sliccy 6.154.5 → 6.154.6
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 +166 -166
- package/dist/ui/assets/{CLAUDE-CWMPcWVI.js → CLAUDE-C4hj5z8T.js} +1 -1
- package/dist/ui/assets/{MEMORY-1jIGxLn4.js → MEMORY-BJp9Ffsq.js} +1 -1
- package/dist/ui/assets/{account-store-QrRg1uSN.js → account-store-6WG1S7Pm.js} +1 -1
- package/dist/ui/assets/{account-store-DqTfhn2_.js → account-store-DZSDFGiY.js} +1 -1
- package/dist/ui/assets/{adobe-B6cbOIZR.js → adobe-CSD_HLUo.js} +1 -1
- package/dist/ui/assets/{adobe-Bea7fu-T.js → adobe-DqY2BLDZ.js} +1 -1
- package/dist/ui/assets/{agent-bridge-CLbiuQFp.js → agent-bridge-D50e_bCg.js} +1 -1
- package/dist/ui/assets/{agent-panels-CrHaxcfP.js → agent-panels-CQCFuU0F.js} +1 -1
- package/dist/ui/assets/{apply-layout-CUdgM9hY.js → apply-layout-DpwYWyCv.js} +1 -1
- package/dist/ui/assets/{apps-CmhTAbmY.js → apps-Cvv2F8Zd.js} +1 -1
- package/dist/ui/assets/{azure-openai-DQvD4JfK.js → azure-openai-BMHNq52P.js} +1 -1
- package/dist/ui/assets/{azure-openai-oNkAJEH9.js → azure-openai-BoKUNg3s.js} +1 -1
- package/dist/ui/assets/{budget-usage-source-DMq3fdAk.js → budget-usage-source-CxT001UE.js} +1 -1
- package/dist/ui/assets/{cdp-CyYrl-r3.js → cdp-DyVyxM9p.js} +1 -1
- package/dist/ui/assets/{cerebras-i6LmJBOw.js → cerebras-BGCRJNZL.js} +1 -1
- package/dist/ui/assets/{cerebras-CLMg0uuV.js → cerebras-Bvb3XQZL.js} +1 -1
- package/dist/ui/assets/{composer-speech-9Zo81K0N.js → composer-speech-CpHom6zE.js} +1 -1
- package/dist/ui/assets/{connect-surface-BfXSOspJ.js → connect-surface-CPqNKSpt.js} +1 -1
- package/dist/ui/assets/{directed-approval-Df9ytmfk.js → directed-approval-Ce8FHRYj.js} +1 -1
- package/dist/ui/assets/{fs-CtNDvIlo.js → fs-BV6duUqj.js} +2 -2
- package/dist/ui/assets/{fs-BiGByget.js → fs-DixtpMlv.js} +1 -1
- package/dist/ui/assets/{github-D753Gf5v.js → github-BK9qY3Dp.js} +2 -2
- package/dist/ui/assets/{github-BNNfDsCz.js → github-J67ogl3l.js} +1 -1
- package/dist/ui/assets/{github-auth-Dah4Bvbq.js → github-auth-DFK3fTyP.js} +1 -1
- package/dist/ui/assets/{github-copilot-B1Ax8Lk3.js → github-copilot-BD3tCMhs.js} +1 -1
- package/dist/ui/assets/{github-copilot-BFeyn-UC.js → github-copilot-utdlw5T2.js} +1 -1
- package/dist/ui/assets/{github-install-NhZ0wUHD.js → github-install-CG84acvy.js} +1 -1
- package/dist/ui/assets/{github-zip-Dl9WuPaB.js → github-zip-Dei-4lGa.js} +1 -1
- package/dist/ui/assets/{hear-Ctqu4qhx.js → hear-gYxFkxil.js} +1 -1
- package/dist/ui/assets/{help-Bw8UwEZ2.js → help-dNszPyQ5.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-w_3ye_7l.js → js-realm-worker-Bnl_qf6X.js} +1 -1
- package/dist/ui/assets/{kernel-worker-Bort6gFm.js → kernel-worker-XuXyPE5D.js} +166 -166
- package/dist/ui/assets/{local-llm-InWZD5_6.js → local-llm-55U-3pMU.js} +1 -1
- package/dist/ui/assets/{local-llm-BB5kQEa2.js → local-llm-BHYcxEqH.js} +1 -1
- package/dist/ui/assets/{main-CpFTnqJu.js → main-DyuWfD9Q.js} +3 -3
- package/dist/ui/assets/{main-cherry-C00FP5cd.js → main-cherry-BzM_BqPA.js} +1 -1
- package/dist/ui/assets/{memory-curation-seam-UdyrM1Mx.js → memory-curation-seam-gS_uRoYt.js} +1 -1
- package/dist/ui/assets/{mount-omsLg2iT.js → mount-CvjPMVSw.js} +3 -3
- package/dist/ui/assets/{mount-CNl3JQQP.js → mount-Drfr_j4Q.js} +1 -1
- package/dist/ui/assets/{mount-recovery-B9S80wQd.js → mount-recovery-Be7iHZMh.js} +1 -1
- package/dist/ui/assets/{new-session-DzHUS_-O.js → new-session-BiudxW5x.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-EjnDaNLY.js → oauth-bootstrap-Ls8bbNTd.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-CasEZ5Ti.js → onboarding-orchestrator-BjNAi3ha.js} +1 -1
- package/dist/ui/assets/{openai-codex-MngNy3OL.js → openai-codex-BqHcjWDm.js} +1 -1
- package/dist/ui/assets/{openai-codex-c9FzyJSx.js → openai-codex-DCoZhGOn.js} +1 -1
- package/dist/ui/assets/{openrouter-58brdWIl.js → openrouter-LWCIZWrE.js} +1 -1
- package/dist/ui/assets/{openrouter-CTU-VUZU.js → openrouter-XQsjur8s.js} +1 -1
- package/dist/ui/assets/{openrouter-free-Cw45OIqu.js → openrouter-free-CiD2N3nW.js} +1 -1
- package/dist/ui/assets/{openrouter-free-B1pQjdc9.js → openrouter-free-W8i93TBB.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BVyZ9RG4.js → openrouter-oauth-C2jnsYYB.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-S-co-_BE.js → openrouter-oauth-DUHOu5QH.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-D_G7IsL-.js → panel-rpc-handlers-DokKsJYg.js} +2 -2
- package/dist/ui/assets/{panelize-shell-dRR-gQQ4.js → panelize-shell-DbP4SDhf.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-DzlJRvzD.js → pi-edit-execution-DYRoRikS.js} +1 -1
- package/dist/ui/assets/{provider-CeNevkik.js → provider-B5DqJTXt.js} +1 -1
- package/dist/ui/assets/{provider-D-5WiTrV.js → provider-el781haf.js} +2 -2
- package/dist/ui/assets/provider-settings-D8F77Xhh.js +1 -0
- package/dist/ui/assets/provider-store-access-Bbm8UQlA.js +1 -0
- package/dist/ui/assets/provider-store-access-DP_iz1Q0.js +1 -0
- package/dist/ui/assets/{providers-JVYHxTrW.js → providers-BHgR4i3z.js} +2 -2
- package/dist/ui/assets/{providers-CZoy8wMj.js → providers-DuCgei7-.js} +1 -1
- package/dist/ui/assets/{quick-llm-BrhzKZyf.js → quick-llm-BxSQl3MP.js} +1 -1
- package/dist/ui/assets/{recovery-screen-Dm_Ys4T5.js → recovery-screen-zniAEHuE.js} +1 -1
- package/dist/ui/assets/{run-CfuM1xwa.js → run-C5mIkEGQ.js} +1 -1
- package/dist/ui/assets/run-CuXkU2qx.js +3 -0
- package/dist/ui/assets/{run-D-ptdMRR.js → run-Dckyjx6-.js} +2 -2
- package/dist/ui/assets/{run-Da4WIBP4.js → run-DnO5hH4e.js} +1 -1
- package/dist/ui/assets/{session-jsonl-Be97cQdP.js → session-jsonl-CWhJWPOK.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-D47pV_MM.js → setup-feature-flags-remote-qB-mSMUq.js} +1 -1
- package/dist/ui/assets/sidecar-repair-dj57y-8O.js +1 -0
- package/dist/ui/assets/{silent-renew-backoff-Cynzp3bE.js → silent-renew-backoff-C251JX1S.js} +1 -1
- package/dist/ui/assets/{skills-DoZg-ojy.js → skills-BtA0WqTn.js} +1 -1
- package/dist/ui/assets/slicc-version-42Jn19Ww.js +1 -0
- package/dist/ui/assets/{snapshot-DZQ1apX-.js → snapshot-C2775cOf.js} +1 -1
- package/dist/ui/assets/{snapshot-features-DVyd7MCD.js → snapshot-features-ChEbT7az.js} +1 -1
- package/dist/ui/assets/{soundscape-BMwJ3NUw.js → soundscape-dXwPqTJ-.js} +1 -1
- package/dist/ui/assets/{speak-1sadgIHv.js → speak-cpgcfooI.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-D6Qrwdww.js → sprinkle-manager-jd6a2IYN.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-Pg2SqEAJ.js → sprinkle-renderer-Br7gWsny.js} +1 -1
- package/dist/ui/assets/{state-DA5Ppyx-.js → state-C1XZTzHt.js} +1 -1
- package/dist/ui/assets/{store-JtuNg-ld.js → store-CxD6rJNd.js} +1 -1
- package/dist/ui/assets/{store-BIDY4hVD.js → store-D0akwt8a.js} +1 -1
- package/dist/ui/assets/{sudo-BAvTUS5b.js → sudo-Ng9MeLFC.js} +1 -1
- package/dist/ui/assets/{sync-dialog-B22MjR-Y.js → sync-dialog-g9D5_IF8.js} +1 -1
- package/dist/ui/assets/{transformers-env-Dbzm2zOd.js → transformers-env-ClNwGCkj.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-DfQxtpAU.js → tray-sidecar-B0K5KzF-.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-B0CnEfsD.js → upgrade-detection-Cz-hPWu6.js} +1 -1
- package/dist/ui/assets/{upskill-lick-skip-Dkrc8SQj.js → upskill-lick-skip-Coa1zDvD.js} +1 -1
- package/dist/ui/assets/{voice-reply-hxJpzo4Z.js → voice-reply-BTnXYrYT.js} +1 -1
- package/dist/ui/assets/{wc-attach-B-RwMKh4.js → wc-attach-CjRJwFv_.js} +2 -2
- package/dist/ui/assets/{wc-extension-BzgY7Ay5.js → wc-extension-zyJvXHK3.js} +2 -2
- package/dist/ui/assets/{wc-follower-RmDJj3vx.js → wc-follower-Dm1EanME.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-CzL_YM3W.js → wc-follower-oauth-CIiFOuDi.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-DMO16qkW.js → wc-gelatiere-Cy9jod1J.js} +1 -1
- package/dist/ui/assets/{wc-live-C1fkW0oh.js → wc-live-JCXonoSm.js} +6 -6
- package/dist/ui/assets/{wc-nav-EBobpmc0.js → wc-nav-CRD8N4xt.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-sry3pJ3v.js → wc-onboarding-BXeb4TbL.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-yiwnKVQh.js → wc-placeholder-BY85O4B6.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-DR5a7SVR.js → wc-secret-request-yPyZt78A.js} +1 -1
- package/dist/ui/assets/{wc-settings-BB5MYHf5.js → wc-settings-BHJBZGEl.js} +3 -3
- package/dist/ui/assets/{wc-shell-DMzpB1X4.js → wc-shell-CfRSHqBD.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-CutoJlLo.js → wc-shortcut-config-cEwRH43m.js} +1 -1
- package/dist/ui/assets/{wc-shortcuts-Db5RFxfY.js → wc-shortcuts-C6T4EYNZ.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-CyZsTtq7.js → wc-sprinkles-6kq8ChrP.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-Bkn8aEFu.js → wc-transcript-export-vCgK8B1Y.js} +2 -2
- package/dist/ui/assets/{wc-tray-6uck1DGP.js → wc-tray-GsvwH8iN.js} +4 -4
- package/dist/ui/assets/welcome-detection-BAEGrqo6.js +1 -0
- package/dist/ui/assets/{whisper-session-BNYJek9P.js → whisper-session-C6BRUKHG.js} +2 -2
- package/dist/ui/assets/{xai-grok-CaMqKb8o.js → xai-grok-Bpe_qjy3.js} +1 -1
- package/dist/ui/assets/{xai-grok-DcM2TX44.js → xai-grok-DlnOMaxU.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-CseKsTkN.js +0 -1
- package/dist/ui/assets/provider-store-access-B8K7spUZ.js +0 -1
- package/dist/ui/assets/provider-store-access-Cr4NjO-D.js +0 -1
- package/dist/ui/assets/sidecar-repair-9M_U9-Iy.js +0 -1
- package/dist/ui/assets/slicc-version-7PkoDMIu.js +0 -1
- package/dist/ui/assets/welcome-detection-DsUV5zMq.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-DZQ1apX-.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{n as p,r as m,t as h}from"./feature-flags-BIRXJe0o.js";import{a as g,t as _}from"./providers-CZoy8wMj.js";import{r as v,t as y}from"./base64-DzRgusa4.js";import{n as b}from"./bridge-protocol-DdqxTTSu.js";import{t as x}from"./content-type-_QKWY0B2.js";import{a as S,c as C,i as w,l as T,o as E,r as D,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as O,d as ie,f as ae,g as oe,h as se,i as ce,m as le,p as ue,u as de,v as fe,x as pe,y as k}from"./account-store-QrRg1uSN.js";import{a as me,l as he,n as ge,o as _e}from"./proxied-fetch-DEK8DT-z.js";import{t as ve}from"./runtime-env-DadgceZk.js";import{t as ye}from"./slugify-BYJ6QVAt.js";import{i as be}from"./archive-redaction-ByV7X5fs.js";import{r as xe}from"./binary-cache-bSOhqXB1.js";import{i as Se,n as A,r as j,t as Ce}from"./fetch-body-CuwTaJC_.js";import{a as we,l as M,o as Te,s as N,t as Ee,u as P}from"./api-endpoint-3qEcn7BY.js";import{$ as F,A as De,At as Oe,B as ke,C as Ae,Ct as I,D as je,Dt as Me,E as Ne,Et as Pe,F as Fe,H as Ie,I as Le,J as Re,K as ze,L as Be,M as Ve,Mt as L,N as He,Nt as Ue,O as We,Ot as Ge,P as Ke,Q as qe,R as Je,St as eee,T as Ye,Tt as Xe,U as Ze,V as Qe,W as $e,X as et,Y as tt,Z as nt,_ as rt,_t as it,a as at,at as ot,b as st,bt as ct,c as lt,ct as R,d as ut,dt as tee,et as dt,f as ft,ft as pt,g as mt,gt as ht,h as gt,ht as _t,i as vt,it as yt,j as bt,jt as xt,k as St,kt as Ct,l as nee,lt as wt,m as Tt,mt as Et,n as Dt,nt as Ot,o as kt,ot as At,p as jt,pt as z,q as Mt,r as Nt,rt as Pt,s as Ft,st as B,t as ree,tt as It,u as iee,ut as Lt,v as Rt,vt as zt,w as Bt,wt as Vt,x as Ht,xt as Ut,y as Wt,yt as Gt,z as Kt}from"./build-BRNa03GH.js";import{a as qt}from"./models-4WTk3EBD.js";import{o as Jt,t as Yt}from"./compat-uEPf6-XW.js";import{a as Xt,c as Zt,i as Qt,l as $t,o as en,s as tn,t as nn,u as rn}from"./core-DP-MJcag.js";import{t as aee}from"./__vite-browser-external-5eBdwsFd.js";import{n as oee,r as see}from"./attachments-u2K0aIPI.js";import{i as an,n as on,r as sn,t as cn}from"./context-compaction-DRymamfD.js";import{n as ln,t as un}from"./mime-types-D7IV6i7k.js";import{t as dn}from"./secrets-bridge-client-ZpBL1Zhl.js";import{t as fn}from"./image-markers-DuyWsic3.js";import{i as pn,r as mn}from"./budget-usage-source-DMq3fdAk.js";import{a as hn,i as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{a as yn,i as bn,o as xn,r as Sn,t as Cn}from"./agent-bridge-CLbiuQFp.js";import{A as wn,C as Tn,D as En,E as Dn,S as On,T as kn,_ as An,a as jn,c as Mn,d as Nn,f as Pn,g as Fn,h as In,k as cee,l as Ln,m as Rn,n as zn,o as Bn,p as lee,r as uee,s as Vn,t as dee,u as Hn,v as fee,w as pee,y as mee}from"./record-YqlVEfh_.js";import{c as Un,d as Wn,i as Gn,l as Kn,n as qn,o as Jn,r as Yn,s as Xn,u as Zn}from"./descriptor-D-6Koktu.js";import{a as Qn,c as $n,i as er,l as tr,o as nr,r as rr,s as ir,u as ar}from"./agent-message-to-chat-w7n13QEN.js";import{n as or,t as sr}from"./thinking-level-5x0UAu9N.js";import{n as cr,t as lr}from"./types-Dgm4REV3.js";import{i as ur}from"./mount-index-D9w_zMSm.js";import{a as dr,c as fr,i as pr,l as mr,n as hr,o as gr,r as _r,s as vr,u as yr}from"./mount-CNl3JQQP.js";import{o as br}from"./mount-table-store-DrF_Ifaz.js";import{t as xr}from"./remote-cache-BE5T1-53.js";import{i as Sr,n as Cr,r as wr}from"./fs-BiGByget.js";import{r as Tr,t as Er}from"./mount-recovery-B9S80wQd.js";import{r as Dr,t as Or}from"./key-DExP84Xm.js";import{n as kr,t as Ar}from"./manager-CstXzWYQ.js";import{a as jr,c as Mr,i as Nr,n as Pr,o as Fr,r as Ir,s as Lr}from"./lick-urls-BZVq_P3x.js";import{C as Rr,D as zr,E as Br,S as Vr,_ as Hr,a as Ur,b as Wr,d as Gr,g as Kr,h as qr,m as Jr,n as Yr,o as Xr,r as Zr,s as Qr,t as $r,u as hee,w as ei,y as gee}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-CRZxBChd.js";import{n as ti,r as _ee,t as vee}from"./slicc-version-7PkoDMIu.js";import{a as ni,i as yee,n as V,r as ri,t as bee}from"./browser-BxGToOGy.js";import{t as H}from"./subcommand-flags-BZi7j78Q.js";import{n as ii,r as ai,t as oi}from"./subcommand-help-CgO7wRS5.js";import{a as xee,i as See,n as Cee,r as wee}from"./cost-command-BzdZ_evm.js";import{a as Tee,c as si,d as Eee,f as ci,h as li,i as Dee,l as ui,m as di,n as fi,o as pi,p as mi,r as hi,s as gi,t as _i,u as vi}from"./sudoers-KgJRnN4b.js";import{a as yi,i as bi,n as xi,o as Si,r as Ci,s as wi}from"./skills-DoZg-ojy.js";import{a as Ti,c as Ei,i as Di,l as Oi,n as ki,o as Ai,r as ji,t as Mi}from"./types-BfwydWt7.js";import{n as Ni,t as Pi}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as Fi}from"./html-B_Hg2WOy.js";import{n as Ii,t as Li}from"./llm-session-id-BZyXP_j2.js";import{a as Ri}from"./frozen-archive-format-B4efpvB9.js";import{n as zi,r as Bi}from"./derive-BqbmiIL9.js";import{n as Vi,t as Hi}from"./cone-memory-budget-ieIsscyt.js";import{i as Ui,r as Wi}from"./browser-2rCVqcqy.js";import{a as Gi}from"./gelatiere-constants-BYJlhm8R.js";import{n as Ki,t as qi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ji,_ as Yi,a as Xi,b as Zi,c as Qi,d as $i,f as ea,g as ta,h as na,i as ra,l as ia,n as aa,o as oa,p as sa,r as ca,s as la,t as ua,u as da,v as U,x as fa,y as pa}from"./state-DA5Ppyx-.js";import{a as ma,i as ha,r as ga,t as _a}from"./git-config-Bdgu8kD2.js";import{a as va,c as ya,i as ba,o as xa,r as Sa,s as Ca,t as wa}from"./script-catalog-Bt94D0RP.js";import{t as Ta}from"./process-manager-BkhAohXT.js";import{A as Ea,C as Da,F as Oa,I as ka,N as Aa,P as ja,_ as Ma,a as Na,b as Pa,c as Fa,d as Ia,f as La,g as Ra,h as za,i as Ba,j as Va,l as Ha,m as Ua,n as Wa,o as Ga,p as Ka,r as qa,s as Ja,t as Ya,u as Xa,v as Za,x as Qa,y as $a}from"./shared-C_68vn79.js";import{t as eo}from"./tmpdir-env-ate4iNcK.js";import{t as to}from"./realm-browser-fetch-V3uggGbM.js";import{n as no,t as ro}from"./esbuild-wasm-DS_YG2EY.js";import{n as io,t as ao}from"./wasm-compiler-Ct7QZURL.js";import{a as oo,i as so,n as co,o as lo,s as uo,t as fo}from"./usb-device-registry-DFzxaOky.js";import{n as po,r as mo,t as ho}from"./just-bash-compat-_TMo8UnL.js";import{a as go,c as _o,o as vo,s as yo,t as bo}from"./types-Dzr0qYl3.js";import{a as xo,c as So,d as Co,f as wo,n as To,r as Eo,u as Do}from"./github-zip-Dl9WuPaB.js";import{i as Oo,t as ko}from"./github-auth-Dah4Bvbq.js";import{a as Ao,i as jo,o as Mo,r as No,t as Oee}from"./provenance-DdmsQ3Nr.js";import{a as Po,c as Fo,i as Io,n as Lo,o as Ro,r as zo,s as kee}from"./github-install-NhZ0wUHD.js";import{n as Aee,t as jee}from"./magick-wasm-DCNZhAyd.js";import{i as Mee,n as Bo,r as Nee,t as Vo}from"./pdf-raster-BWk6ezTX.js";import{n as Ho,t as Pee}from"./lick-target-env-8JxfVcIV.js";import{a as Fee,c as Iee,d as Lee,f as Ree,i as zee,l as Bee,n as Vee,o as Hee,p as Uee,r as Uo,s as Wee,t as Gee,u as Kee}from"./installer-D4WxHb-C.js";import{n as Wo,r as Go,t as qee}from"./extension-media-capture-CRjN0St9.js";import{t as Jee}from"./local-llm-InWZD5_6.js";import{t as Yee}from"./client-B6iKb_ye.js";import{t as Xee}from"./redirect-uri-CgKdq7-K.js";import{t as Zee}from"./write-verification-BOaZdtyk.js";let Ko=null;function Qee(e){Ko=e!==null&&Number.isFinite(e)&&e>0?e:null}function $ee(){if(Ko!==null)return Ko;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const ete=[`/workspace`,`/shared`,`/scoops`,`/home`];var qo=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function Jo(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Yo=r(`cdp`);function tte(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 nte=class{ws=null;nextId=1;_superseded=!1;pending=new qo;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,Yo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Yo.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(),Yo.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),Yo.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return Jo(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Yo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Yo.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;Yo.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,Yo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Yo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Yo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(tte(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{}}}},Xo=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 Zo(e,t){if(e?.aborted)throw new Xo(t)}function rte(e,t){return e?{signal:e,error:()=>new Xo(t)}:void 0}function ite(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Xo(n));return}let a=()=>{clearTimeout(o),i(new Xo(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ate(e,t,n){return t?t.aborted?Promise.reject(new Xo(n)):new Promise((r,i)=>{let a=()=>i(new Xo(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 Qo=r(`har-recorder`);var ote=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)}`;Zo(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Zo(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Zo(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}`),Qo.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=>{Qo.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=>{Qo.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 ste(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Qo.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 Qo.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)),Qo.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 Qo.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 ste(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){Qo.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Qo.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const $o=`(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-C2775cOf.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{n as p,r as m,t as h}from"./feature-flags-BIRXJe0o.js";import{a as g,t as _}from"./providers-DuCgei7-.js";import{r as v,t as y}from"./base64-DzRgusa4.js";import{n as b}from"./bridge-protocol-DdqxTTSu.js";import{t as x}from"./content-type-_QKWY0B2.js";import{a as S,c as C,i as w,l as T,o as E,r as D,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as O,d as ie,f as ae,g as oe,h as se,i as ce,m as le,p as ue,u as de,v as fe,x as pe,y as k}from"./account-store-6WG1S7Pm.js";import{a as me,l as he,n as ge,o as _e}from"./proxied-fetch-DEK8DT-z.js";import{t as ve}from"./runtime-env-DadgceZk.js";import{t as ye}from"./slugify-BYJ6QVAt.js";import{i as be}from"./archive-redaction-ByV7X5fs.js";import{r as xe}from"./binary-cache-bSOhqXB1.js";import{i as Se,n as A,r as j,t as Ce}from"./fetch-body-CuwTaJC_.js";import{a as we,l as M,o as Te,s as N,t as Ee,u as P}from"./api-endpoint-3qEcn7BY.js";import{$ as F,A as De,At as Oe,B as ke,C as Ae,Ct as I,D as je,Dt as Me,E as Ne,Et as Pe,F as Fe,H as Ie,I as Le,J as Re,K as ze,L as Be,M as Ve,Mt as L,N as He,Nt as Ue,O as We,Ot as Ge,P as Ke,Q as qe,R as Je,St as eee,T as Ye,Tt as Xe,U as Ze,V as Qe,W as $e,X as et,Y as tt,Z as nt,_ as rt,_t as it,a as at,at as ot,b as st,bt as ct,c as lt,ct as R,d as ut,dt as tee,et as dt,f as ft,ft as pt,g as mt,gt as ht,h as gt,ht as _t,i as vt,it as yt,j as bt,jt as xt,k as St,kt as Ct,l as nee,lt as wt,m as Tt,mt as Et,n as Dt,nt as Ot,o as kt,ot as At,p as jt,pt as z,q as Mt,r as Nt,rt as Pt,s as Ft,st as B,t as ree,tt as It,u as iee,ut as Lt,v as Rt,vt as zt,w as Bt,wt as Vt,x as Ht,xt as Ut,y as Wt,yt as Gt,z as Kt}from"./build-BRNa03GH.js";import{a as qt}from"./models-4WTk3EBD.js";import{o as Jt,t as Yt}from"./compat-uEPf6-XW.js";import{a as Xt,c as Zt,i as Qt,l as $t,o as en,s as tn,t as nn,u as rn}from"./core-DP-MJcag.js";import{t as aee}from"./__vite-browser-external-5eBdwsFd.js";import{n as oee,r as see}from"./attachments-u2K0aIPI.js";import{i as an,n as on,r as sn,t as cn}from"./context-compaction-DRymamfD.js";import{n as ln,t as un}from"./mime-types-D7IV6i7k.js";import{t as dn}from"./secrets-bridge-client-ZpBL1Zhl.js";import{t as fn}from"./image-markers-DuyWsic3.js";import{i as pn,r as mn}from"./budget-usage-source-CxT001UE.js";import{a as hn,i as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{a as yn,i as bn,o as xn,r as Sn,t as Cn}from"./agent-bridge-D50e_bCg.js";import{A as wn,C as Tn,D as En,E as Dn,S as On,T as kn,_ as An,a as jn,c as Mn,d as Nn,f as Pn,g as Fn,h as In,k as cee,l as Ln,m as Rn,n as zn,o as Bn,p as lee,r as uee,s as Vn,t as dee,u as Hn,v as fee,w as pee,y as mee}from"./record-YqlVEfh_.js";import{c as Un,d as Wn,i as Gn,l as Kn,n as qn,o as Jn,r as Yn,s as Xn,u as Zn}from"./descriptor-D-6Koktu.js";import{a as Qn,c as $n,i as er,l as tr,o as nr,r as rr,s as ir,u as ar}from"./agent-message-to-chat-w7n13QEN.js";import{n as or,t as sr}from"./thinking-level-5x0UAu9N.js";import{n as cr,t as lr}from"./types-Dgm4REV3.js";import{i as ur}from"./mount-index-D9w_zMSm.js";import{a as dr,c as fr,i as pr,l as mr,n as hr,o as gr,r as _r,s as vr,u as yr}from"./mount-Drfr_j4Q.js";import{o as br}from"./mount-table-store-DrF_Ifaz.js";import{t as xr}from"./remote-cache-BE5T1-53.js";import{i as Sr,n as Cr,r as wr}from"./fs-DixtpMlv.js";import{r as Tr,t as Er}from"./mount-recovery-Be7iHZMh.js";import{r as Dr,t as Or}from"./key-DExP84Xm.js";import{n as kr,t as Ar}from"./manager-CstXzWYQ.js";import{a as jr,c as Mr,i as Nr,n as Pr,o as Fr,r as Ir,s as Lr}from"./lick-urls-BZVq_P3x.js";import{C as Rr,D as zr,E as Br,S as Vr,_ as Hr,a as Ur,b as Wr,d as Gr,g as Kr,h as qr,m as Jr,n as Yr,o as Xr,r as Zr,s as Qr,t as $r,u as hee,w as ei,y as gee}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-CRZxBChd.js";import{n as ti,r as _ee,t as vee}from"./slicc-version-42Jn19Ww.js";import{a as ni,i as yee,n as V,r as ri,t as bee}from"./browser-BxGToOGy.js";import{t as H}from"./subcommand-flags-BZi7j78Q.js";import{n as ii,r as ai,t as oi}from"./subcommand-help-CgO7wRS5.js";import{a as xee,i as See,n as Cee,r as wee}from"./cost-command-BzdZ_evm.js";import{a as Tee,c as si,d as Eee,f as ci,h as li,i as Dee,l as ui,m as di,n as fi,o as pi,p as mi,r as hi,s as gi,t as _i,u as vi}from"./sudoers-KgJRnN4b.js";import{a as yi,i as bi,n as xi,o as Si,r as Ci,s as wi}from"./skills-BtA0WqTn.js";import{a as Ti,c as Ei,i as Di,l as Oi,n as ki,o as Ai,r as ji,t as Mi}from"./types-BfwydWt7.js";import{n as Ni,t as Pi}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as Fi}from"./html-B_Hg2WOy.js";import{n as Ii,t as Li}from"./llm-session-id-BZyXP_j2.js";import{a as Ri}from"./frozen-archive-format-B4efpvB9.js";import{n as zi,r as Bi}from"./derive-BqbmiIL9.js";import{n as Vi,t as Hi}from"./cone-memory-budget-ieIsscyt.js";import{i as Ui,r as Wi}from"./browser-2rCVqcqy.js";import{a as Gi}from"./gelatiere-constants-BYJlhm8R.js";import{n as Ki,t as qi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ji,_ as Yi,a as Xi,b as Zi,c as Qi,d as $i,f as ea,g as ta,h as na,i as ra,l as ia,n as aa,o as oa,p as sa,r as ca,s as la,t as ua,u as da,v as U,x as fa,y as pa}from"./state-C1XZTzHt.js";import{a as ma,i as ha,r as ga,t as _a}from"./git-config-Bdgu8kD2.js";import{a as va,c as ya,i as ba,o as xa,r as Sa,s as Ca,t as wa}from"./script-catalog-Bt94D0RP.js";import{t as Ta}from"./process-manager-BkhAohXT.js";import{A as Ea,C as Da,F as Oa,I as ka,N as Aa,P as ja,_ as Ma,a as Na,b as Pa,c as Fa,d as Ia,f as La,g as Ra,h as za,i as Ba,j as Va,l as Ha,m as Ua,n as Wa,o as Ga,p as Ka,r as qa,s as Ja,t as Ya,u as Xa,v as Za,x as Qa,y as $a}from"./shared-C_68vn79.js";import{t as eo}from"./tmpdir-env-ate4iNcK.js";import{t as to}from"./realm-browser-fetch-V3uggGbM.js";import{n as no,t as ro}from"./esbuild-wasm-DS_YG2EY.js";import{n as io,t as ao}from"./wasm-compiler-Ct7QZURL.js";import{a as oo,i as so,n as co,o as lo,s as uo,t as fo}from"./usb-device-registry-DFzxaOky.js";import{n as po,r as mo,t as ho}from"./just-bash-compat-_TMo8UnL.js";import{a as go,c as _o,o as vo,s as yo,t as bo}from"./types-Dzr0qYl3.js";import{a as xo,c as So,d as Co,f as wo,n as To,r as Eo,u as Do}from"./github-zip-Dei-4lGa.js";import{i as Oo,t as ko}from"./github-auth-DFK3fTyP.js";import{a as Ao,i as jo,o as Mo,r as No,t as Oee}from"./provenance-DdmsQ3Nr.js";import{a as Po,c as Fo,i as Io,n as Lo,o as Ro,r as zo,s as kee}from"./github-install-CG84acvy.js";import{n as Aee,t as jee}from"./magick-wasm-DCNZhAyd.js";import{i as Mee,n as Bo,r as Nee,t as Vo}from"./pdf-raster-BWk6ezTX.js";import{n as Ho,t as Pee}from"./lick-target-env-8JxfVcIV.js";import{a as Fee,c as Iee,d as Lee,f as Ree,i as zee,l as Bee,n as Vee,o as Hee,p as Uee,r as Uo,s as Wee,t as Gee,u as Kee}from"./installer-D4WxHb-C.js";import{n as Wo,r as Go,t as qee}from"./extension-media-capture-CRjN0St9.js";import{t as Jee}from"./local-llm-55U-3pMU.js";import{t as Yee}from"./client-B6iKb_ye.js";import{t as Xee}from"./redirect-uri-CgKdq7-K.js";import{t as Zee}from"./write-verification-BOaZdtyk.js";let Ko=null;function Qee(e){Ko=e!==null&&Number.isFinite(e)&&e>0?e:null}function $ee(){if(Ko!==null)return Ko;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const ete=[`/workspace`,`/shared`,`/scoops`,`/home`];var qo=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function Jo(e,t,n,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(r.error());return}let o=null,s=!1,c,l=()=>{s=!0,clearTimeout(u),c&&r?.signal?.removeEventListener(`abort`,c),o?.()},u=setTimeout(()=>{l(),a(Error(n))},t);r?.signal&&(c=()=>{l(),a(r.error())},r.signal.addEventListener(`abort`,c,{once:!0})),o=e(e=>{l(),i(e)}),s&&o()})}const Yo=r(`cdp`);function tte(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 nte=class{ws=null;nextId=1;_superseded=!1;pending=new qo;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,Yo.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Yo.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(),Yo.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),Yo.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return Jo(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Yo.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Yo.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;Yo.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,Yo.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?Yo.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):Yo.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(tte(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{}}}},Xo=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 Zo(e,t){if(e?.aborted)throw new Xo(t)}function rte(e,t){return e?{signal:e,error:()=>new Xo(t)}:void 0}function ite(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new Xo(n));return}let a=()=>{clearTimeout(o),i(new Xo(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ate(e,t,n){return t?t.aborted?Promise.reject(new Xo(n)):new Promise((r,i)=>{let a=()=>i(new Xo(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 Qo=r(`har-recorder`);var ote=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)}`;Zo(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),Zo(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),Zo(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}`),Qo.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=>{Qo.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=>{Qo.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 ste(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Qo.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 Qo.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)),Qo.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 Qo.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 ste(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){Qo.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Qo.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const $o=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -974,7 +974,7 @@ Write /etc/models
|
|
|
974
974
|
`,1)[0]?.trim()===`# Per-scoop sudoers — generated from ScoopConfig (sandbox surface).`&&(await this.fs.writeFile(n,lb),rb.info(`Discarded legacy generated per-scoop sudoers (ambiguous rules, fail-closed)`,{folder:e,path:n})),await this.reloadScoopPolicy(e)}async appendScoopRule(e,t,n){let r=di(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=li(e),o=``;try{if(await this.fs.exists(a)){let e=await this.fs.readFile(a,{encoding:`utf-8`});o=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}let s=`NOPASSWD ${i} ${r}`;if(o.split(`
|
|
975
975
|
`).some(e=>e.trim()===s))return rb.info(`Per-scoop sudoers rule already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(`/scoops/${e}/etc`,{recursive:!0})}catch{}let c=o?o.endsWith(`
|
|
976
976
|
`)?o:`${o}\n`:lb;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),rb.info(`Appended per-scoop sudoers rule`,{folder:e,kind:t,pattern:r}),r}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}forgetScoopPolicies(e){this.scoopConfigPolicies.delete(e),this.scoopPolicies.delete(e),this.scoopReloadChains.delete(e),this.onPolicyReload(e)}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null,this.scoopUnwatch?.(),this.scoopUnwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=li(e);try{if(!await this.fs.exists(t)){this.scoopPolicies.delete(e),this.onPolicyReload(e);return}}catch{this.scoopPolicies.delete(e),this.onPolicyReload(e);return}this.scoopPolicies.set(e,await this.readPolicyFile(t)),this.onPolicyReload(e)}async doReload(){let e=[await this.readPolicyFile(hi)];try{let t=(await this.fs.readDir(fi)).filter(e=>e.type===`file`).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${fi}/${n}`))}catch{}this.policy=ci(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return si();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return mi(n)}catch(t){return rb.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),si()}}async ensureDefaults(){try{await this.fs.mkdir(fi,{recursive:!0})}catch{}await this.seedWhenAbsent(hi,()=>Dy),await this.seedWhenAbsent(_i,async()=>(await import(`./approver-agent-BA3dC9Lg.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),rb.info(`Seeded bundled policy default`,{path:e})}catch(t){rb.warn(`Failed to seed bundled policy default`,{path:e,error:t instanceof Error?t.message:String(t)})}}persistCommandGrant(e){return this.persistGrant(`Cmnd`,e)}async persistGrant(e,t){let n=di(t);if(!n)return;let r=``;try{if(await this.fs.exists(Ci)){let e=await this.fs.readFile(Ci,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(fi,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
|
|
977
|
-
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Ci,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,ib,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,ob,e=>{let t=new Set;for(let n of e){let e=sb(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let fb=null;function pb(e){return fb=e,()=>{fb===e&&(fb=null)}}function mb(){if(!fb)throw new Vs(`session-not-found`);return fb}function hb(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function gb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _b(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)_b(e[r],`${t}/${r}`,n);return}if(gb(e))for(let[r,i]of Object.entries(e))_b(i,`${t}/${hb(r)}`,n)}function vb(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=vb(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(gb(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=vb(o,`${t}/${hb(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function yb(e,t,n){if(gb(e))return vb(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=yb(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function bb(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function xb(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new Vs(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new Vs(`redaction-unavailable`)}if(c.length!==s.length)throw new Vs(`redaction-unavailable`);r.push(...c),i=o}return r}function Sb(e,t,n,r){let i=[],a=bb(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=bb(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=be(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function Cb(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function wb(e,t,n,r){if(r?.aborted)throw new Vs(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];_b(a,``,o);let s=o.filter(e=>!Bs(e.pointer)),c=[...t.entries()],l=await xb([...s.map(e=>e.value),...c.map(([,e])=>e)],n,r),u=[],d={},f=1,p=new Map,m=[];for(let e=0;e<s.length;e++){let t=s[e],n=Sb(t.value,l[e],{kind:`json`,pointer:t.pointer},f);f=n.nextId,n.finalText!==t.value&&p.set(t.pointer,n.finalText),m.push(n)}Cb(m,u,d);let h=new Map,g=s.length,_=[];for(let e=0;e<c.length;e++){let[t,n]=c[e],r=Sb(n,l[g+e],{kind:`attachment`,attachmentId:t},f);f=r.nextId,h.set(t,r.finalText),_.push(r)}Cb(_,u,d);let v=yb(e,``,p);return{document:{...v,privacy:{...v.privacy,redactionCounts:d,redactions:u}},textAttachments:h}}function Tb(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function Eb(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Db={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function Ob(e,t){return Db[e]??(t===`text-redacted`?`.txt`:`.bin`)}function kb(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${Ob(t,n)}`}function Ab(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}function jb(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function Mb(e,t,n,r,i){let a=Tb(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(Ab(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=Ab(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function Nb(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:Ab(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(Mb(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Pb(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function Fb(e,t,n,r,i,a,o){let s=Pb(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(Mb(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function Ib(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=Fb(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Lb(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,kb(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function Rb(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Lb(e,n),s,c;try{let e=await wb({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof Vs?e:new Vs(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new Vs(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new Vs(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Eb(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function zb(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=Nb(jb(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=Ib(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await Rb(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function Bb(e){return zn(e)}function Vb(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function Hb(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:Tn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Tn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=Bb(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Ub(e,t,n={}){let r=e=>n.rootJid===void 0?e:En(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new Vs(`transfer-aborted`);let i=Vb(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new Vs(`transfer-aborted`);let s=r(e.listScoops());if(i===Vb(s,e))return Hb(s,a,o,e)}}function Wb(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Gb(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function Kb(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Gb(t,r++));return n}function qb(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Gb(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Jb(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Gb(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Yb(e,t,n){let r=Wb(t,n),i=Kb(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function Xb(e,t,n){let r=Wb(t,n),{blocks:i,excluded:a,images:o}=qb(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function Zb(e,t,n){let r=Wb(t,n),{blocks:i,images:a}=Jb(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function Qb(e,t,n){return e.role===`user`?Yb(e,t,n):e.role===`assistant`?Xb(e,t,n):e.role===`toolResult`?Zb(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function $b(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function ex(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=Qb(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:$b(e),excludedReasoningBlocks:t,canonicalImages:n}}var tx=`input is invalid type`,nx=`finalize already called`,rx=typeof ArrayBuffer<`u`,ix=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(rx&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(tx)},q=`0123456789abcdef`.split(``),ax=[-2147483648,8388608,32768,128],ox=[24,16,8,0],sx=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cx=[`hex`,`array`,`digest`,`arrayBuffer`],lx=[],ux=function(e,t){return function(n){return new mx(t,!0).update(n)[e]()}},dx=function(e){var t=ux(`hex`,e);t.create=function(){return new mx(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<cx.length;++n){var r=cx[n];t[r]=ux(r,e)}return t},fx=function(e,t){return function(n,r){return new hx(n,t,!0).update(r)[e]()}},px=function(e){var t=fx(`hex`,e);t.create=function(t){return new hx(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<cx.length;++n){var r=cx[n];t[r]=fx(r,e)}return t};function mx(e,t){t?(lx[0]=lx[16]=lx[1]=lx[2]=lx[3]=lx[4]=lx[5]=lx[6]=lx[7]=lx[8]=lx[9]=lx[10]=lx[11]=lx[12]=lx[13]=lx[14]=lx[15]=0,this.blocks=lx):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}mx.prototype.update=function(e){if(this.finalized)throw Error(nx);var t=ix(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<ox[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<ox[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<ox[a++&3],s[a>>>2]|=(128|r>>>12&63)<<ox[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<ox[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},mx.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=ax[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},mx.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+sx[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+sx[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+sx[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+sx[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},mx.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=q[e>>>28&15]+q[e>>>24&15]+q[e>>>20&15]+q[e>>>16&15]+q[e>>>12&15]+q[e>>>8&15]+q[e>>>4&15]+q[e&15]+q[t>>>28&15]+q[t>>>24&15]+q[t>>>20&15]+q[t>>>16&15]+q[t>>>12&15]+q[t>>>8&15]+q[t>>>4&15]+q[t&15]+q[n>>>28&15]+q[n>>>24&15]+q[n>>>20&15]+q[n>>>16&15]+q[n>>>12&15]+q[n>>>8&15]+q[n>>>4&15]+q[n&15]+q[r>>>28&15]+q[r>>>24&15]+q[r>>>20&15]+q[r>>>16&15]+q[r>>>12&15]+q[r>>>8&15]+q[r>>>4&15]+q[r&15]+q[i>>>28&15]+q[i>>>24&15]+q[i>>>20&15]+q[i>>>16&15]+q[i>>>12&15]+q[i>>>8&15]+q[i>>>4&15]+q[i&15]+q[a>>>28&15]+q[a>>>24&15]+q[a>>>20&15]+q[a>>>16&15]+q[a>>>12&15]+q[a>>>8&15]+q[a>>>4&15]+q[a&15]+q[o>>>28&15]+q[o>>>24&15]+q[o>>>20&15]+q[o>>>16&15]+q[o>>>12&15]+q[o>>>8&15]+q[o>>>4&15]+q[o&15];return this.is224||(c+=q[s>>>28&15]+q[s>>>24&15]+q[s>>>20&15]+q[s>>>16&15]+q[s>>>12&15]+q[s>>>8&15]+q[s>>>4&15]+q[s&15]),c},mx.prototype.toString=mx.prototype.hex,mx.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},mx.prototype.array=mx.prototype.digest,mx.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function hx(e,t,n){var r,i=ix(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new mx(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}mx.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}hx.prototype=new mx,hx.prototype.finalize=function(){if(mx.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();mx.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),mx.prototype.finalize.call(this)}};var gx=dx(),_x=dx(!0);gx.sha256=gx,gx.sha224=_x,gx.hmac=px(),_x.hmac=px(!0);const vx=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function yx(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^vx[(t^e[n])&255];return~t>>>0}const bx=new TextEncoder;function xx(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function Sx(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function Cx(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,xx(r,4,20),xx(r,6,2048),xx(r,8,0),xx(r,10,0),xx(r,12,0),Sx(r,14,n),Sx(r,18,t),Sx(r,22,t),xx(r,26,e.length),xx(r,28,0),r.set(e,30),r}function wx(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,xx(i,4,20),xx(i,6,20),xx(i,8,2048),xx(i,10,0),xx(i,12,0),xx(i,14,0),Sx(i,16,n),Sx(i,20,t),Sx(i,24,t),xx(i,28,e.length),xx(i,30,0),xx(i,32,0),xx(i,34,0),xx(i,36,0),Sx(i,38,0),Sx(i,42,r),i.set(e,46),i}function Tx(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,xx(r,4,0),xx(r,6,0),xx(r,8,e),xx(r,10,e),Sx(r,12,t),Sx(r,16,n),xx(r,20,0),r}function Ex(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function Dx(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${ye(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*Ox(e,t,n,r,i){if(n?.aborted)throw i(new Vs(`transfer-aborted`)),new Vs(`transfer-aborted`);let a=()=>i(new Vs(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=gx.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=bx.encode(`transcript.json`),f=yx(i),p=Cx(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new Vs(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new Vs(`transfer-aborted`);let t=bx.encode(e),i=yx(r),a=Cx(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new Vs(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new Vs(`transfer-aborted`);yield*d(wx(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new Vs(`transfer-aborted`);yield*d(Tx(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new Vs(`transfer-aborted`)))}}function kx(e,t,n){for(let e of t.keys())if(!Ex(e))throw new Vs(`schema-invalid`);if(t.size+1>65535)throw new Vs(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new Vs(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:Dx(e),chunks:Ox(e,t,n,r,i),completion:a}}function Ax(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:Ls},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function jx(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function Mx(e){let t=Bc(e);if(!t.ok)throw new Vs(`schema-invalid`,t.error)}function Nx(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path)){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function Px(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function Fx(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var Ix=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),Mx(i.document),r?.({phase:`packaging`}),kx(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Ub(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=ex(n.sources),{document:i,bundleFiles:a}=await zb({document:Ax(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});Mx(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Ub(this.deps.collection,e),r=ex(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=Ax(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),zb({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await wb(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new Vs(`redaction-unavailable`)}let a=Nx(r.attachments,i,e.attachments),o=await Px(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await Ri(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new Vs(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new Vs(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-eMNv3Qki.js`),{title:o,messages:s}=await a(this.deps.vfs,i,r.filename),c=`legacy-cone`,l=jx(s,c),u=Fx(i),d={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:Ls},session:{id:e,title:o,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...u,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:c,kind:`cone`,name:o,messages:l}],delegations:[],attachments:[]},f=new Map([[c,s]]);return n?.({phase:`redacting`}),zb({document:d,chatMessagesByConversation:f,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new Vs(`attachment-unreadable`);return t}};const Lx=`/sessions/data`,Rx=`document.json`;async function zx(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Bx(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new Vs(`session-not-found`)}function Vx(e){return`${Lx}/${e}`}function Hx(e){return`${Lx}/.tmp-${e}`}async function Ux(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function Wx(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await Wx(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Gx(e,t,n){await Ux(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Gx(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function Kx(e,t,n){Bx(t);let r=Hx(t),i=Vx(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new Vs(`schema-invalid`);await Wx(e,i),await Ux(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await zx(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${Rx}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await Ux(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Gx(e,r,i),await e.flush()}catch(t){throw await Wx(e,r),t}await Wx(e,r)}async function qx(e,t){Bx(t);let n=Vx(t),r=`${n}/${Rx}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new Vs(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new Vs(`schema-invalid`)}if(!Bc(a).ok)throw new Vs(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new Vs(`transfer-corrupt`)}if(await zx(i)!==t.sha256)throw new Vs(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Jx(e){return`error`in e}function Yx(){throw new Vs(`redaction-unavailable`)}function Xx(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Yx(),e.texts}function Zx(){return{async redact(e){let t;try{t=await fetch(Te(`/api/secrets/redact-export`),{method:`POST`,headers:Ee({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Yx()}t.ok||Yx();let n;try{n=await t.json()}catch{Yx()}return Xx(n,e.length)}}}function Qx(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Yx()}return typeof t==`object`&&t&&Jx(t)&&Yx(),Xx(t,e.length)}}}function $x(){return{async redact(e){let t;try{t=await dn(`secrets.redact-export`,{texts:e})}catch{Yx()}return t??Yx(),typeof t==`object`&&t&&Jx(t)&&Yx(),Xx(t,e.length)}}}function eS(){return{async redact(e){Yx()}}}function tS(){let e=rn();return e===`connect`?eS():e===`extension-direct`?Qx():e===`extension-delegate`?$x():Zx()}const nS=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function rS(e){return`e${e}`}function iS(e){let t=[];for(let n of e){let e=sS(n),r=lS(n);if(e===`assistant`){let e=t.length,i=rS(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:fS(n),message:n,model:dS(n)});for(let e of pS(n)){let n=t.length;t.push({id:rS(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:rS(i),seq:i,kind:`tool-result`,timestamp:r,text:fS(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=fS(n),a=e===`user`?oS(i):null,o=t.length,s=rS(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):nS.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function aS(e){let t=[];for(let n of e){let e=t.length,r=rS(e),i=uS(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:rS(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&ar(n.channel)?n.channel:oS(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):nS.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function oS(e){for(let t of Qn(e)){let e=(t.sender?er(t.sender):null)??rr(t.body);if(e)return e}return null}function sS(e){return e.role??``}function cS(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function lS(e){return cS(e.timestamp)}function uS(e){return cS(e.timestamp)}function dS(e){let t=e.model;return typeof t==`string`?t:void 0}function fS(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function pS(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}const mS=r(`work-unit-conversation`),hS=`conversations`;async function gS(e){let t=e.now??(()=>Date.now()),n=await vS(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys);for(let a of e.units){let o={...a,parentJid:a.parentJid??null},s=Or(o);if(i.has(s)){r.alreadyDone++;continue}try{let n=await _S(e,o,s,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(e){let t=e instanceof Error?e.message:String(e);r.skipped++,n.skipped.push({key:s,reason:t}),mS.warn(`Skipping a unit whose legacy conversation could not be read`,{key:s,folder:o.folder,error:t})}i.add(s),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${o.jid}`)}return n.done=!0,n.updatedAt=t(),await e.store.putMigrationState(n),mS.info(`Canonical conversation migration complete`,{...r}),r}async function _S(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return mS.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw Error(`canonical record unreadable: ${i.reason}`);let a={key:n,workUnitId:t.jid,workspaceId:Dr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:zn(t)}},o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:1,origin:`agent-history`,entries:iS(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:1,origin:`ui-projection`,entries:aS(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function vS(e,t){let n=await e.getMigrationState(hS);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:hS,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}const yS=r(`work-unit-conversation`),bS=`conversations`,xS=`migrations`;var SS=class{dbPromise=null;dbName;writeChains=new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await DS((await this.getDb()).transaction(bS,`readonly`).objectStore(bS).get(e));return t?Bi(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(yS.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(yS.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return yS.warn(`Conversation record read failed`,{key:e,error:kS(t)}),{status:`error`,reason:kS(t)}}}async save(e){let t=(await this.getDb()).transaction(bS,`readwrite`);t.objectStore(bS).put(e),await OS(t)}async delete(e){try{let t=(await this.getDb()).transaction(bS,`readwrite`);t.objectStore(bS).delete(e),await OS(t)}catch(t){yS.warn(`Conversation record delete failed`,{key:e,error:kS(t)})}}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){yS.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){yS.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:kS(n)})}}async listKeys(){try{return(await DS((await this.getDb()).transaction(bS,`readonly`).objectStore(bS).getAllKeys())).map(String)}catch(e){return yS.warn(`Conversation key listing failed`,{error:kS(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=iS(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=CS(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?(await this.save(o),o):a}catch(t){return yS.warn(`Conversation record write failed`,{key:e.key,error:kS(t)}),null}}async putMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async deleteMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t){return this.serialize(e,()=>this.mutateRecord(e,t))}async mutateRecord(e,t){try{let n=await this.read(e);if(n.status!==`ok`)return!1;let r=t(n.record);return r?(await this.save({...r,updatedAt:Date.now()}),!0):!1}catch(t){return yS.warn(`Conversation marker write failed`,{key:e,error:kS(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await DS((await this.getDb()).transaction(xS,`readonly`).objectStore(xS).get(e))??null}catch(t){return yS.warn(`Migration state read failed`,{id:e,error:kS(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(xS,`readwrite`);t.objectStore(xS).put(e),await OS(t)}catch(t){yS.warn(`Migration state write failed`,{id:e.id,error:kS(t)})}}async clearAll(){let e=(await this.getDb()).transaction([bS,xS],`readwrite`);e.objectStore(bS).clear(),e.objectStore(xS).clear(),await OS(e)}getDb(){return this.dbPromise||(this.dbPromise=ES(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function CS(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:1,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&wS(a,t))return null;let o=t.length>a.length&&wS(a,t);return{...e,version:1,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function wS(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!TS(e[n],t[n]))return!1;return!0}function TS(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function ES(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(bS)||e.createObjectStore(bS,{keyPath:`key`}),e.objectStoreNames.contains(xS)||e.createObjectStore(xS,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function DS(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function OS(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function kS(e){return e instanceof Error?e.message:String(e)}const AS=`focus`,jS={type:`leaf`,surfaceId:`chat`};function MS(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 NS={focus:{name:`focus`,tree:MS({left:jS},{left:3,middle:1})}};function PS(e){return NS[e]??null}const FS=r(`skills`),IS=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DT25ppH5.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/DREAMING.md":()=>import(`./DREAMING-DKcamfu0.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CDj3aVTD.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-1jIGxLn4.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-CFQTt8oo.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-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-BXSAhY0E.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-C947OHCv.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.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/gelatiere/SKILL.md":()=>import(`./SKILL-DvHAkJSI.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-BGww2dFz.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/memory/SKILL.md":()=>import(`./SKILL-C9vwCrkC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-CLF3MdfR.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-DC91lupP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-UenQ5SPT.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-D6vP9Uiw.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-DirmNXBw.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-BvFX24DM.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-C9-SR5fY.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-DJtLE66_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-BkCuZ1rT.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-CtxHowg1.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-Cc0Ep86w.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/SKILL.md":()=>import(`./SKILL-UcxSfshP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/wiki.jsh":()=>import(`./wiki-DA0qKUVC.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)}),LS=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function RS(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 zS={};function BS(){let e={};for(let[t,n]of Object.entries(IS))e[t]=n;for(let[t,n]of Object.entries(LS))e[t]=async()=>RS(await n());for(let[t,n]of Object.entries(zS)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function VS(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){FS.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 HS(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(`
|
|
977
|
+
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Ci,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,ib,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,ob,e=>{let t=new Set;for(let n of e){let e=sb(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let fb=null;function pb(e){return fb=e,()=>{fb===e&&(fb=null)}}function mb(){if(!fb)throw new Vs(`session-not-found`);return fb}function hb(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function gb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _b(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)_b(e[r],`${t}/${r}`,n);return}if(gb(e))for(let[r,i]of Object.entries(e))_b(i,`${t}/${hb(r)}`,n)}function vb(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=vb(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(gb(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=vb(o,`${t}/${hb(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function yb(e,t,n){if(gb(e))return vb(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=yb(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function bb(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function xb(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new Vs(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new Vs(`redaction-unavailable`)}if(c.length!==s.length)throw new Vs(`redaction-unavailable`);r.push(...c),i=o}return r}function Sb(e,t,n,r){let i=[],a=bb(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=bb(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=be(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function Cb(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function wb(e,t,n,r){if(r?.aborted)throw new Vs(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];_b(a,``,o);let s=o.filter(e=>!Bs(e.pointer)),c=[...t.entries()],l=await xb([...s.map(e=>e.value),...c.map(([,e])=>e)],n,r),u=[],d={},f=1,p=new Map,m=[];for(let e=0;e<s.length;e++){let t=s[e],n=Sb(t.value,l[e],{kind:`json`,pointer:t.pointer},f);f=n.nextId,n.finalText!==t.value&&p.set(t.pointer,n.finalText),m.push(n)}Cb(m,u,d);let h=new Map,g=s.length,_=[];for(let e=0;e<c.length;e++){let[t,n]=c[e],r=Sb(n,l[g+e],{kind:`attachment`,attachmentId:t},f);f=r.nextId,h.set(t,r.finalText),_.push(r)}Cb(_,u,d);let v=yb(e,``,p);return{document:{...v,privacy:{...v.privacy,redactionCounts:d,redactions:u}},textAttachments:h}}function Tb(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function Eb(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Db={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function Ob(e,t){return Db[e]??(t===`text-redacted`?`.txt`:`.bin`)}function kb(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${Ob(t,n)}`}function Ab(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}function jb(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function Mb(e,t,n,r,i){let a=Tb(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(Ab(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=Ab(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function Nb(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:Ab(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(Mb(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Pb(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function Fb(e,t,n,r,i,a,o){let s=Pb(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(Mb(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function Ib(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=Fb(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Lb(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,kb(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function Rb(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Lb(e,n),s,c;try{let e=await wb({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof Vs?e:new Vs(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new Vs(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new Vs(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await Eb(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function zb(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=Nb(jb(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=Ib(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await Rb(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function Bb(e){return zn(e)}function Vb(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function Hb(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:Tn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Tn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=Bb(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Ub(e,t,n={}){let r=e=>n.rootJid===void 0?e:En(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new Vs(`transfer-aborted`);let i=Vb(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new Vs(`transfer-aborted`);let s=r(e.listScoops());if(i===Vb(s,e))return Hb(s,a,o,e)}}function Wb(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Gb(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function Kb(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Gb(t,r++));return n}function qb(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Gb(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Jb(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Gb(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Yb(e,t,n){let r=Wb(t,n),i=Kb(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function Xb(e,t,n){let r=Wb(t,n),{blocks:i,excluded:a,images:o}=qb(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function Zb(e,t,n){let r=Wb(t,n),{blocks:i,images:a}=Jb(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function Qb(e,t,n){return e.role===`user`?Yb(e,t,n):e.role===`assistant`?Xb(e,t,n):e.role===`toolResult`?Zb(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function $b(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function ex(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=Qb(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:$b(e),excludedReasoningBlocks:t,canonicalImages:n}}var tx=`input is invalid type`,nx=`finalize already called`,rx=typeof ArrayBuffer<`u`,ix=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(rx&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(tx)},q=`0123456789abcdef`.split(``),ax=[-2147483648,8388608,32768,128],ox=[24,16,8,0],sx=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],cx=[`hex`,`array`,`digest`,`arrayBuffer`],lx=[],ux=function(e,t){return function(n){return new mx(t,!0).update(n)[e]()}},dx=function(e){var t=ux(`hex`,e);t.create=function(){return new mx(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<cx.length;++n){var r=cx[n];t[r]=ux(r,e)}return t},fx=function(e,t){return function(n,r){return new hx(n,t,!0).update(r)[e]()}},px=function(e){var t=fx(`hex`,e);t.create=function(t){return new hx(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<cx.length;++n){var r=cx[n];t[r]=fx(r,e)}return t};function mx(e,t){t?(lx[0]=lx[16]=lx[1]=lx[2]=lx[3]=lx[4]=lx[5]=lx[6]=lx[7]=lx[8]=lx[9]=lx[10]=lx[11]=lx[12]=lx[13]=lx[14]=lx[15]=0,this.blocks=lx):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}mx.prototype.update=function(e){if(this.finalized)throw Error(nx);var t=ix(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<ox[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<ox[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<ox[a++&3],s[a>>>2]|=(128|r>>>12&63)<<ox[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ox[a++&3],s[a>>>2]|=(128|r&63)<<ox[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<ox[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},mx.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=ax[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},mx.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+sx[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+sx[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+sx[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+sx[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},mx.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=q[e>>>28&15]+q[e>>>24&15]+q[e>>>20&15]+q[e>>>16&15]+q[e>>>12&15]+q[e>>>8&15]+q[e>>>4&15]+q[e&15]+q[t>>>28&15]+q[t>>>24&15]+q[t>>>20&15]+q[t>>>16&15]+q[t>>>12&15]+q[t>>>8&15]+q[t>>>4&15]+q[t&15]+q[n>>>28&15]+q[n>>>24&15]+q[n>>>20&15]+q[n>>>16&15]+q[n>>>12&15]+q[n>>>8&15]+q[n>>>4&15]+q[n&15]+q[r>>>28&15]+q[r>>>24&15]+q[r>>>20&15]+q[r>>>16&15]+q[r>>>12&15]+q[r>>>8&15]+q[r>>>4&15]+q[r&15]+q[i>>>28&15]+q[i>>>24&15]+q[i>>>20&15]+q[i>>>16&15]+q[i>>>12&15]+q[i>>>8&15]+q[i>>>4&15]+q[i&15]+q[a>>>28&15]+q[a>>>24&15]+q[a>>>20&15]+q[a>>>16&15]+q[a>>>12&15]+q[a>>>8&15]+q[a>>>4&15]+q[a&15]+q[o>>>28&15]+q[o>>>24&15]+q[o>>>20&15]+q[o>>>16&15]+q[o>>>12&15]+q[o>>>8&15]+q[o>>>4&15]+q[o&15];return this.is224||(c+=q[s>>>28&15]+q[s>>>24&15]+q[s>>>20&15]+q[s>>>16&15]+q[s>>>12&15]+q[s>>>8&15]+q[s>>>4&15]+q[s&15]),c},mx.prototype.toString=mx.prototype.hex,mx.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},mx.prototype.array=mx.prototype.digest,mx.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function hx(e,t,n){var r,i=ix(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new mx(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}mx.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}hx.prototype=new mx,hx.prototype.finalize=function(){if(mx.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();mx.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),mx.prototype.finalize.call(this)}};var gx=dx(),_x=dx(!0);gx.sha256=gx,gx.sha224=_x,gx.hmac=px(),_x.hmac=px(!0);const vx=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function yx(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^vx[(t^e[n])&255];return~t>>>0}const bx=new TextEncoder;function xx(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function Sx(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function Cx(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,xx(r,4,20),xx(r,6,2048),xx(r,8,0),xx(r,10,0),xx(r,12,0),Sx(r,14,n),Sx(r,18,t),Sx(r,22,t),xx(r,26,e.length),xx(r,28,0),r.set(e,30),r}function wx(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,xx(i,4,20),xx(i,6,20),xx(i,8,2048),xx(i,10,0),xx(i,12,0),xx(i,14,0),Sx(i,16,n),Sx(i,20,t),Sx(i,24,t),xx(i,28,e.length),xx(i,30,0),xx(i,32,0),xx(i,34,0),xx(i,36,0),Sx(i,38,0),Sx(i,42,r),i.set(e,46),i}function Tx(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,xx(r,4,0),xx(r,6,0),xx(r,8,e),xx(r,10,e),Sx(r,12,t),Sx(r,16,n),xx(r,20,0),r}function Ex(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function Dx(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${ye(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*Ox(e,t,n,r,i){if(n?.aborted)throw i(new Vs(`transfer-aborted`)),new Vs(`transfer-aborted`);let a=()=>i(new Vs(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=gx.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=bx.encode(`transcript.json`),f=yx(i),p=Cx(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new Vs(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new Vs(`transfer-aborted`);let t=bx.encode(e),i=yx(r),a=Cx(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new Vs(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new Vs(`transfer-aborted`);yield*d(wx(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new Vs(`transfer-aborted`);yield*d(Tx(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new Vs(`transfer-aborted`)))}}function kx(e,t,n){for(let e of t.keys())if(!Ex(e))throw new Vs(`schema-invalid`);if(t.size+1>65535)throw new Vs(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new Vs(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:Dx(e),chunks:Ox(e,t,n,r,i),completion:a}}function Ax(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:Ls},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function jx(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function Mx(e){let t=Bc(e);if(!t.ok)throw new Vs(`schema-invalid`,t.error)}function Nx(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path)){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function Px(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function Fx(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var Ix=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),Mx(i.document),r?.({phase:`packaging`}),kx(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Ub(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=ex(n.sources),{document:i,bundleFiles:a}=await zb({document:Ax(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});Mx(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Ub(this.deps.collection,e),r=ex(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=Ax(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),zb({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await wb(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new Vs(`redaction-unavailable`)}let a=Nx(r.attachments,i,e.attachments),o=await Px(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await Ri(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new Vs(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new Vs(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-eMNv3Qki.js`),{title:o,messages:s}=await a(this.deps.vfs,i,r.filename),c=`legacy-cone`,l=jx(s,c),u=Fx(i),d={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:Ls},session:{id:e,title:o,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...u,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:c,kind:`cone`,name:o,messages:l}],delegations:[],attachments:[]},f=new Map([[c,s]]);return n?.({phase:`redacting`}),zb({document:d,chatMessagesByConversation:f,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new Vs(`attachment-unreadable`);return t}};const Lx=`/sessions/data`,Rx=`document.json`;async function zx(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Bx(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new Vs(`session-not-found`)}function Vx(e){return`${Lx}/${e}`}function Hx(e){return`${Lx}/.tmp-${e}`}async function Ux(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function Wx(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await Wx(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Gx(e,t,n){await Ux(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Gx(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function Kx(e,t,n){Bx(t);let r=Hx(t),i=Vx(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new Vs(`schema-invalid`);await Wx(e,i),await Ux(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await zx(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${Rx}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await Ux(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Gx(e,r,i),await e.flush()}catch(t){throw await Wx(e,r),t}await Wx(e,r)}async function qx(e,t){Bx(t);let n=Vx(t),r=`${n}/${Rx}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new Vs(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new Vs(`schema-invalid`)}if(!Bc(a).ok)throw new Vs(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new Vs(`transfer-corrupt`)}if(await zx(i)!==t.sha256)throw new Vs(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Jx(e){return`error`in e}function Yx(){throw new Vs(`redaction-unavailable`)}function Xx(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Yx(),e.texts}function Zx(){return{async redact(e){let t;try{t=await fetch(Te(`/api/secrets/redact-export`),{method:`POST`,headers:Ee({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Yx()}t.ok||Yx();let n;try{n=await t.json()}catch{Yx()}return Xx(n,e.length)}}}function Qx(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Yx()}return typeof t==`object`&&t&&Jx(t)&&Yx(),Xx(t,e.length)}}}function $x(){return{async redact(e){let t;try{t=await dn(`secrets.redact-export`,{texts:e})}catch{Yx()}return t??Yx(),typeof t==`object`&&t&&Jx(t)&&Yx(),Xx(t,e.length)}}}function eS(){return{async redact(e){Yx()}}}function tS(){let e=rn();return e===`connect`?eS():e===`extension-direct`?Qx():e===`extension-delegate`?$x():Zx()}const nS=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function rS(e){return`e${e}`}function iS(e){let t=[];for(let n of e){let e=sS(n),r=lS(n);if(e===`assistant`){let e=t.length,i=rS(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:fS(n),message:n,model:dS(n)});for(let e of pS(n)){let n=t.length;t.push({id:rS(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:rS(i),seq:i,kind:`tool-result`,timestamp:r,text:fS(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=fS(n),a=e===`user`?oS(i):null,o=t.length,s=rS(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):nS.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function aS(e){let t=[];for(let n of e){let e=t.length,r=rS(e),i=uS(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:rS(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&ar(n.channel)?n.channel:oS(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):nS.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function oS(e){for(let t of Qn(e)){let e=(t.sender?er(t.sender):null)??rr(t.body);if(e)return e}return null}function sS(e){return e.role??``}function cS(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function lS(e){return cS(e.timestamp)}function uS(e){return cS(e.timestamp)}function dS(e){let t=e.model;return typeof t==`string`?t:void 0}function fS(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function pS(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}const mS=r(`work-unit-conversation`),hS=`conversations`;async function gS(e){let t=e.now??(()=>Date.now()),n=await vS(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys);for(let a of e.units){let o={...a,parentJid:a.parentJid??null},s=Or(o);if(i.has(s)){r.alreadyDone++;continue}try{let n=await _S(e,o,s,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(e){let t=e instanceof Error?e.message:String(e);r.skipped++,n.skipped.push({key:s,reason:t}),mS.warn(`Skipping a unit whose legacy conversation could not be read`,{key:s,folder:o.folder,error:t})}i.add(s),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${o.jid}`)}return n.done=!0,n.updatedAt=t(),await e.store.putMigrationState(n),mS.info(`Canonical conversation migration complete`,{...r}),r}async function _S(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return mS.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw Error(`canonical record unreadable: ${i.reason}`);let a={key:n,workUnitId:t.jid,workspaceId:Dr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:zn(t)}},o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:1,origin:`agent-history`,entries:iS(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:1,origin:`ui-projection`,entries:aS(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function vS(e,t){let n=await e.getMigrationState(hS);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:hS,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}const yS=r(`work-unit-conversation`),bS=`conversations`,xS=`migrations`;var SS=class{dbPromise=null;dbName;writeChains=new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await DS((await this.getDb()).transaction(bS,`readonly`).objectStore(bS).get(e));return t?Bi(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(yS.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(yS.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return yS.warn(`Conversation record read failed`,{key:e,error:kS(t)}),{status:`error`,reason:kS(t)}}}async save(e){let t=(await this.getDb()).transaction(bS,`readwrite`);t.objectStore(bS).put(e),await OS(t)}async delete(e){try{let t=(await this.getDb()).transaction(bS,`readwrite`);t.objectStore(bS).delete(e),await OS(t)}catch(t){yS.warn(`Conversation record delete failed`,{key:e,error:kS(t)})}}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){yS.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){yS.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:kS(n)})}}async listKeys(){try{return(await DS((await this.getDb()).transaction(bS,`readonly`).objectStore(bS).getAllKeys())).map(String)}catch(e){return yS.warn(`Conversation key listing failed`,{error:kS(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=iS(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=CS(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?(await this.save(o),o):a}catch(t){return yS.warn(`Conversation record write failed`,{key:e.key,error:kS(t)}),null}}async putMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async deleteMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t){return this.serialize(e,()=>this.mutateRecord(e,t))}async mutateRecord(e,t){try{let n=await this.read(e);if(n.status!==`ok`)return!1;let r=t(n.record);return r?(await this.save({...r,updatedAt:Date.now()}),!0):!1}catch(t){return yS.warn(`Conversation marker write failed`,{key:e,error:kS(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await DS((await this.getDb()).transaction(xS,`readonly`).objectStore(xS).get(e))??null}catch(t){return yS.warn(`Migration state read failed`,{id:e,error:kS(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(xS,`readwrite`);t.objectStore(xS).put(e),await OS(t)}catch(t){yS.warn(`Migration state write failed`,{id:e.id,error:kS(t)})}}async clearAll(){let e=(await this.getDb()).transaction([bS,xS],`readwrite`);e.objectStore(bS).clear(),e.objectStore(xS).clear(),await OS(e)}getDb(){return this.dbPromise||(this.dbPromise=ES(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function CS(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:1,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&wS(a,t))return null;let o=t.length>a.length&&wS(a,t);return{...e,version:1,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function wS(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!TS(e[n],t[n]))return!1;return!0}function TS(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function ES(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(bS)||e.createObjectStore(bS,{keyPath:`key`}),e.objectStoreNames.contains(xS)||e.createObjectStore(xS,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function DS(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function OS(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function kS(e){return e instanceof Error?e.message:String(e)}const AS=`focus`,jS={type:`leaf`,surfaceId:`chat`};function MS(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 NS={focus:{name:`focus`,tree:MS({left:jS},{left:3,middle:1})}};function PS(e){return NS[e]??null}const FS=r(`skills`),IS=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DT25ppH5.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-C4hj5z8T.js`).then(e=>e.default),"/packages/vfs-root/shared/DREAMING.md":()=>import(`./DREAMING-DKcamfu0.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CDj3aVTD.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-BJp9Ffsq.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-CFQTt8oo.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-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-BXSAhY0E.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-C947OHCv.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.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/gelatiere/SKILL.md":()=>import(`./SKILL-DvHAkJSI.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-BGww2dFz.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/memory/SKILL.md":()=>import(`./SKILL-C9vwCrkC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-CLF3MdfR.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-DC91lupP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-UenQ5SPT.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-D6vP9Uiw.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-DirmNXBw.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-BvFX24DM.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-C9-SR5fY.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-DJtLE66_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-BkCuZ1rT.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-CtxHowg1.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-Cc0Ep86w.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/SKILL.md":()=>import(`./SKILL-UcxSfshP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/wiki.jsh":()=>import(`./wiki-DA0qKUVC.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)}),LS=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function RS(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 zS={};function BS(){let e={};for(let[t,n]of Object.entries(IS))e[t]=n;for(let[t,n]of Object.entries(LS))e[t]=async()=>RS(await n());for(let[t,n]of Object.entries(zS)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function VS(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){FS.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 HS(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(`
|
|
978
978
|
`)){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 US(e,t){let n=await WS(e,t),r=await GS(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=VS([...i,...r,...a]);return FS.info(`Skills loaded`,{count:o.length,dir:t}),o}async function WS(e,t){let n=await xi(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=HS(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}),FS.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{FS.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function GS(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}=HS(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}),FS.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{FS.debug(`Standalone skills directory not found`,{dir:t})}return n}function KS(e){return e.length===0?``:`
|
|
979
979
|
---
|
|
980
980
|
AVAILABLE SKILLS
|
|
@@ -1629,7 +1629,7 @@ except BaseException:
|
|
|
1629
1629
|
`)?a:`${a}\n`;t(n>0?`${` `.repeat(n)}${o}`:o)}function UV(e,t,n){let r=LV(n);if(e.has(r)){t(`Label '${r}' already exists for console.time()`);return}e.set(r,RV())}function WV(e,t,n,r){let i=LV(r),a=e.get(i);if(a===void 0){t(`No such label '${i}' for console.timeEnd()`);return}e.delete(i),n(`${i}: ${zV(RV()-a)}`)}function GV(e,t,n,r,i){let a=LV(r),o=e.get(a);if(o===void 0){t(`No such label '${a}' for console.timeLog()`);return}let s=`${a}: ${zV(RV()-o)}`;i.length===0?n(s):n(s,...i)}function KV(e,t,n){let r=LV(n),i=(e.get(r)??0)+1;e.set(r,i),t(`${r}: ${i}`)}function qV(e,t,n){let r=LV(n);if(!e.has(r)){t(`Count for '${r}' does not exist`);return}e.set(r,0)}function JV(e,t,n){n.length>0&&t(...n),e.depth+=1}function YV(e){e.depth>0&&--e.depth}function XV(e,t){let n=new Map,r=new Map,i={depth:0},a=(...t)=>BV(e,i.depth,t),o=(...e)=>BV(t,i.depth,e),s=(...e)=>JV(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:()=>YV(i),assert:(e,...t)=>VV(o,e,t),trace:(...e)=>HV(o,t,i.depth,e),time:e=>UV(r,o,e),timeEnd:e=>WV(r,o,a,e),timeLog:(e,...t)=>GV(r,o,a,e,t),count:e=>KV(n,a,e),countReset:e=>qV(n,o,e)}}function ZV(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=$V(e.stdin??``,o),c=DV(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:Oa},version:`v${Oa}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new PV(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var QV=class extends TI.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 PV){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 $V(e,t){return new QV(e,t)}function eH(e){if(e===``)return[];let t=e.split(`
|
|
1630
1630
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function tH(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function nH(e){return new TextDecoder(`utf-8`).decode(OF(e))}function rH(e){if(e&&typeof e.write==`function`)return e}var iH=class extends yI{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=eH(nH(tH(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 PV&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function aH(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=rH(e.output)}else r=t,i=rH(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new iH(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:iH,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var oH=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`?`: ${sH(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 sH(e){try{return JSON.stringify(e)}catch{return String(e)}}function cH(e){return new Promise(t=>setTimeout(t,e))}function lH(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 uH(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?lH(r,n):r}function dH(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 fH(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 mH(e){if(fH(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 hH(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 gH(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function _H(e,t,n){let r=await t(n);r&&!gH(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function vH(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 yH(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function bH(e,t){let n=await mH(e);return t?yH(e,n):n}async function xH(e,t){let n=await mH(e).catch(()=>null);throw new oH(e.status,e.statusText,t,n)}function SH(e,t){let n=pH(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function CH(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=vH(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 bH(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return xH(l,t);await e.sleep(SH(l,a))}if(i)return xH(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function wH(e){let t=e.sleep??cH;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=uH(n.baseUrl,o,s.params),l=dH(n.headers,s.headers);n.token&&await _H(l,n.token,{method:a,path:o,url:c});let u=hH(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),CH({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 TH(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 EH(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`,TH(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 DH(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(EH(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 OH(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 kH(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=OH(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 AH(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 jH(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 jH(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(fr(e)){let t=await vr(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 MH(e){return{findTab:t=>e.call(`browser`,`findTab`,[PH(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,FH(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[OH(t),NH(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[OH(t),NH(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[OH(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[OH(t),n]),fetch:(t,n,r={})=>to(n,r).then(n=>e.call(`browser`,`evalAsync`,[OH(t),n])),websocket:kH(e)}}function NH(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 PH(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 FH(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function IH(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function LH(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:IH(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}const RH=new Set([204,205,304]),zH=new Set([`content-encoding`,`transfer-encoding`,`content-length`]);function BH(e,t){let n=VH(e.body),r=HH(e.headers),i=RH.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 UH(a,n),a}function VH(e){return e.byteLength===0?new Uint8Array:e.slice()}function HH(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(!zH.has(n.toLowerCase()))try{t.set(n,r)}catch{}return t}function UH(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 WH(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 GH(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function KH(e){return e==null?[]:Array.isArray(e)?e:[e]}function qH(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:GH(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,WH(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,WH(r)]),receiveFeatureReport:async t=>GH((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 JH(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>qH(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[KH(t)]))[0];if(!n)throw Error(`No device selected.`);return qH(e,n)}}}function YH(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 XH=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 };`)}},ZH=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=YH(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 XH(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 XH(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?.())}},QH=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 ZH(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()}},$H=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 ZH(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 QH(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 eU(e){let t=async t=>new $H(e),n=async(t,n)=>new $H(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const tU=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`]),nU={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 rU(e,t){let n=nU[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function iU(e){return{...e,time:MV,fmt:aI,pool:OV}}function aU(e,t){return e?.startsWith(`/`)?NV(e):t}function oU(e){return e.includes(`require`)||e.includes(`import`)||/(?:^|[;\n}])\s*export\b/.test(e)}async function sU(e,t,n,r){return oU(t)?e.call(`module`,`buildGraph`,[t,aU(r,n),r]):{files:[],entryMap:{},edges:{},edgeErrors:{},errors:{}}}function cU(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 lU(e){return{playwright:eU(e)}}function uU(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=WL,nodeUtilModule:u=UI}=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=zL({requireFrom:(e,t)=>x(e,t),resolveFrom:(e,t)=>b(e,t)}),h=EL(()=>{let e=r?.cwd?.();return typeof e==`string`&&e.length>0?e:`/`}),g=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=dU(t,{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:l,nodeUtilModule:u,nodePathModule:h,nodeReadline:c,nodeModule:m});if(a.hit)return a;if(tU.has(t))throw rU(e,t);if(ja.has(t))throw hU(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},_=(e,n,r)=>{let i=g(n);if(i.hit)return i.value;let a=e?.[n];if(a)return v(a);let o=r===null?t.errors[n]:t.edgeErrors?.[r]?.[n];throw o?Error(o):fU(n)};function v(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=>_(t.edges[e],n,e),c=NV(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`&&cU(o.exports),o.exports}function y(e){return d.has(e)}function b(e,n){if(ka(n))return n;let r=t.edges[e]?.[n];if(r)return r;let i=NV(e);if(RL(n)){let e=IL(i,n,y);if(e)return e}else{let e=LL(i,n,y);if(e)return e}let a=t.edgeErrors?.[e]?.[n];throw a?Error(a):fU(n)}function x(e,t){let n=g(t);return n.hit?n.value:v(b(e,t))}return{require:e=>_(t.entryMap,e,null)}}function dU(e,t){let{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:a,nodeUtilModule:o,nodePathModule:s,nodeReadline:c,nodeModule:l}=t;return e===`fs`||e===`fs/promises`?{hit:!0,value:n}:e===`path`?{hit:!0,value:s}:e===`crypto`?{hit:!0,value:mL}: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:_I}:e===`assert/strict`?{hit:!0,value:gI}:e===`util`?{hit:!0,value:o}:e===`events`?{hit:!0,value:bI}:e===`os`?{hit:!0,value:a}:e===`tty`?{hit:!0,value:GL}:e===`stream`?{hit:!0,value:TI}:e===`url`?{hit:!0,value:AL}:e===`zlib`?{hit:!0,value:TV}:e===`readline`&&c?{hit:!0,value:c}:e===`readline/promises`&&c?{hit:!0,value:c.promises}:e===`module`&&l?{hit:!0,value:l}:{hit:!1}}function fU(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 mU={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function hU(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${mU[t]||``}`)}async function gU(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";
|
|
1631
1631
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof PV?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function _U(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?WH(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,WH(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function vU(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>_U(e,t)),request:async t=>_U(e,await e.call(`serial`,`request`,[KH(t)]))}}function yU(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 bU(e,t){let n=t.handle,r=e=>({status:e.status,data:GH(e.bytes)}),i=new Set,a=new Set,o=!1,s=null,c=e=>{let t=e;if(!t||t.handle!==n)return;let r=t.type===`disconnect`?i:a;for(let e of[...r])try{e(t)}catch{}},l=()=>{o||(o=!0,s=e.onEvent?e.onEvent(`usb-claim-event`,c):null,e.call(`usb`,`subscribeClaimEvents`,[n]).catch(()=>{o=!1,s?.(),s=null}))},u=()=>{!o||i.size>0||a.size>0||(o=!1,s?.(),s=null,e.call(`usb`,`unsubscribeClaimEvents`,[n]).catch(()=>{}))};return{...t,open:()=>e.call(`usb`,`open`,[n]),close:t=>e.call(`usb`,`close`,t?.force?[n,{force:!0}]:[n]),reset:t=>e.call(`usb`,`reset`,t?.force?[n,{force:!0}]:[n]),clearHalt:(t,r)=>e.call(`usb`,`clearHalt`,[n,t,r]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:(t,r)=>e.call(`usb`,`claim`,r?.wait?[n,t,{wait:!0}]:[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,WH(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,WH(r)]),addEventListener(e,t){if(e===`disconnect`)i.add(t);else if(e===`claim-lost`)a.add(t);else throw TypeError(`usb device: unknown event type '${String(e)}'`);l()},removeEventListener(e,t){e===`disconnect`?i.delete(t):e===`claim-lost`&&a.delete(t),u()}}}function xU(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>bU(e,t)),request:async t=>bU(e,await e.call(`usb`,`request`,[KH(t)]))}}function SU(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function CU(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 wU(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function TU(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function EU(e){let t=SU(e.argv[1]??``),n=CU(t),r=TU(n,`references`),i=TU(n,`assets`),a=TU(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)+`
|
|
1632
|
-
`),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 ${wU(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 DU=new Map,OU=new Map;function kU(e){let t=crypto.randomUUID();return DU.set(t,e),t}function AU(e){return DU.get(e)??null}function jU(e,t){if(!DU.has(e))return t.abort(),()=>{};let n=OU.get(e);return n||(n=new Set,OU.set(e,n)),n.add(t),()=>{let n=OU.get(e);n&&(n.delete(t),n.size===0&&OU.delete(e))}}function MU(e){DU.delete(e);let t=OU.get(e);if(t){OU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function NU(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 PU(e){let t=AU(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 NU(e)}}function FU(e){return`slicc-sync-fs-`+e}const IU=`sync-fs-ack`,LU=`sync-fs-res`,RU=6e5,zU=5e3,BU=`exec`;function VU(e){return e.channel===BU}function HU(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 UU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,RU)}async function WU(e){let t=AU(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=HU(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()},UU(e.timeoutMs,RU)),o=jU(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`}:NU(e)}finally{clearTimeout(a),o()}}function GU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function KU(e){let t=JU(e);if(YU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw GU(`EIO`,e.label);XU(t,e.label)}function qU(e){let t=KU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw GU(`EIO`,e.label)}}function JU(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 GU(`EIO`,e.label)}return t}function YU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function XU(e,t){throw GU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function ZU(e){return(t,n,r)=>{let i=qU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:BU})),timeoutMs:n+zU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw GU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function QU(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 $U(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??ZU(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&QU(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=UU(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 eW(e,t){return GU(e,`sync-fs bridge, '${t}'`)}function tW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function nW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:tW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return KU(r(`GET`,e))},writeFile(e,t){KU(r(`POST`,e,t))},stat(e){let t=qU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw eW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=qU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw eW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=qU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw eW(`EIO`,e);return t},exists(e){let t=qU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw eW(`EIO`,e);return t},mkdir(e){KU(r(`POST`,e,void 0,`mkdir`))},rm(e){KU(r(`POST`,e,void 0,`rm`))}}}const rW=new TextEncoder,iW=new TextDecoder;function aW(e){if(!e.ok)return{status:4,payload:rW.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:rW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function oW(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(iW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(iW.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 sW(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 cW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function lW(e,t,n={}){let{header:r,window:i}=sW(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 GU(`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 GU(`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 GU(`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 GU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return oW(f,d)}}}function uW(e,t){return GU(e,`sync-sab bridge, '${t}'`)}function dW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function fW(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 uW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw uW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw uW(`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(!dW(t))throw uW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!dW(t))throw uW(`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 uW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw uW(`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:BU},n+zU,r);if(!i.ok)throw GU(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 GU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function mW(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 EF(r)}function hW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function gW(e,t){return t?fW(t):e.syncFsToken?nW(e.syncFsToken):void 0}function _W(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return lW(e.syncSab,t)}function vW(e,t,n,r,i){let a=_W(e,t),o=gW(e,a);if(Object.assign(r,KF(n,e.cwd,o,i)),e.syncFsToken)return $U(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:pW(a)}:{}})}function yW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:ti().version,writable:!1,enumerable:!1,configurable:!1})}function bW(e,t,n){let r=YF({isTTY:!e,noColor:e});return{colorApi:r,cliApi:qF({writeStdout:t,writeStderr:n,exit:e=>{throw new PV(e)},color:r})}}function xW(e,t,n){return{readStdinBytes:()=>OF(e.stdin??``),writeStdout:t,writeStderr:n}}function SW(e){return{usbBridge:xU(e),serialBridge:vU(e),hidBridge:JH(e)}}async function CW(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=XV(i,a),s=ZV(e,i,a),{colorApi:c,cliApi:l}=bW(!!e.env?.NO_COLOR,i,a),u=new LP(t),d=xW(e,i,a),f=BF(u,C,d),p=await mW(u,e.cwd,hW(e,a)),m=vW(e,t,p,f,d),h=LH(u,p,e.cwd,a),g=DH(h,{cwd:e.cwd}),_=EU({argv:e.argv,fs:f,exec:h}),v=MH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=SW(u),S=wH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return BH(await u.call(`fetch`,`request`,[n,await AH(t,e)]),n)}let w=iU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=NV(T),D=await sU(u,e.code,e.cwd,T),ee=uU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:QI(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:lU(u),nodeReadline:aH({output:{write:i},onExit:s.recordExit}),nodeOsModule:UL(e.env),nodeUtilModule:HI(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await wW({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 wW(e){let t=globalThis;yW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=yU(globalThis,{onCallbackError(e){if(!(e instanceof PV))throw e}});n.install();try{let r=await TW({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 TW(e){let t=await gU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await EW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await DW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await EW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function EW(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 DW(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 OW(){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 kW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=OW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&CW(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 AW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=OW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&JP(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 jW=kW(),MW=AW();function NW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?FW():MW({kind:e,ctx:t}):typeof Worker<`u`?PW():jW({kind:e,ctx:t})}function PW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return IW(new Worker(new URL(`/assets/js-realm-worker-w_3ye_7l.js`,``+import.meta.url),{type:`module`}))}function FW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return IW(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function IW(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 LW(){if(Ka())return decodeURIComponent(Ra(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function RW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function zW(e){return e instanceof Error?e.message:String(e)}function BW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function VW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:BW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function HW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:BW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const UW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,WW=/\bimport\s*\.\s*meta\b/g;function GW(e,t){let n=JSON.stringify(t);return e.replace(UW,n).replace(WW,`({ url: ${n} })`)}async function KW(e,t,n,r){let i=await e();return i.transpileModule(GW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function qW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>no(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ia(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Pa(e))return e;let a=RW(t),o;try{return await VW(n,e,t,a)}catch(e){o=e}try{return await KW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${zW(o)}; typescript fallback: ${zW(e)}`)}}}function JW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>no(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ia(t));return async({source:e,filename:t})=>{if(!Pa(e)&&!$a(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?RW(t):void 0,o=i?t:`[eval].js`,s;try{return await HW(n,e,t,a)}catch(e){s=e}try{return await KW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${zW(s)}; typescript fallback: ${zW(e)}`)}}}function YW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1632
|
+
`),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 ${wU(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 DU=new Map,OU=new Map;function kU(e){let t=crypto.randomUUID();return DU.set(t,e),t}function AU(e){return DU.get(e)??null}function jU(e,t){if(!DU.has(e))return t.abort(),()=>{};let n=OU.get(e);return n||(n=new Set,OU.set(e,n)),n.add(t),()=>{let n=OU.get(e);n&&(n.delete(t),n.size===0&&OU.delete(e))}}function MU(e){DU.delete(e);let t=OU.get(e);if(t){OU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function NU(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 PU(e){let t=AU(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 NU(e)}}function FU(e){return`slicc-sync-fs-`+e}const IU=`sync-fs-ack`,LU=`sync-fs-res`,RU=6e5,zU=5e3,BU=`exec`;function VU(e){return e.channel===BU}function HU(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 UU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,RU)}async function WU(e){let t=AU(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=HU(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()},UU(e.timeoutMs,RU)),o=jU(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`}:NU(e)}finally{clearTimeout(a),o()}}function GU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function KU(e){let t=JU(e);if(YU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw GU(`EIO`,e.label);XU(t,e.label)}function qU(e){let t=KU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw GU(`EIO`,e.label)}}function JU(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 GU(`EIO`,e.label)}return t}function YU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function XU(e,t){throw GU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function ZU(e){return(t,n,r)=>{let i=qU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:BU})),timeoutMs:n+zU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw GU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function QU(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 $U(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??ZU(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&QU(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=UU(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 eW(e,t){return GU(e,`sync-fs bridge, '${t}'`)}function tW(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function nW(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:tW(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return KU(r(`GET`,e))},writeFile(e,t){KU(r(`POST`,e,t))},stat(e){let t=qU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw eW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=qU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw eW(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=qU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw eW(`EIO`,e);return t},exists(e){let t=qU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw eW(`EIO`,e);return t},mkdir(e){KU(r(`POST`,e,void 0,`mkdir`))},rm(e){KU(r(`POST`,e,void 0,`rm`))}}}const rW=new TextEncoder,iW=new TextDecoder;function aW(e){if(!e.ok)return{status:4,payload:rW.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:rW.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function oW(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(iW.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(iW.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 sW(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 cW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function lW(e,t,n={}){let{header:r,window:i}=sW(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 GU(`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 GU(`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 GU(`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 GU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return oW(f,d)}}}function uW(e,t){return GU(e,`sync-sab bridge, '${t}'`)}function dW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function fW(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 uW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw uW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw uW(`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(!dW(t))throw uW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!dW(t))throw uW(`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 uW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw uW(`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:BU},n+zU,r);if(!i.ok)throw GU(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 GU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function mW(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 EF(r)}function hW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function gW(e,t){return t?fW(t):e.syncFsToken?nW(e.syncFsToken):void 0}function _W(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return lW(e.syncSab,t)}function vW(e,t,n,r,i){let a=_W(e,t),o=gW(e,a);if(Object.assign(r,KF(n,e.cwd,o,i)),e.syncFsToken)return $U(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:pW(a)}:{}})}function yW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:ti().version,writable:!1,enumerable:!1,configurable:!1})}function bW(e,t,n){let r=YF({isTTY:!e,noColor:e});return{colorApi:r,cliApi:qF({writeStdout:t,writeStderr:n,exit:e=>{throw new PV(e)},color:r})}}function xW(e,t,n){return{readStdinBytes:()=>OF(e.stdin??``),writeStdout:t,writeStderr:n}}function SW(e){return{usbBridge:xU(e),serialBridge:vU(e),hidBridge:JH(e)}}async function CW(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=XV(i,a),s=ZV(e,i,a),{colorApi:c,cliApi:l}=bW(!!e.env?.NO_COLOR,i,a),u=new LP(t),d=xW(e,i,a),f=BF(u,C,d),p=await mW(u,e.cwd,hW(e,a)),m=vW(e,t,p,f,d),h=LH(u,p,e.cwd,a),g=DH(h,{cwd:e.cwd}),_=EU({argv:e.argv,fs:f,exec:h}),v=MH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=SW(u),S=wH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return BH(await u.call(`fetch`,`request`,[n,await AH(t,e)]),n)}let w=iU({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=NV(T),D=await sU(u,e.code,e.cwd,T),ee=uU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:QI(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:lU(u),nodeReadline:aH({output:{write:i},onExit:s.recordExit}),nodeOsModule:UL(e.env),nodeUtilModule:HI(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await wW({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 wW(e){let t=globalThis;yW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=yU(globalThis,{onCallbackError(e){if(!(e instanceof PV))throw e}});n.install();try{let r=await TW({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 TW(e){let t=await gU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await EW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await DW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await EW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function EW(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 DW(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 OW(){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 kW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=OW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&CW(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 AW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=OW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&JP(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 jW=kW(),MW=AW();function NW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?FW():MW({kind:e,ctx:t}):typeof Worker<`u`?PW():jW({kind:e,ctx:t})}function PW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return IW(new Worker(new URL(`/assets/js-realm-worker-Bnl_qf6X.js`,``+import.meta.url),{type:`module`}))}function FW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return IW(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function IW(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 LW(){if(Ka())return decodeURIComponent(Ra(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function RW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function zW(e){return e instanceof Error?e.message:String(e)}function BW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function VW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:BW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function HW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:BW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const UW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,WW=/\bimport\s*\.\s*meta\b/g;function GW(e,t){let n=JSON.stringify(t);return e.replace(UW,n).replace(WW,`({ url: ${n} })`)}async function KW(e,t,n,r){let i=await e();return i.transpileModule(GW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function qW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>no(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ia(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Pa(e))return e;let a=RW(t),o;try{return await VW(n,e,t,a)}catch(e){o=e}try{return await KW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${zW(o)}; typescript fallback: ${zW(e)}`)}}}function JW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>no(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ia(t));return async({source:e,filename:t})=>{if(!Pa(e)&&!$a(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?RW(t):void 0,o=i?t:`[eval].js`,s;try{return await HW(n,e,t,a)}catch(e){s=e}try{return await KW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${zW(s)}; typescript fallback: ${zW(e)}`)}}}function YW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1633
1633
|
`);return t===-1?``:e.slice(t+1)}function XW(e){return hn(e).dir}const ZW=[`node`,`require`,`default`],QW=[`node`,`import`,`default`],$W=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,eG=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,tG=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,nG=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,rG=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function iG(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function aG(e){let t=Qa(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!iG(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r($W,`require`,`require`),r(eG,`import`,`import`),r(tG,`import`,`import`),r(nG,`import`,`export`),r(rG,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function oG(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=YW(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${Ya} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function sG(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??ZW,s=e.importConditions??QW,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 oG(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=XW(e),m={},h={};for(let{specifier:e,kind:t}of aG(n)){let n;try{n=await Da(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 Da(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 cG(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Aa.has(e)||tU.has(e))}function lG(e,t){for(let[n,r]of Object.entries(t))e[n]={...e[n]??{},...r}}async function uG(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 aG(t))if(cG(e))try{let t=await sG({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?QW:ZW,requireConditions:ZW,importConditions:QW});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap),lG(u,t.edges),lG(d,t.edgeErrors)}catch(t){f[e]=t instanceof Error?t.message:String(t)}let p;o&&(Pa(t)||$a(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 dG(){return globalThis.navigator?.hid??null}function fG(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??``)&&fG(e)===fG(t)&&!!e.productName}var mG=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 hG=null;function gG(){return hG||=new mG,hG}const _G=4194304;function vG(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 yG(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function bG(e){e.opened||await e.open()}function xG(e,t){if(e>4194304)throw Error(`${t} exceeds the ${_G}-byte (4 MiB) v1 limit`)}function SG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function CG(e,t){return(await t.getDevices()).map(t=>vG(e.register(t),t))}async function wG(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>vG(e.register(t),t))}function TG(e,t){return vG(t,yG(e,t))}async function EG(e,t){await yG(e,t).open()}async function DG(e,t){await yG(e,t).close()}async function OG(e,t,n,r){xG(r.byteLength,`send report payload`);let i=yG(e,t);await bG(i),await i.sendReport(n,r)}async function kG(e,t,n,r){xG(r.byteLength,`send feature report payload`);let i=yG(e,t);await bG(i),await i.sendFeatureReport(n,r)}async function AG(e,t,n){let r=yG(e,t);return await bG(r),{reportId:n,bytes:SG(await r.receiveFeatureReport(n))}}async function jG(e,t,n){let r=yG(e,t);await bG(r);let i=e=>{n({reportId:e.reportId,bytes:SG(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const MG=6e4;function NG(){return rw()}function PG(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),MG);iw(`hid-device`,e??[],void 0,{timeoutMs:MG}).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 FG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var IG=class{registry;constructor(e){this.registry=e}hid(){let e=dG();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return CG(this.registry,this.hid())}async request(e){if(NG()){let t=await PG(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=>vG(this.registry.register(e),e))}return wG(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(TG(this.registry,e))}open(e){return EG(this.registry,e)}close(e){return DG(this.registry,e)}sendReport(e,t,n){return OG(this.registry,e,t,FG(n))}sendFeatureReport(e,t,n){return kG(this.registry,e,t,FG(n))}async receiveFeatureReport(e,t){let n=await AG(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return jG(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},LG=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:FG(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:FG(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 RG(e,t){return e&&dG()?new IG(gG()):t?new LG(t):null}function zG(e){return async function(t,n){let r=t instanceof Request?t:null,i=BG(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=HG(r?.headers,n?.headers),s=await GG(n,r,a,o);s.defaultContentType&&!UG(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 BG(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function VG(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 HG(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=VG(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function UG(e,t){return WG(e,t)!==void 0}function WG(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function GG(e,t,n,r){if(e&&`body`in e&&e.body!==void 0)return KG(e.body,n);if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=WG(r,`content-type`)??``,a=e&&(!i||!x(i));return{body:n.byteLength===0?void 0:a?Ce(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function KG(e,t){if(fr(e)){if(t===`GET`||t===`HEAD`)return{};let n=await vr(e);return{body:n.bytes,defaultContentType:n.contentType}}return{body:await qG(e,t),defaultContentType:YG(e,t)}}async function qG(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 Ce(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 JG(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function YG(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!JG(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function XG(){return globalThis.navigator?.serial??null}var ZG=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 QG=null;function $G(){return QG||=new ZG,QG}const eK=4194304;function tK(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 nK(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function rK(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function iK(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 aK(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 oK(e){if(await aK(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function sK(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await oK(t);return n.map(t=>{let n=e.register(t);return tK(n,e.get(n))})}async function cK(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return tK(i,e.get(i))}function lK(e,t){return tK(t,nK(e,t))}async function uK(e,t,n){let r=nK(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 dK(e,t){let n=nK(e,t);await aK(n);try{await n.port.close()}catch(e){if(!fK(e))throw e}n.opened=!1}function fK(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 mK(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 hK(e,t,n){let r=nK(e,t),i=Math.min(n.maxBytes??4194304,eK),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=iK(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=rK(c,a.value);let e=u();if(e)return e}}return c}async function gK(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${eK}-byte (4 MiB) v1 limit`);return await mK(nK(e,t)).write(n),n.length}async function _K(e,t){return nK(e,t).port.getSignals()}async function vK(e,t,n){await nK(e,t).port.setSignals(n)}const yK=6e4;function bK(){return rw()}function xK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),yK);iw(`serial-port`,e??[],void 0,{timeoutMs:yK}).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 SK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var CK=class{registry;constructor(e){this.registry=e}serial(){let e=XG();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return sK(this.registry,this.serial())}async request(e){if(bK()){let t=await xK(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 tK(r,this.registry.get(r))}return cK(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(lK(this.registry,e))}open(e,t){return uK(this.registry,e,t)}close(e){return dK(this.registry,e)}read(e,t){return hK(this.registry,e,t)}write(e,t){return gK(this.registry,e,t)}getSignals(e){return _K(this.registry,e)}setSignals(e,t){return vK(this.registry,e,t)}},wK=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?SK(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:SK(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 TK(e,t){return e&&XG()?new CK($G()):t?new wK(t):null}const EK=r(`usb`);async function DK(){return import(`./usb-claim-broker-C5dFP5bv.js`)}function OK(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function kK(e,t){if(e>4194304)throw Error(`${t} exceeds the ${fo}-byte (4 MiB) v1 limit`)}function AK(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function jK(e,t){return(await t.getDevices()).map(t=>oo(e.register(t),t))}async function MK(e,t,n){let r=await t.requestDevice({filters:n});return oo(e.register(r),r)}function NK(e,t){return oo(t,OK(e,t))}async function PK(e,t){await OK(e,t).open()}async function FK(e,t,n){await GK(e,t,`close`,n)}async function IK(e,t,n){await OK(e,t).selectConfiguration(n)}async function LK(e,t,n,r){let i=r?.owner??`usb`,a=OK(e,t),o=await DK(),s=await o.acquireInterfaceClaim(e,t,n,i,r?.wait??!1,r?.signal),c=()=>o.claimOwner(e,t,n),l=()=>c()===i,u=()=>o.wasGrantCancelled(e,t,n,i),d=async r=>{if(!(l()&&!u())){if(u()||!c()){if(r)try{await a.releaseInterface(n)}catch{}o.settleCancelledGrant(e,t,n,i),o.wakeInterfaceWaiter(e,t,n)}throw o.claimWaitCancelledError(t,n,i)}};try{await d(!1),await a.claimInterface(n),await d(!0)}catch(r){throw s===`acquired`&&(u()?(o.settleCancelledGrant(e,t,n,i),o.wakeInterfaceWaiter(e,t,n)):l()?o.releaseInterfaceClaim(e,t,n,i):c()||o.wakeInterfaceWaiter(e,t,n)),r}finally{o.clearPendingGrant(e,t,n,i)}}async function RK(e,t){let n=await DK(),r=n.takeOwnerClaims(e,t);for(let t of r){try{await e.get(t.handle)?.releaseInterface(t.interfaceNumber)}catch{}n.wakeInterfaceWaiter(e,t.handle,t.interfaceNumber)}}async function zK(e,t,n,r){let i=r?.owner??`usb`,a=OK(e,t),o=await DK(),s=o.claimOwner(e,t,n);if(s&&s!==i)throw new so({handle:t,holder:s,op:`release`,interfaceNumber:n});await a.releaseInterface(n),o.releaseInterfaceClaim(e,t,n,i)}async function BK(e,t,n,r){kK(r,`control-in length`);let i=await OK(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?AK(i.data):new ArrayBuffer(0)}}async function VK(e,t,n,r){kK(r.byteLength,`control-out payload`);let i=await OK(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function HK(e,t,n,r){kK(r,`transfer-in length`);let i=await OK(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?AK(i.data):new ArrayBuffer(0)}}async function UK(e,t,n,r){kK(r.byteLength,`transfer-out payload`);let i=await OK(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function WK(e,t,n){await GK(e,t,`reset`,n)}async function GK(e,t,n,r){let i=r?.owner??`usb`,a=r?.force??!1,o=OK(e,t),s=await DK(),c=s.listClaims(e,t);if(c.length>0){let e=c.map(e=>`${e.interfaceNumber}=${e.owner}`).join(`, `);EK.warn(`usb ${n} ${t} with claimed interfaces (${e})${a?` [force]`:``}`)}let l=s.assertExclusive(e,t,i,a,n);n===`close`?await o.close():await o.reset(),s.displaceHandle(e,t,{reason:n,displacedBy:i,displaced:l})}async function KK(e,t,n,r){await OK(e,t).clearHalt(n,r)}const qK=6e4;function JK(){return rw()}function YK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),qK);iw(`usb-device`,e??[],void 0,{timeoutMs:qK}).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 XK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var ZK=class{registry;constructor(e){this.registry=e}usb(){let e=lo();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return jK(this.registry,this.usb())}async request(e){if(JK()){let t=await YK(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 oo(this.registry.register(n),n)}return MK(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(NK(this.registry,e))}open(e){return PK(this.registry,e)}close(e,t){return FK(this.registry,e,QK(t))}selectConfig(e,t){return IK(this.registry,e,t)}claim(e,t,n){return LK(this.registry,e,t,QK(n))}release(e,t,n){return zK(this.registry,e,t,QK(n))}async controlIn(e,t,n){let r=await BK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return VK(this.registry,e,t,XK(n))}async transferIn(e,t,n){let r=await HK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return UK(this.registry,e,t,XK(n))}clearHalt(e,t,n){return KK(this.registry,e,t,n)}reset(e,t){return WK(this.registry,e,QK(t))}subscribeClaimEvents(e){let t,n=import(`./usb-claim-broker-C5dFP5bv.js`).then(n=>{t=n.addClaimListener(this.registry,e)});return()=>{n.then(()=>t?.())}}dropOwner(e){return RK(this.registry,e)}};function QK(e){return{...e,owner:e?.owner??`shell`}}var $K=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;static CLAIM_WAIT_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,t){await this.rpc.call(`usb-close`,{handle:e,owner:t?.owner??`shell`,force:t?.force??!1})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(t,n,r){let i=r?.owner??`shell`,a=r?.wait??!1;try{await this.rpc.call(`usb-claim-interface`,{handle:t,interfaceNumber:n,owner:i,wait:a},a?{timeoutMs:e.CLAIM_WAIT_TIMEOUT_MS}:void 0)}catch(e){throw a&&await this.rpc.call(`usb-cancel-claim-wait`,{handle:t,interfaceNumber:n,owner:i}).catch(()=>void 0),e}}async release(e,t,n){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t,owner:n?.owner??`shell`})}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:XK(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:XK(n)})}async clearHalt(e,t,n){await this.rpc.call(`usb-clear-halt`,{handle:e,direction:t,endpointNumber:n})}async reset(e,t){await this.rpc.call(`usb-reset`,{handle:e,owner:t?.owner??`shell`,force:t?.force??!1})}subscribeClaimEvents(e){return this.rpc.onEvent(`usb-claim-event`,t=>{e(t)})}async dropOwner(e){await this.rpc.call(`usb-drop-owner`,{owner:e})}};function eq(e,t){return e&&lo()?new ZK(uo()):t?new $K(t):null}function tq(e,t,n,r={}){let{header:i,window:a}=sW(t),o=new Map,s=!1,c=r.dispatch??(e=>VU(e)?WU(e):PU(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}=aW(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 nq=r(`realm-host`);let rq=0;function iq(e,t,n={}){let r=new Map,i=new Map,a=`${co}:${++rq}`,o=n.syncFsBridgeEnabled?kU({fs:t.fs,...t.exec?{exec:t.exec}:{},cwd:t.cwd}):void 0,s=!1,c=(t,n=[])=>{if(!s)try{e.postMessage(t,n)}catch{}},l={subscriptions:r,pushEvent:c},u={subscriptions:i,pushEvent:c,owner:a},d=new Map,f={spawns:d,opts:n},p=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;aq(e,i,t,n,l,u,f)};e.addEventListener(`message`,p);let m=o&&n.syncSab?tq(e,n.syncSab,o):void 0;return e.start?.(),{syncFsToken:o,dispose:()=>{if(!s){s=!0,m?.dispose(),o&&MU(o),e.removeEventListener(`message`,p);for(let{controller:e}of d.values())try{e.signal.aborted||e.abort()}catch{}d.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear();for(let e of i.values())try{Promise.resolve(e()).catch(()=>{})}catch{}i.clear();try{(n.usbBackend??lq(n)).dropOwner?.(a)?.catch(()=>{})}catch{}}}}}async function aq(e,t,n,r,i,a,o){try{let s=await oq(t,n,r,i,a,o),c={type:`realm-rpc-res`,id:t.id,result:s},l=Yq(s);e.postMessage(c,l)}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 oq(e,t,n,r,i,a){switch(e.channel){case`vfs`:return fq(e.op,e.args,t);case`exec`:return Tq(e.op,e.args,t,a);case`fetch`:return kq(e.op,e.args,t);case`browser`:return Nq(e.op,e.args,sq(n),n);case`usb`:return Kq(e.op,e.args,lq(n),i);case`serial`:return qq(e.op,e.args,uq(n));case`hid`:return Jq(e.op,e.args,dq(n),r);case`module`:return jq(e.op,e.args,t);case`wasm`:return Mq(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function sq(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 cq(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 lq(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 uq(e){if(e.serialBackend)return e.serialBackend;let t=TK(d(),u());if(!t)throw Error(`serial is not available in this runtime`);return t}function dq(e){if(e.hidBackend)return e.hidBackend;let t=RG(d(),u());if(!t)throw Error(`hid is not available in this runtime`);return t}async function fq(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 xq(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await Sq(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const pq=10485760;function mq(e){return e.fileCount>=500||e.totalBytes>=pq}function hq(e){return e.entries.length>=2e4}async function gq(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 _q(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 vq(e,t,n,r,i){if(n>1048576||mq(r)||r.totalBytes+n>pq){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 yq(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function yq(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await gq(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function bq(e,t,n){if(hq(n))return;let r=[t];for(;r.length>0;){if(hq(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await _q(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await gq(e,t,r,n):a.isFile&&await vq(e,t,a.size,n,r)}}async function xq(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await bq(e,t,n),t!==`/tmp`&&await bq(e,`/tmp`,n),{entries:n.entries}}async function Sq(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 Cq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),wq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function Tq(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 Dq(t,n,r);if(e===`kill`)return Oq(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function Eq(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 Dq(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??{};Eq(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 Oq(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Cq.has(r)?r:`SIGTERM`;wq.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 kq(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?zG(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 Aq(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 jq(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=Aq(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return uG({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:qW({ipk:s}),transpileEntry:JW({ipk:s})})}async function Mq(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 ao(e=>n.fs.readFileBuffer(e),i)}async function Nq(e,t,n,r){switch(e){case`findTab`:return Iq(n,t[0]??{});case`ensureTab`:{let e=t[0];return Lq(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return Rq(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return Rq(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return Hq(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return Uq(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await cq(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return cq(r).update(e,n)}case`wsClose`:{let e=t[0];return cq(r).close(e)}case`wsList`:return cq(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 Vq(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function Pq(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function Fq(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=Pq()?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){nq.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function Iq(e,t){let n=await Fq(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Wq(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 Lq(e,t,n){let r=await Fq(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=Gq(t);if(e){let t=r.find(t=>Gq(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function Rq(e,t,n,r){return e.withTab(t,async e=>zq(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function zq(e){if(typeof e!=`string`)return e;let t=Bq(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=Bq(t);if(typeof e==`object`&&e)return e}return t}return e}function Bq(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 Vq(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(){
|
|
1634
1634
|
try {
|
|
1635
1635
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1646,7 +1646,7 @@ except BaseException:
|
|
|
1646
1646
|
})()`,{returnByValue:!0}))return})}async function Hq(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 Uq(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 Wq(e){try{return new URL(e).hostname}catch{return null}}function Gq(e){try{return new URL(e).origin}catch{return null}}async function Kq(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],{owner:r.owner,force:!!t[1]?.force});case`reset`:return n.reset(t[0],{owner:r.owner,force:!!t[1]?.force});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],{owner:r.owner,wait:!!t[2]?.wait});case`release`:return n.release(t[0],t[1],{owner:r.owner});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]);case`subscribeClaimEvents`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=n.subscribeClaimEvents;if(!i)return!0;let a=i(t=>{t.handle===e&&r.pushEvent({type:`realm-event`,channel:`usb-claim-event`,payload:t})});return r.subscriptions.set(e,a),!0}case`unsubscribeClaimEvents`:{let e=t[0],n=r.subscriptions.get(e);return!n||(r.subscriptions.delete(e),await n(),!0)}default:throw Error(`realm-host: unknown usb op '${e}'`)}}async function qq(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 Jq(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 Yq(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 Xq(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?Zq(e.syncSabBytes):void 0,a=iq(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+`
|
|
1647
1647
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1648
1648
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1649
|
-
`,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 Zq(e){if(cW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let Qq=!1;function $q(e){Qq=e}function eJ(){return Qq}const tJ=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 nJ(e){return tJ[e]??null}function rJ(e,t){let n=nJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let iJ=null;function aJ(e){let t=iJ;return iJ=e,t}async function oJ(){if(!iJ)return{};try{return await iJ()??{}}catch{return{}}}function sJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1649
|
+
`,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 Zq(e){if(cW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let Qq=!1;function $q(e){Qq=e}function eJ(){return Qq}const tJ=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 nJ(e){return tJ[e]??null}function rJ(e,t){let n=nJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let iJ=null;function aJ(e){let t=iJ;return iJ=e,t}async function oJ(){if(!iJ)return{};try{return await iJ()??{}}catch{return{}}}function sJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t);return rJ(t(),e())}}async function cJ(e,t,n,r,i={}){return await n.fs.exists(e)?lJ(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 lJ(e,t,n,r,i={}){let a=i.realmFactory??uJ(),o=r?.processManager??pJ()??fJ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await Xq({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await oJ(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:po(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:eJ()})}function uJ(){return typeof Worker<`u`||typeof document<`u`?NW():kW()}let dJ=null;function fJ(){return dJ||=new Ta,dJ}function pJ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function mJ(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 hJ=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=tn();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?gJ(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=_J(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:_J(i)})})}};async function gJ(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function _J(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function vJ(e,t){return t.length?`${e} ${t.join(` `)}`:e}function yJ(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function bJ(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:yJ(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 xJ={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}},SJ=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function CJ(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 wJ(e,t){switch(e.type){case`CommandSubstitution`:return FJ(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=wJ(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function TJ(e,t){let n=0;for(let r of e.parts){let e=wJ(r,t);if(e===null)return null;n+=e}return n}function EJ(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=TJ(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=TJ(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=CJ(e.name);if(r===null||SJ.has(r))return null;if(!t.has(r))return n;n+=1;let i=xJ[r];if(i){let r=e.args.map(CJ);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(SJ.has(a))return null;t.has(a)&&(n+=1)}return n}function DJ(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 OJ(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||CJ(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=CJ(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 kJ(e){let t=0;for(let n of e){let e=n.type===`Word`?AJ(n.word):DJ(n);if(e===null)return null;t+=e}return t}function AJ(e){let t=OJ(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=kJ(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function jJ(e){let t=0;for(let n of e){let e=AJ(n);if(e===null)return null;t+=e}return t}function MJ(e,t){let n=0;for(let r of e){let e=PJ(r,t);if(e===null)return null;n+=e}return n}function NJ(e,t){switch(e.type){case`SimpleCommand`:return EJ(e,t);case`For`:{if(!e.words)return null;let n=jJ(e.words),r=MJ(e.body,t);return n===null||r===null?null:e.words.filter(e=>OJ(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return MJ(e.body,t);case`FunctionDef`:return 0;default:return null}}function PJ(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=NJ(e,t);if(r===null)return null;n+=r}return n}function FJ(e,t){return MJ(e.statements,t)}function IJ(e,t){let n=FJ(e,t);return{totalSteps:n!==null&&n>0?n:null}}function LJ(e){return e.split(`
|
|
1650
1650
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var RJ=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 zJ=globalThis.setTimeout.bind(globalThis);function BJ(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function VJ(e,t={}){let n=t.now??Date.now,r=t.setTimeout??zJ,i=t.isAborted??(()=>!1),a=t.label??BJ,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 HJ=globalThis.setTimeout.bind(globalThis);function UJ(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 WJ(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 GJ(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??HJ;return{...e,async execute(n,a){let o=WJ(n),s=o>=0?UJ(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=vJ(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 KJ=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 qJ(e,t,n={}){if((n.skip??KJ).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=vJ(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`})}}}}const JJ=new Map([[`jsh`,`node`]]);function YJ(e,t){return`${JJ.get(e)??e} ${t.join(` `)}`.trim()}function XJ(e){return yi(`sudo`,e)}async function ZJ(e,t){let n=e.trim();if(!n||Dee(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:XJ(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const QJ={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 $J(e,t=[],n){let r=QJ[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${Fi(n)}</div>`:``;return`
|
|
1651
1651
|
<div class="sprinkle-action-card">
|
|
1652
1652
|
<div class="sprinkle-action-card__header">
|
|
@@ -1769,7 +1769,7 @@ Examples:
|
|
|
1769
1769
|
skill list
|
|
1770
1770
|
skill info bluebubbles
|
|
1771
1771
|
skill read bluebubbles
|
|
1772
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1772
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-BtA0WqTn.js`).then(e=>e.t);try{switch(r){case`list`:return HY(t,e,i);case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1773
1773
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:BY(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
|
|
1774
1774
|
`,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+`
|
|
1775
1775
|
`,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 WY=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&ee(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=>Io(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=>C(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 GY(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=WY.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 KY(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function qY(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 JY(e,t,n,r){let i=await qY(e,t);return Co(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?KY(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function YY(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await JY(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 wo(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 XY(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 ko(t),d=await jo(s,c,o.ref,u,!0,l||void 0);if(d&&r.sha===d&&await ZY(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await QY(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 YY(e,`${go}/${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 rX(e,{changes:h,writes:g,removals:_}),await Mo(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 ZY(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 QY(e,t,n,r,i,a,o){let s=await Eo(e,t,a,i??`main`);if(s.status===`ok`){let i=xo(s.files),a=n||$Y(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:nX(i,a),path:a}}try{return{files:tX(eX(await To(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 $Y(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 eX(e){return new Map([...e].filter(([e])=>So(e)))}function tX(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function nX(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);So(e)&&r.set(e,i)}return tX(r)}async function rX(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 iX(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 FY(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${go}/${n}/SKILL.md`,u=await qY(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&NY(new TextDecoder().decode(u))===NY(c.content);if(KY(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${go}/${n}`,{recursive:!0}),await e.writeFile(l,d),await Mo(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function aX(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=Io(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 sX(e,t,n){if(t.length===0){let t=await Ao(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await No(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 cX(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1780,7 +1780,7 @@ Examples:
|
|
|
1780
1780
|
`}function dX(e,t,n,r,i){let a=t?`Skill update (dry run — nothing written):
|
|
1781
1781
|
`:`Skill update:
|
|
1782
1782
|
`;for(let n of e)a+=aX(n,t);if(i.length>0&&(a+=uX(i)),!n&&r&&e.length>0){let n=i.length>0?`all ${lX(e.length,`skill`)} with provenance ${e.length===1?`is`:`are`}`:`all skills are`;a+=t?`\n${n.charAt(0).toUpperCase()}${n.slice(1)} current.\n`:`\nNothing to update — ${n} current.\n`}return a}async function fX(e,t,n){let{targets:r,missing:i,skipped:a}=await sX(e,n.skills,{skills:n.skills,dryRun:n.dryRun,json:!1,branch:n.branch,from:n.from,path:n.path}),o=[];for(let i of r)o.push(i.provenance.kind===`browse.sh`?await iX(e,t,i.name,i.provenance,n.dryRun):await XY(e,t,i.name,i.provenance,n.branch,n.dryRun));return{results:o,skipped:a,missing:i}}async function pX(e,t,n){let r=GY(e);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{results:i,missing:a,skipped:o}=await fX(t,n,r);if(i.length===0)return a.length===0&&o.length>0?{stdout:r.json?`${JSON.stringify({ok:!0,dryRun:r.dryRun,results:[],skipped:o})}\n`:dX([],r.dryRun,!1,!0,o),stderr:``,exitCode:0}:{stdout:``,stderr:a.length?a.map(cX).join(``):"upskill: no skill has install provenance yet — reinstall a skill, or run `upskill update <skill> --from <owner>/<repo>`, to record its source\n",exitCode:1};let s=i.filter(e=>e.outcome===`error`),c=i.some(e=>e.outcome===`updated`);c&&!r.dryRun&&await Fo();let l=a.map(cX).join(``)+s.map(e=>`upskill: ${e.skill}: ${e.error}\n`).join(``),u=s.length===0&&a.length===0;return r.json?{stdout:`${JSON.stringify({ok:u,dryRun:r.dryRun,results:i,skipped:o})}\n`,stderr:l,exitCode:+!u}:{stdout:dX(i,r.dryRun,c,u,o),stderr:l,exitCode:+!u}}function mX(e){let t={outdated:!1,json:!1};for(let n of e)if(n===`--outdated`)t.outdated=!0;else if(n===`--json`)t.json=!0;else if(n.startsWith(`-`))return t.error=`upskill: unknown option "${n}" for list`,t;else return t.error=`upskill: unexpected argument "${n}" for list`,t;return t}function hX(e){return e.to&&e.from&&e.to!==e.from?` ${e.from.slice(0,7)} → ${e.to.slice(0,7)}`:e.to?` ${e.to.slice(0,7)}`:``}function gX(e,t){let n=e.filter(e=>e.outcome===`updated`),r=[];if(n.length===0)r.push(`No outdated skills.`);else{r.push(`Outdated skills:`,``);for(let e of n)r.push(` ${e.skill} ${e.source}${hX(e)}`)}if(t.length>0){let e=t.length===1?`skill`:`skills`;r.push(``,`Skipped ${t.length} ${e} with no install provenance — not checked.`)}let i=e.filter(e=>e.outcome===`error`);if(i.length>0){let e=i.length===1?`skill`:`skills`;r.push(``,`Could not check ${i.length} ${e}:`);for(let e of i)r.push(` ${e.skill}: failed — ${e.error}`)}return`${r.join(`
|
|
1783
|
-
`)}\n`}async function _X(e,t){let n=await(await import(`./skills-
|
|
1783
|
+
`)}\n`}async function _X(e,t){let n=await(await import(`./skills-BtA0WqTn.js`).then(e=>e.t)).discoverSkills(e);return t?{stdout:`${JSON.stringify({ok:!0,skills:n})}\n`,stderr:``,exitCode:0}:n.length===0?{stdout:`No discoverable local skills found.\n\n${LY()}`,stderr:``,exitCode:0}:{stdout:zY(n,`Discoverable local skills`),stderr:``,exitCode:0}}async function vX(e,t,n){let{results:r,skipped:i}=await fX(e,t,{skills:[],dryRun:!0}),a=r.filter(e=>e.outcome===`updated`),o=r.filter(e=>e.outcome===`error`),s=o.length===0,c=o.map(e=>`upskill: ${e.skill}: ${e.error}\n`).join(``);return n?{stdout:`${JSON.stringify({ok:s,results:[...a,...o],skipped:i})}\n`,stderr:c,exitCode:+!s}:{stdout:gX(r,i),stderr:c,exitCode:+!s}}async function yX(e,t,n){let r=mX(e);return r.error?{stdout:``,stderr:`${r.error}\n`,exitCode:1}:r.outdated?vX(t,n,r.json):_X(t,r.json)}async function bX(e,t){let n=`${_o}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(Oo(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=Se(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=Po(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function xX(e,t){let n=`${_o}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${Oo(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=Se(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=Po(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const SX=[{label:`Tessl`,host:new URL(_o).host,fetch:bX},{label:`browse.sh`,host:new URL(bo).host,fetch:DY}];function CX(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function wX(e,t,n=1){let r=await Promise.allSettled(SX.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=CX(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=SX[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
|
|
1784
1784
|
`}return u<l&&(p+=`Showing ${d+1}-${d+f.length} of ${c}. `,p+=`Next page: upskill search ${e} --page ${u+1}\n\n`),p+=`To install:
|
|
1785
1785
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
1786
1786
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
@@ -1803,7 +1803,7 @@ Examples:
|
|
|
1803
1803
|
`,{stdout:s,stderr:``,exitCode:0}}function jX(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1804
1804
|
`,exitCode:1}:ee(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
|
|
1805
1805
|
`,exitCode:1}}function MX(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`||!C(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
|
|
1806
|
-
`,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=jX(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 NX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-
|
|
1806
|
+
`,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=jX(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 NX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-BtA0WqTn.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 No(n,t),a=i?Oee(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:BY(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+`
|
|
1807
1807
|
`,stderr:``,exitCode:0}}async function PX(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 Ro(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 FX(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 Lo(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 IX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await Lo(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 LX(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 RX(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await ko(r),l=await zo(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:LX(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:LX(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 Eo(i,a,r,o);if(e.status===`ok`){let r=await jo(i,a,o,c,!0,s),l=await PX(u,i,a,xo(e.files),n,t.force,f,{kind:`github`,source:`${i}/${a}`,ref:o,sha:r});({output:p,errors:m,successCount:h}=l)}else{let e=await FX(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await IX(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 Fo()),{stdout:p,stderr:m,exitCode:+!!m}}async function zX(e,t,n,r){switch(e[0]){case`tabs`:return kX(t,n,r,e.includes(`--json`));case`recommendations`:return AX(t,n,e.includes(`--install`));case`update`:case`upgrade`:return pX(e.slice(1),t,n);case`list`:return yX(e.slice(1),t,n);case`info`:case`read`:return NX(e[0],e[1],t);case`search`:return VX(e,n);default:return null}}function BX(e,t,n){return V(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return VY();let a=await zX(r,e,t,n);if(a)return a;let o=MX(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return VY();if(o.sourceRef.startsWith(`tessl:`))return HX(o.sourceRef,o.force,e,t);let s=AY(o.sourceRef);if(s)return IY(s.hostname,s.task,e,t,o.force);let c=Io(o.sourceRef);return c?RX(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 VX(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?wX(a,t,i):VY()}async function HX(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1808
1808
|
`,exitCode:1};let a=await xX(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await ko(r);return Lo(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function UX(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1809
1809
|
|
|
@@ -2224,7 +2224,7 @@ Examples:
|
|
|
2224
2224
|
`;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+=`
|
|
2225
2225
|
`;return t}async function S1(e,t){let n=H(e.slice(1),{});if(`error`in n)return y1(n.error);if(!t()){let e=await f1();if(!e)return h1(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2226
2226
|
`,stderr:``,exitCode:0}:{stdout:x1(t),stderr:``,exitCode:0}}let{ok:r,data:i}=await _1(`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
|
|
2227
|
-
`,stderr:``,exitCode:0}:{stdout:x1(a),stderr:``,exitCode:0}}async function C1(e,t){let n=e[0],r=H(e.slice(1),{});if(`error`in r)return y1(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 f1();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}:h1(`delete`)}let{ok:a,status:o,data:s}=await _1(`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 w1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return V(`crontask`,async(e,n)=>{let r=e[0];if(!r||oi(e,{valueFlags:v1}))return g1();try{switch(r){case`create`:return await b1(e,n.env,t);case`list`:return await S1(e,t);case`delete`:case`kill`:return await C1(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 T1(e){return V(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2227
|
+
`,stderr:``,exitCode:0}:{stdout:x1(a),stderr:``,exitCode:0}}async function C1(e,t){let n=e[0],r=H(e.slice(1),{});if(`error`in r)return y1(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 f1();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}:h1(`delete`)}let{ok:a,status:o,data:s}=await _1(`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 w1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return V(`crontask`,async(e,n)=>{let r=e[0];if(!r||oi(e,{valueFlags:v1}))return g1();try{switch(r){case`create`:return await b1(e,n.env,t);case`list`:return await S1(e,t);case`delete`:case`kill`:return await C1(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 T1(e){return V(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-C5mIkEGQ.js`);return r(e,t,n)})}const E1=`slicc-fs`;async function D1(){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===E1)}catch{return!0}}async function O1(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(E1)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function k1(){if(!await D1())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await O1();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 A1(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2228
2228
|
|
|
2229
2229
|
Usage:
|
|
2230
2230
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -2716,7 +2716,7 @@ Options:
|
|
|
2716
2716
|
`,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 C4(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!ea(e))throw e}t.sessionDirsCreated=!0}}async function wue(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(`
|
|
2717
2717
|
`),p=`/.playwright/snapshots/page-${Qi(new Date)}.yml`;return await t.writeFile(p,f),p})}catch{return null}}async function Tue(e,t,n){await C4(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(`
|
|
2718
2718
|
`)+`
|
|
2719
|
-
`,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 w4(){return import(`./snapshot-features-
|
|
2719
|
+
`,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 w4(){return import(`./snapshot-features-ChEbT7az.js`)}async function Eue(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(`
|
|
2720
2720
|
`);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 Due(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() {
|
|
2721
2721
|
this.scrollIntoView({ block: 'center' });
|
|
2722
2722
|
const r = this.getBoundingClientRect();
|
|
@@ -2794,7 +2794,7 @@ Options:
|
|
|
2794
2794
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2795
2795
|
return el.files.length;
|
|
2796
2796
|
})()`,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`,Iue],[`state-load`,Lue],[`console`,$ce],[`requests`,uue],[`request`,due],[`request-headers`,fue],[`request-body`,pue],[`response-headers`,mue],[`response-body`,hue],[`mousemove`,Fle],[`mousedown`,Ile],[`mouseup`,Lle],[`mousewheel`,Rle],[`drop`,zle],[`route`,xue],[`route-list`,Sue],[`unroute`,Cue],[`generate-locator`,sle],[`highlight`,cle]]);function Que(){let e=(ra.string??[]).map(e=>`--${e}`),t=new Set(ra.boolean??[]);for(let[e,n]of Object.entries(ra.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 $ue(e){return e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e)}function ede(e){return{...e,bool:[...e.bool??[],`--_noiframes`],value:[...e.value??[],`--_noiframes`]}}const F4=2e3;function tde(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 nde(e,t,n,r){if(!t||typeof e.getTabLockStats!=`function`)return r;let i=e.getTabLockStats(),a=i.totalWaitMs-t.totalWaitMs;if(a<F4)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>=F4?`${(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.
|
|
2797
|
-
`;return{...r,stderr:r.stderr+c}}async function rde(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await ia(e,t.tab,n):null)??r}\n`,exitCode:1}}function I4(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 ide(e,t,n){let r=Zue.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?I4(e,t,void 0):a}catch(r){return i?.aborted?I4(e,t,r):await rde(n.browser,n.flags,r)}}async function ade(e,t,n,r){let i=H($ue(n),ede(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=na(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-
|
|
2797
|
+
`;return{...r,stderr:r.stderr+c}}async function rde(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await ia(e,t.tab,n):null)??r}\n`,exitCode:1}}function I4(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 ide(e,t,n){let r=Zue.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?I4(e,t,void 0):a}catch(r){return i?.aborted?I4(e,t,r):await rde(n.browser,n.flags,r)}}async function ade(e,t,n,r){let i=H($ue(n),ede(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=na(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-dNszPyQ5.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 ode(e,t,n){let r=t?$i(t,n):null,i=Que();return V(e,async(a,o)=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`){let{formatHelp:t}=await import(`./help-dNszPyQ5.js`);return{stdout:t(e)+`
|
|
2798
2798
|
`,stderr:``,exitCode:0}}let s=a[0],c=a.slice(1),l=await ade(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=tde(t,f),m=await ide(e,s,{browser:t,fs:n,state:r,positional:u,flags:d,scratchDir:eo(o.env),onTab:(e,n)=>t.withTab(e,n,{signal:o.signal}),signal:o.signal}),h=d.tab??null,g=null;ua.has(s)&&m.exitCode===0&&h&&(g=await wue(t,n,h,r));try{await Tue(n,r,{command:s,args:c,result:m,snapshotPath:g,targetId:h})}catch{}return nde(t,p,f,m)})}const sde=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`,`jsh`,`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`,...ca,`sprinkle`]],[`Clipboard`,[`pbcopy`,`pbpaste`,`xclip`,`xsel`]],[`Filesystem`,[`mount`,`umount`,`fswatch`]],[`Scoops & agents`,[`agent`,`gelatiere`,`mcp`,`webhook`,`crontask`]],[`Process`,[`ps`,`kill`,`meminfo`,`uptime`]],[`Shell builtins (limited)`,[...OZ]]]);function cde(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:
|
|
2799
2799
|
`);let a=[];for(let[e,t]of sde){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(`
|
|
2800
2800
|
`)+`
|
|
@@ -3052,7 +3052,7 @@ Common base URLs:
|
|
|
3052
3052
|
`)+`
|
|
3053
3053
|
`,stderr:``,exitCode:0}}function dpe(e,t){let n=t.models.length;return{stdout:[`✓ ${e} (${J3(t.runtime,!1)})`,` Saved ${n} model${n===1?``:`s`} to Settings:`,...Y3(t.models)].join(`
|
|
3054
3054
|
`)+`
|
|
3055
|
-
`,stderr:``,exitCode:0}}function fpe(){return V(q3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:cpe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
3055
|
+
`,stderr:``,exitCode:0}}function fpe(){return V(q3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:cpe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-55U-3pMU.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(q3);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
3056
3056
|
`,exitCode:1};let c=await a(s,t(q3)??void 0);if(!c.ok)return lpe(s,c);if(o===`discover`){let e=n(q3)??``;return i(q3,e,s,c.models.join(`, `)),dpe(s,c)}return upe(s,c)})}function ppe(){return{stdout:`usage: man <topic>
|
|
3057
3057
|
|
|
3058
3058
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3090,20 +3090,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3090
3090
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3091
3091
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3092
3092
|
short name resolves on the PATH.
|
|
3093
|
-
`);let n=H(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length<2)return $3(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return $3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return $3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3093
|
+
`);let n=H(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length<2)return $3(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return $3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return $3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CxD6rJNd.js`).then(e=>e.r);if(await a(i,t.fs))return $3(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-B6iKb_ye.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 bpe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>a6(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 zpe(i,t);let m=await c6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-B5DqJTXt.js`);e({name:i,serverUrl:r,auth:u})}return Q3([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${Z3}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3094
3094
|
`)+`
|
|
3095
|
-
`)}async function bpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3096
|
-
`);let n=H(e,{});if(`error`in n)return e6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3095
|
+
`)}async function bpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t),c=await Lpe(r.oauthFetchImpl),l=r.oauthLauncher??await o6(),u=await i(e,n,c);X3.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await Xee(rn()),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 xpe(e,t){if(oi(e))return Q3(`usage: mcp list
|
|
3096
|
+
`);let n=H(e,{});if(`error`in n)return e6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-B5DqJTXt.js`);await r();let{listServers:i}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),a=await i(t.fs),o=Object.keys(a).sort();if(o.length===0)return Q3("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 Q3(t6(s))}function t6(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(`
|
|
3097
3097
|
`)+`
|
|
3098
3098
|
`}async function Spe(e,t){if(oi(e))return Q3(`usage: mcp search <query>
|
|
3099
3099
|
|
|
3100
3100
|
Case-insensitive substring search across the cached tools of every
|
|
3101
3101
|
registered MCP server. Matches tool name OR description and prints a
|
|
3102
3102
|
table of (server, tool, description, match-field) rows.
|
|
3103
|
-
`);let n=H(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length===0)return $3(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-
|
|
3104
|
-
`);let n=H(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-
|
|
3103
|
+
`);let n=H(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length===0)return $3(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-B5DqJTXt.js`);await a();let{listServers:o}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),s=await o(t.fs),c=Object.keys(s).sort();if(c.length===0)return Q3("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 Q3(`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,Cpe(e.description),e.match]);return Q3(t6(u))}function Cpe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function wpe(e,t){if(e.length===0||oi(e))return e.length===0?$3(`mcp delete: expected <name>`):Q3(`usage: mcp delete <name>
|
|
3104
|
+
`);let n=H(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-B5DqJTXt.js`);await i(r);let{deleteServer:o}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),s=await o(r,t.fs);await Bpe(r,t),await Vpe(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t);t().some(e=>e.providerId===c)&&(await e(c),l=!0)}catch(e){X3.warn(`mcp delete: OAuth removal failed`,{providerId:c,error:e instanceof Error?e.message:String(e)})}let u=a(r);return!s&&!l&&!u?$3(`mcp delete: no server, alias, or account found for "${r}"`):Q3([`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(`
|
|
3105
3105
|
`)+`
|
|
3106
|
-
`)}async function Tpe(e,t){if(e.length===0)return $3(`mcp invoke: expected <name>`);if(oi(e.slice(0,1)))return Q3(Dpe());let n=H([e[0]],{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-
|
|
3106
|
+
`)}async function Tpe(e,t){if(e.length===0)return $3(`mcp invoke: expected <name>`);if(oi(e.slice(0,1)))return Q3(Dpe());let n=H([e[0]],{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-B5DqJTXt.js`);await a(r);let{getServer:o}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),s=await o(r,t.fs);if(!s)return $3(`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 Q3(Ope(r,s,c));let l=H([i[0]],{});if(`error`in l)return e6(l.error);let u=l.positionals[0];if(!u)return $3(`mcp invoke: expected <tool>`);let d=c.find(e=>e.name===u);if(!d)return $3(`mcp invoke: unknown tool "${u}" on "${r}" (run \`${r}\` to list tools)`);let{timeoutMs:f,remaining:p,warnings:m}=Epe(i.slice(1));if(oi(p))return Q3(kpe(r,d));let h=Ape(p,d.inputSchema);if(!h.ok)return $3(`mcp invoke: ${h.error}`);let{McpClient:g}=await import(`./client-B6iKb_ye.js`).then(e=>e.n),_=new g({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>a6(r):void 0,...f===void 0?{}:{timeoutMs:f}});await _.initialize();let v=Ppe(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function Epe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=n6(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=n6(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 n6(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 Dpe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3107
3107
|
|
|
3108
3108
|
mcp invoke <name> List tools on <name>.
|
|
3109
3109
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3133,7 +3133,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3133
3133
|
|
|
3134
3134
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3135
3135
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3136
|
-
`);let n=H(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3136
|
+
`);let n=H(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-B5DqJTXt.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),s=await a(r,t.fs);if(!s)return $3(`mcp refresh: unknown server "${r}"`);let{McpClient:c,McpAuthRequiredError:l}=await import(`./client-B6iKb_ye.js`).then(e=>e.n),u=new c({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>a6(r):void 0});try{await u.initialize()}catch(e){if(e instanceof l)return $3(`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 c6(r,f,t);return Q3(`Refreshed "${r}" — tools: ${d.length}, apps: ${f.length} (${p} sprinkle${p===1?``:`s`})\n`)}async function Ipe(e,t){if(oi(e))return Q3(`usage: mcp auth <name> [--silent | --interactive]
|
|
3137
3137
|
|
|
3138
3138
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3139
3139
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3145,7 +3145,7 @@ Options:
|
|
|
3145
3145
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3146
3146
|
directly. Use after revoking a refresh token or
|
|
3147
3147
|
when the AS no longer accepts the cached one.
|
|
3148
|
-
`);let n=H(e,{bool:gpe});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`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 $3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3148
|
+
`);let n=H(e,{bool:gpe});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`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 $3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-B5DqJTXt.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-CxD6rJNd.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return $3(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return $3(`mcp auth: server "${r}" does not use OAuth`);if(!s)return $3(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-DuCgei7-.js`).then(e=>e.r),f=d(u);if(!f)return $3(`mcp auth: provider "${u}" is not registered`);if(a)return await i6(r,f,t);if(!f.onSilentRenew)return i?$3(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await i6(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 $3(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);X3.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?Q3(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?$3(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await i6(r,f,t)}async function i6(e,t,n){if(!t.onOAuthLogin)return $3(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await o6(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?Q3(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):$3(`mcp auth: interactive login for "${e}" did not complete`)}async function a6(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DuCgei7-.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){X3.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function o6(){let{createOAuthLauncher:e}=await import(`./oauth-service-IlBYPvwr.js`);return e()}async function Lpe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-DEK8DT-z.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 s6(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DixtpMlv.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return await t.create({dbName:n})}function Rpe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3149
3149
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3150
3150
|
const { promisify } = require('util');
|
|
3151
3151
|
const { exec } = require('child_process');
|
|
@@ -3174,7 +3174,7 @@ try {
|
|
|
3174
3174
|
if (stdout) process.stdout.write(stdout);
|
|
3175
3175
|
if (stderr) process.stderr.write(stderr);
|
|
3176
3176
|
process.exit(exitCode);
|
|
3177
|
-
`}async function zpe(e,t){let n=await s6(t.fs);await n.mkdir(Z3,{recursive:!0}),await n.writeFile(`${Z3}/${e}.jsh`,Rpe(e)),t.scriptCatalog?.invalidateJsh()}async function Bpe(e,t){let n=await s6(t.fs),r=`${Z3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){X3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Vpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3177
|
+
`}async function zpe(e,t){let n=await s6(t.fs);await n.mkdir(Z3,{recursive:!0}),await n.writeFile(`${Z3}/${e}.jsh`,Rpe(e)),t.scriptCatalog?.invalidateJsh()}async function Bpe(e,t){let n=await s6(t.fs),r=`${Z3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){X3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Vpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-Cvv2F8Zd.js`);await n(e,t.fs)}async function c6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-Cvv2F8Zd.js`);return(await r(e,t,n.fs)).length}catch(t){return X3.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function l6(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function u6(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 Hpe(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 Upe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function Wpe(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 Gpe(e){let t=[`total: ${u6(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(`${u6(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${Hpe(e)}`)}return`${t.join(`
|
|
3178
3178
|
`)}\n`}function Kpe(e={}){return V(`meminfo`,async t=>{let n=Wpe(t);if(`error`in n)return l6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3179
3179
|
|
|
3180
3180
|
Usage:
|
|
@@ -3201,7 +3201,7 @@ Options:
|
|
|
3201
3201
|
-h, --help Show this help message
|
|
3202
3202
|
`}function rme(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function h6(e){return`$${e.toFixed(2)}`}const ime=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function ame(e){let t=`${e.id} ${e.name??``}`;return!ime.test(t)}function ome(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 sme(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),ome(t)??t.replace(/-[\d.]+$/,``)}function cme(e){let t=new Map;for(let n of e){let e=sme(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function lme(e,t,n,r,i){let a=i?tme(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 ume(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=`${h6(e.cost.input)} / ${h6(e.cost.output)}`,a=`${rme(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(`
|
|
3203
3203
|
`)+`
|
|
3204
|
-
`}function dme(e){let t=H(e,{bool:Ype,value:f6});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 fme(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 pme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(ame);if(o.length===0)return[];let s=o.map(e=>lme(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=cme(s)),s}function mme(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 hme(e,t){if(oi(e,{valueFlags:f6}))return{stdout:nme(),stderr:``,exitCode:0};let n=dme(e);if(`error`in n)return p6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3204
|
+
`}function dme(e){let t=H(e,{bool:Ype,value:f6});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 fme(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 pme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(ame);if(o.length===0)return[];let s=o.map(e=>lme(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=cme(s)),s}function mme(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 hme(e,t){if(oi(e,{valueFlags:f6}))return{stdout:nme(),stderr:``,exitCode:0};let n=dme(e);if(`error`in n)return p6(`models: ${n.error}`);let r=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t);if(r.getAccounts().length===0)return p6(`No provider accounts configured. Run the provider settings to add one.
|
|
3205
3205
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await eme(t,n.forceRefresh);e.length>0&&(l=e)}let u=fme(r,n,s);if(`error`in u)return p6(u.error);let d=[],f=[];for(let e of u){let t=pme(r,e,a,o,l,n.allVersions);if(t.length===0){if(!n.allMode)return p6(`No models available for provider ${e}.\n`);continue}if(d.push(...t),!n.jsonMode){let n=r.getProviderConfig(e);f.push(ume(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3206
3206
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3207
3207
|
`),f.push(mme(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3259,7 +3259,7 @@ Examples:
|
|
|
3259
3259
|
`)}\n`,stderr:``,exitCode:0}}async function Pme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3260
3260
|
`,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 Fme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3261
3261
|
`,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 Ime(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>
|
|
3262
|
-
`,exitCode:1}}async function Lme(e,t,n,r){switch(t){case`list`:return Nme(e,n);case`add`:return Pme(e,n,r);case`remove`:return Fme(e,n,r);case`clear`:return Ime(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${b6()}`,exitCode:1}}}function Rme(){return V(`oauth-domain`,async e=>{if(e.length===0||oi(e))return{stdout:b6(),stderr:``,exitCode:0};let t=H(e);if(`error`in t)return x6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3262
|
+
`,exitCode:1}}async function Lme(e,t,n,r){switch(t){case`list`:return Nme(e,n);case`add`:return Pme(e,n,r);case`remove`:return Fme(e,n,r);case`clear`:return Ime(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${b6()}`,exitCode:1}}}function Rme(){return V(`oauth-domain`,async e=>{if(e.length===0||oi(e))return{stdout:b6(),stderr:``,exitCode:0};let t=H(e);if(`error`in t)return x6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-6WG1S7Pm.js`).then(e=>e.t);try{return await Lme(a,n,r,i)}catch(e){return x6(e instanceof Error?e.message:String(e))}})}function zme(){return V(`oauth-token`,async(e,t)=>{let{runOAuthToken:n}=await import(`./run-Dckyjx6-.js`);return n(e,t)})}const Bme=[`--download`,`-d`,`--view`,`-v`],S6=[`--size`],C6={low:256,medium:768,high:1536};function w6(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
3263
3263
|
|
|
3264
3264
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
3265
3265
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -3285,7 +3285,7 @@ Examples:
|
|
|
3285
3285
|
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=kN(e,await Fa(t.fs,i?e:Ga(e))),o;try{o=await r(a)}catch(e){return D6(`${e instanceof Error?e.message:String(e)}\n`)}return E6(`opened ${e} → ${a}${O6(o)}`)}async function ehe(e,t,n,r){if(!La(e)&&e.endsWith(`.shtml`)&&t.fs)return Yme(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return D6(`open: browser APIs are unavailable in this environment
|
|
3286
3286
|
`);if(La(e))return Xme(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?Zme(e,i,t,n.sizeSpec):n.download?Qme(e,i,t,r.hasDom):$me(i,t,r.canOpenWindow,r.openExternal)}function the(e){return V(`open`,async(t,n)=>{if(t.length===0||oi(t,{valueFlags:S6}))return w6();let r=qme(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 w6();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:Jme(e,l,d)},p=[];for(let e of s){let t=await ehe(e,n,{view:a,download:i,sizeSpec:o},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
3287
3287
|
`)+`
|
|
3288
|
-
`,stderr:``,exitCode:0}})}function nhe(){return V(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-
|
|
3288
|
+
`,stderr:``,exitCode:0}})}function nhe(){return V(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-DnO5hH4e.js`);return n(e,t)})}function k6(e=`pdftk`){return V(e,async(t,n)=>{let{runPdftk:r}=await import(`./run-ChkY2Agc.js`);return r(e,t,n)})}function rhe(){return{stdout:`usage: pdftoppm [options] <input.pdf> [output-prefix]
|
|
3289
3289
|
|
|
3290
3290
|
Rasterize PDF pages to images. Writes <prefix>-<n>.<ext> per page, where <n>
|
|
3291
3291
|
is zero-padded to the digit width of the last page (out-1.png for a 9-page
|
|
@@ -3345,7 +3345,7 @@ Examples:
|
|
|
3345
3345
|
plugin list
|
|
3346
3346
|
plugin info my-plugin
|
|
3347
3347
|
plugin remove my-plugin
|
|
3348
|
-
`}function hhe(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return N6(mhe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await _he(i,a,e);case`list`:case`ls`:return await xhe(i,e);case`info`:return await She(i,e);case`validate`:return await Che(i,a,e,eo(n?.env));case`remove`:case`rm`:case`delete`:return await whe(i,e);default:return P6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return P6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function I6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3348
|
+
`}function hhe(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return N6(mhe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await _he(i,a,e);case`list`:case`ls`:return await xhe(i,e);case`info`:return await She(i,e);case`validate`:return await Che(i,a,e,eo(n?.env));case`remove`:case`rm`:case`delete`:return await whe(i,e);default:return P6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return P6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function I6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-DixtpMlv.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 L6(e,t,n){let r=The(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-CG84acvy.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 ghe(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function R6(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${M6}/${t.map(ghe).join(`--`)}`}async function z6(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-Dei-4lGa.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 B6(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function _he(e,t,n){if(oi(e))return N6(`usage: plugin install <path|repo>
|
|
3349
3349
|
|
|
3350
3350
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3351
3351
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3356,19 +3356,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3356
3356
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3357
3357
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3358
3358
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3359
|
-
`);let r=F6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return P6(`plugin install: expected <path|repo>`);let i=await I6(n),a=await L6(r.positionals[0],t,i);if(a.kind===`error`)return P6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return P6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=R6(a.ref),s=a.ref.display;let e=await z6(a.ref,o,i,n.fetch);if(e)return P6(`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 B6(i,o),P6(`plugin install: plugin at ${s??o} was rejected:\n${V6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3359
|
+
`);let r=F6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return P6(`plugin install: expected <path|repo>`);let i=await I6(n),a=await L6(r.positionals[0],t,i);if(a.kind===`error`)return P6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return P6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=R6(a.ref),s=a.ref.display;let e=await z6(a.ref,o,i,n.fetch);if(e)return P6(`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 B6(i,o),P6(`plugin install: plugin at ${s??o} was rejected:\n${V6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-D0akwt8a.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await B6(i,o),P6(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await bhe(u,n),g=await yhe(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),N6(vhe(u,h,g,s??o,l.diagnostics))}function vhe(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:`,V6(i)),c.join(`
|
|
3360
3360
|
`)+`
|
|
3361
|
-
`}async function yhe(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-
|
|
3362
|
-
`);let n=F6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3361
|
+
`}async function yhe(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-CxD6rJNd.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 bhe(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-CxD6rJNd.js`).then(e=>e.r),{McpClient:a}=await import(`./client-B6iKb_ye.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 xhe(e,t){if(oi(e))return N6(`usage: plugin list
|
|
3362
|
+
`);let n=F6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-D0akwt8a.js`),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return N6("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 N6(o.map(e=>e.map((e,t)=>e.padEnd(s[t])).join(` `)).join(`
|
|
3363
3363
|
`)+`
|
|
3364
3364
|
`)}async function She(e,t){if(oi(e))return N6(`usage: plugin info <name>
|
|
3365
|
-
`);let n=F6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-
|
|
3365
|
+
`);let n=F6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-D0akwt8a.js`),a=await i(r,t.fs);if(!a)return P6(`plugin info: no installed plugin named "${r}"`);let o=await I6(t),{loadPluginFromDirectory:s}=await import(`./loader-Dw-TPPKt.js`),c=await s(o,a.root);if(!c.ok)return P6(`plugin info: plugin at ${a.root} no longer loads:\n${V6(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:`,V6(c.diagnostics)),N6(d.join(`
|
|
3366
3366
|
`)+`
|
|
3367
3367
|
`)}async function Che(e,t,n,r){if(oi(e))return N6(`usage: plugin validate <path|repo>
|
|
3368
3368
|
`);let i=F6(`validate`,e);if(!(`ok`in i))return i;if(i.positionals.length<1)return P6(`plugin validate: expected <path|repo>`);let a=await I6(n),o=await L6(i.positionals[0],t,a);if(o.kind===`error`)return P6(`plugin validate: ${o.message}`);let s,c=null;if(o.kind===`github`){if(!n.fetch)return P6(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);c=`${r}/.plugin-validate/${R6(o.ref).split(`/`).pop()}`;let e=await z6(o.ref,c,a,n.fetch);if(e)return P6(`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 B6(a,c)}if(!u.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${V6(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:`,V6(u.diagnostics)),N6(p.join(`
|
|
3369
3369
|
`)+`
|
|
3370
3370
|
`)}async function whe(e,t){if(oi(e))return N6(`usage: plugin remove <name>
|
|
3371
|
-
`);let n=F6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-
|
|
3371
|
+
`);let n=F6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-D0akwt8a.js`),o=await i(r,t.fs);if(!o)return P6(`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-CxD6rJNd.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(`${M6}/`);return c&&await B6(await I6(t),o.root),N6([`Removed agent plugin "${r}"`,` registry: removed`,` mcp servers: ${s} removed`,c?` files: removed (${o.root})`:` files: left in place (${o.root})`].join(`
|
|
3372
3372
|
`)+`
|
|
3373
3373
|
`)}function The(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 V6(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3374
3374
|
`)}const H6=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Ehe=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Dhe={running:`R`,pending:`S`,exited:`Z`,killed:`K`},Ohe=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],U6=[`-o`,`--columns`];function khe(e={}){return V(`ps`,async t=>{if(oi(t,{valueFlags:U6}))return Vhe();let n=e.processManager??Ahe();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -3406,7 +3406,7 @@ Examples:
|
|
|
3406
3406
|
ps -o pid,kind,stat just three columns
|
|
3407
3407
|
`,stderr:``,exitCode:0}}const Hhe=new Set([`dev`,`proc`,`lib`,`bin`,`usr`,`etc`,`home`,`tmp`]);async function Uhe(e,t=Hhe){let n=[],r=new Set;try{let i=await e.readdir(`/`);for(let a of i){if(!a||a.includes(`/`)||t.has(a))continue;let i=`/${a}`,o=!1;try{o=!!(await e.stat(i)).isDirectory}catch{continue}o&&(r.has(i)||(r.add(i),n.push(i)))}}catch{}return r.has(`/tmp`)||(r.add(`/tmp`),n.push(`/tmp`)),n}function Whe(e,t){let n=e;if(typeof n.listMountPoints!=`function`)return[];let r=e=>{for(let n of t)if(e===n||e.startsWith(n===`/`?`/`:n+`/`)||n.startsWith(e+`/`))return!0;return!1},i=[];for(let e of n.listMountPoints())e.kind!==`proc`&&r(e.path)&&i.push({path:e.path,kind:e.kind});return i}function Ghe(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`slicc-fs`}catch{}}function Khe(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},fromDir:e.cwd}}async function qhe(e,t){try{let n=await e.readFile(`${t}/package.json`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function Jhe(e,t){return`installed pyodide ${e} is not the supported version ${t}: run \`ipk uninstall pyodide\` then \`ipk add pyodide@${t}\``}function Yhe(){return{stdout:`usage: python3 [-c code | script.py] [args...]
|
|
3408
3408
|
`,stderr:``,exitCode:0}}function Xhe(){return{stdout:`Python 3.14 (Pyodide)
|
|
3409
|
-
`,stderr:``,exitCode:0}}async function Zhe(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return mo(n.stdin).trim().length>0?{kind:`ok`,code:mo(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function Qhe(e){let t=Khe(e),n=await WP(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${HP}\n`,exitCode:1}};let r=await qhe(t.reader,n);return r?r===BP?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${Jhe(r,BP)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${HP}\n`,exitCode:1}}}function W6(e,t={}){return V(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return Yhe();if(n.includes(`--version`)||n.includes(`-V`))return Xhe();let i=await Zhe(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await Uhe(r.fs),u=Whe(r.fs,l),d=t.buildProcessConfig?.(r.env),f=d?.processManager??$he(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??NW(),g=t.pyodideIndexURL??LW(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await Qhe(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:mo(r.stdin),y=Ghe();return f?Xq({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):ege({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function $he(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let G6=null;async function ege(e){if(!G6){let{ProcessManager:e}=await import(`./process-manager-BkhAohXT.js`).then(e=>e.n);G6=new e}return Xq({pm:G6,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function K6(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function
|
|
3409
|
+
`,stderr:``,exitCode:0}}async function Zhe(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return mo(n.stdin).trim().length>0?{kind:`ok`,code:mo(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function Qhe(e){let t=Khe(e),n=await WP(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${HP}\n`,exitCode:1}};let r=await qhe(t.reader,n);return r?r===BP?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${Jhe(r,BP)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${HP}\n`,exitCode:1}}}function W6(e,t={}){return V(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return Yhe();if(n.includes(`--version`)||n.includes(`-V`))return Xhe();let i=await Zhe(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await Uhe(r.fs),u=Whe(r.fs,l),d=t.buildProcessConfig?.(r.env),f=d?.processManager??$he(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??NW(),g=t.pyodideIndexURL??LW(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await Qhe(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:mo(r.stdin),y=Ghe();return f?Xq({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):ege({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function $he(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let G6=null;async function ege(e){if(!G6){let{ProcessManager:e}=await import(`./process-manager-BkhAohXT.js`).then(e=>e.n);G6=new e}return Xq({pm:G6,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function tge(){return V(`rg`,async(e,t)=>{let{runRg:n}=await import(`./run-CuXkU2qx.js`);return n(e,t)})}function K6(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function nge(){return null}function rge(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=q6(r),o=q6(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function q6(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function J6(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
|
|
3410
3410
|
|
|
3411
3411
|
Usage:
|
|
3412
3412
|
rsync [flags] <local-path> <runtime-id>:<remote-path> # push
|
|
@@ -3422,21 +3422,21 @@ Examples:
|
|
|
3422
3422
|
rsync /workspace follower-abc123:/workspace
|
|
3423
3423
|
rsync --delete /shared leader:/shared
|
|
3424
3424
|
rsync follower-abc123:/workspace/project /workspace/project
|
|
3425
|
-
`,stderr:``,exitCode:0}}async function Y6(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function X6(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function
|
|
3425
|
+
`,stderr:``,exitCode:0}}async function Y6(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function X6(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function ige(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function age(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function Z6(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function oge(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=K6(await Y6(e,i),await X6(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
3426
3426
|
`)+`
|
|
3427
|
-
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await
|
|
3427
|
+
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await age(t,o,Z6(c));let l=await e.readFile(s,{encoding:`binary`}),u=await t(o,{op:`writeFile`,path:c,content:v(l),encoding:`base64`});if(!u[0].ok)return{stdout:r.join(`
|
|
3428
3428
|
`)+`
|
|
3429
3429
|
`,stderr:`Error writing ${c}: ${u[0].error}\n`,exitCode:1}}for(let e of l.toDelete){let n=a+`/`+e,i=await t(o,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
|
|
3430
3430
|
`)+`
|
|
3431
3431
|
`,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
3432
3432
|
`)+`
|
|
3433
|
-
`,stderr:``,exitCode:0}}async function
|
|
3433
|
+
`,stderr:``,exitCode:0}}async function sge(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=K6(await X6(t,o,a),await Y6(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
3434
3434
|
`)+`
|
|
3435
|
-
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=Z6(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=await
|
|
3435
|
+
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=Z6(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=await ige(t,o,r),u=y(l);await e.writeFile(s,u)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
3436
3436
|
`)+`
|
|
3437
|
-
`,stderr:``,exitCode:0}}function
|
|
3437
|
+
`,stderr:``,exitCode:0}}function cge(e={}){let t=e.fs,n=e.getSendFsRequest??nge;return V(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return J6();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
|
|
3438
3438
|
`,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
|
|
3439
|
-
`,exitCode:1};let i=
|
|
3439
|
+
`,exitCode:1};let i=rge(e);if(`error`in i)return i.error===`__help__`?J6():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await oge(t,r,i):await sge(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Q6(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
|
|
3440
3440
|
say --status | --warmup
|
|
3441
3441
|
|
|
3442
3442
|
Speaks the given text. Uses on-device Kokoro voices when the model
|
|
@@ -3456,11 +3456,11 @@ Examples:
|
|
|
3456
3456
|
`,stderr:``,exitCode:0}}function $6(e){switch(e.state){case`ready`:return`voice engine: ready
|
|
3457
3457
|
`;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
|
|
3458
3458
|
`;case`idle`:return`voice engine: not downloaded (run say --warmup)
|
|
3459
|
-
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function e8(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function t8(e){return e instanceof Error?e.message:String(e)}let n8=!1,r8=null;function i8(){return n8?Promise.resolve(speechSynthesis.getVoices()):(r8||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){n8=!0,e(t);return}let n=()=>{n8=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),n8=!0,e(speechSynthesis.getVoices())},1e3)}),r8)}const a8={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function
|
|
3459
|
+
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function e8(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function t8(e){return e instanceof Error?e.message:String(e)}let n8=!1,r8=null;function i8(){return n8?Promise.resolve(speechSynthesis.getVoices()):(r8||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){n8=!0,e(t);return}let n=()=>{n8=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),n8=!0,e(speechSynthesis.getVoices())},1e3)}),r8)}const a8={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function lge(e,t,n){switch(t){case`-v`:return e.voiceName=n,null;case`-l`:return e.lang=n,null;case`-o`:case`--out`:return e.outFile=n,null;case`-r`:{let t=parseFloat(n);return Number.isNaN(t)||t<.1||t>10?`rate must be between 0.1 and 10`:(e.rate=t,null)}default:return`unknown option: ${t}`}}function uge(e){let t={voiceName:null,rate:1,lang:null,outFile:null,text:``},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i in a8){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return e8(`${i} requires ${a8[i]}`);let a=lge(t,i,n);if(a)return e8(a)}else if(i.startsWith(`-`)&&i!==`--list`)return e8(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function o8(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function dge(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speech-page-realm-stub-C7EPKrHd.js`),t=e().map(e=>o8({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await i8()).map(e=>o8({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
|
|
3460
3460
|
`)+`
|
|
3461
3461
|
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>o8(e)).join(`
|
|
3462
3462
|
`)+`
|
|
3463
|
-
`,stderr:``,exitCode:0}}catch(e){return e8(t8(e))}}async function
|
|
3463
|
+
`,stderr:``,exitCode:0}}catch(e){return e8(t8(e))}}async function fge(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speech-page-realm-stub-C7EPKrHd.js`),n=t().map(e=>({name:e.id})),r=(await i8()).map(e=>({name:e.name}));return[...n,...r]}async function pge(e,t){let n=(await fge(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:e8(`voice "${t}" not found. Use --list to see available voices.`)}}async function s8(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speech-page-realm-stub-C7EPKrHd.js`);return{stdout:$6(t?n():e()),stderr:``,exitCode:0}}return{stdout:$6(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return e8(t8(e))}}async function mge(e,t){return t.includes(`--list`)?dge(e):t.includes(`--status`)?s8(e,!1):t.includes(`--warmup`)?s8(e,!0):null}async function hge(e){try{let{speak:t}=await import(`./speech-page-realm-stub-C7EPKrHd.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return e8(`speech synthesis error: ${t8(e)}`)}}async function gge(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:3e5}),{stdout:``,stderr:``,exitCode:0}}catch(e){return e8(t8(e))}}async function _ge(e){let{synthesizeToWav:t}=await import(`./speech-page-realm-stub-C7EPKrHd.js`);try{return{bytes:await t(e)}}catch(e){return e8(t8(e))}}async function vge(e,t){try{let n=await e.panelRpc.call(`synthesize-to-wav`,{text:t.text,lang:t.lang,...t.voice?{voice:t.voice}:{},rate:t.rate},{timeoutMs:3e5});return{bytes:new Uint8Array(n.bytes)}}catch(e){return e8(t8(e))}}async function yge(e,t,n,r){let i=e.local?await _ge(r):await vge(e,r);if(`exitCode`in i)return i;let a=t.fs.resolvePath(t.cwd,n);try{await t.fs.writeFile(a,i.bytes)}catch(e){return e8(`failed to write ${n}: ${t8(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function bge(){return V(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return Q6();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:u()};if(!n.local&&!n.panelRpc)return e8(`Web Speech API unavailable in this environment`);let r=await mge(n,e);if(r)return r;let i=uge(e);if(`exitCode`in i)return i;if(!i.text)return Q6();if(!i.lang)return e8(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await pge(n,i.voiceName);if(t)return t;a=e}let o={text:i.text,lang:i.lang,voice:a,rate:i.rate};return i.outFile?yge(n,t,i.outFile,o):n.local?hge(o):gge(n,o)})}const xge=[`--clipboard`,`-c`,`--view`,`-v`];function c8(e){return{stdout:``,stderr:`screencapture: ${e}\n`,exitCode:1}}function Sge(e,t){return!e&&!t?c8(`browser APIs are unavailable in this environment`):e&&!Wo()&&!navigator.mediaDevices?.getDisplayMedia?c8(`screen capture is not supported in this browser`):null}async function Cge(e,t,n,r){try{if(Wo())return{bytes:(await qee({kind:`screen`,mimeType:n,quality:r})).bytes};if(e)return{bytes:(await Oge(n,r)).bytes};let i=await t.call(`screencapture`,{mimeType:n,quality:r},{timeoutMs:3e5});return{bytes:new Uint8Array(i.bytes)}}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{error:c8(`user cancelled or permission denied`)}:{error:c8(t)}}}async function wge(e,t,n,r){try{if(Wo()&&typeof document<`u`&&typeof document.hasFocus==`function`&&!document.hasFocus())return c8(`clipboard capture needs a focused window; save to a file instead`);if(n){let n=await Age(e,t),r=new ArrayBuffer(n.byteLength);new Uint8Array(r).set(n);let i=new Blob([r],{type:`image/png`});return await jge(),await navigator.clipboard.write([new ClipboardItem({"image/png":i})]),{stdout:`captured ${Math.round(i.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}return await r.call(`clipboard-write-image`,{bytes:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),mimeType:t},{timeoutMs:3e5}),{stdout:`captured ${Math.round(e.byteLength/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return c8(`failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}`)}}async function Tge(e,t,n,r,i){let a=i.fs.resolvePath(i.cwd,t);try{await i.fs.writeFile(a,e)}catch(e){return c8(`failed to write file: ${e instanceof Error?e.message:String(e)}`)}let o=Math.round(e.length/1024);return r?{stdout:`${a} (${o} KB)\n<img:data:${n};base64,${v(e)}>`,stderr:``,exitCode:0}:{stdout:`captured ${o} KB to ${Ba(a)}\n`,stderr:``,exitCode:0}}function Ege(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
|
|
3464
3464
|
|
|
3465
3465
|
Usage: screencapture [options] <output-file>
|
|
3466
3466
|
|
|
@@ -3476,7 +3476,7 @@ Examples:
|
|
|
3476
3476
|
screencapture screenshot.png # Capture to file
|
|
3477
3477
|
screencapture -c # Capture to clipboard
|
|
3478
3478
|
screencapture -v capture.png # Capture and return for agent vision
|
|
3479
|
-
`,stderr:``,exitCode:0}}function
|
|
3479
|
+
`,stderr:``,exitCode:0}}function Dge(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function Oge(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(r,0,0,i,a);let c=await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)});return{bytes:new Uint8Array(await c.arrayBuffer()),mimeType:e}}finally{n.getTracks().forEach(e=>{e.stop()})}}function kge(){return V(`screencapture`,async(e,t)=>{if(oi(e))return Ege();let n=H(e,{bool:xge});if(`error`in n)return c8(n.error);let r=d(),i=u(),a=Sge(r,i);if(a)return a;let o=n.bools.has(`--clipboard`)||n.bools.has(`-c`),s=n.bools.has(`--view`)||n.bools.has(`-v`),c=n.positionals[0];if(!o&&!c)return c8(`output file required (or use -c for clipboard)`);let l=c||`screenshot.png`,f=Dge(l),p=await Cge(r,i,f,f===`image/png`?1:.92);return`error`in p?p.error:o?wge(p.bytes,f,r,i):Tge(p.bytes,l,f,s,t)})}async function Age(e,t){if(t===`image/png`)return e;let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=new Blob([n],{type:t}),i=URL.createObjectURL(r);try{let e=new Image;await new Promise((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(Error(`Failed to load image for conversion`)),e.src=i});let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(`Failed to get canvas context`);n.drawImage(e,0,0);let r=await new Promise((e,n)=>{t.toBlob(t=>t?e(t):n(Error(`Failed to create PNG blob`)),`image/png`)});return new Uint8Array(await r.arrayBuffer())}finally{URL.revokeObjectURL(i)}}async function jge(e=3e5){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}function Mge(e){return new Promise((t,n)=>{chrome.runtime.sendMessage(e,e=>{let r=chrome.runtime.lastError;if(r){n(Error(r.message??`chrome.runtime.lastError`));return}t(e)})})}const l8=1e4;async function u8(e,t,n){let r={method:e,headers:Ee({"Content-Type":`application/json`}),signal:AbortSignal.timeout(l8)};n&&(r.body=JSON.stringify(n));try{let e=await fetch(Te(`/api/secrets${t}`),r),n=await e.json().catch(()=>({}));return{ok:e.ok,status:e.status,data:n}}catch(e){return{ok:!1,status:0,data:{error:Nge(e)}}}}function Nge(e){let t=e instanceof Error?e.name:``;return t===`TimeoutError`||t===`AbortError`?`no response from the secret store within ${l8/1e3}s`:`secret store unreachable: ${e instanceof Error?e.message:String(e)}`}function d8(e,t){return`could not read ${e} secrets — ${t??`the bridge gave no reason`}`}function f8(e,t){let n=e.entries.find(e=>e.name===t)??null;if(n)return n;if(e.warnings.length>0)throw Error(e.warnings.join(`; `));return null}function Pge(){return{async list(){let[e,t]=await Promise.all([u8(`GET`,``),u8(`GET`,`/session`)]),n=[],r=[];if(e.ok)for(let t of e.data)n.push({name:t.name,domains:t.domains,persisted:!0});else r.push(d8(`saved`,m8(e.data)));if(t.ok)for(let e of t.data)n.push({name:e.name,domains:e.domains,persisted:!1});else r.push(d8(`session`,m8(t.data)));return{entries:n,warnings:r}},async getInfo(e){return f8(await this.list(),e)},async getMasked(e){let{ok:t,data:n}=await u8(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await u8(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await u8(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(m8(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await u8(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(m8(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await u8(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(m8(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await u8(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(m8(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function p8(e){let t=t=>e(t);return{async list(){let[e,n]=await Promise.all([t({type:`secrets.list`}),t({type:`secrets.session.list`})]),r=[],i=[];for(let t of e?.entries??[])r.push({name:t.name,domains:t.domains,persisted:!0});for(let e of n?.entries??[])r.push({name:e.name,domains:e.domains,persisted:!1});return e?.entries||i.push(d8(`saved`,e?.error)),n?.entries||i.push(d8(`session`,n?.error)),{entries:r,warnings:i}},async getInfo(e){return f8(await this.list(),e)},async getMasked(e){return((await t({type:`secrets.list-masked-entries`}))?.entries??[]).find(t=>t.name===e)??null},async peek(e){let n=await t({type:`secrets.peek`,name:e});if(n?.error)throw Error(n.error);return n?.record??null},async setSession(e,n,r){let i=await t({type:`secrets.session.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.session.set failed`)},async setPersisted(e,n,r){let i=await t({type:`secrets.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.set failed`)},async setScope(e,n){let r=await t({type:`secrets.set-domains`,name:e,domains:n});if(!r?.ok)throw Error(r?.error??`secrets.set-domains failed`)},async delete(e){let n=await t({type:`secrets.delete`,name:e});if(!n?.ok)throw Error(n?.error??`secrets.delete failed`);return{removed:n.removed??!0,fromSession:n.fromSession}}}}function Fge(){return p8(e=>Mge(e))}function Ige(){return p8(e=>{let{type:t,...n}=e;return dn(t,n)})}function m8(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function Lge(e){switch(e){case`extension-direct`:return Fge();case`extension-delegate`:return Ige();default:return Pge()}}const h8=[`--domain`],Rge=[`--persist`];function zge(){return`secret — manage secrets for the fetch proxy and mount backends
|
|
3480
3480
|
|
|
3481
3481
|
No approval (session-only, in-memory, never persisted):
|
|
3482
3482
|
secret set <name> <value> --domain <pat> Set a session secret. Free for a
|
|
@@ -3513,23 +3513,23 @@ Examples:
|
|
|
3513
3513
|
secret peek OPENAI_KEY
|
|
3514
3514
|
secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
|
|
3515
3515
|
secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
|
|
3516
|
-
`}function g8(e){if(e===void 0||e.startsWith(`-`))return null;let t=e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return t.length===0?null:t}function _8(e){return{stdout:``,stderr:`secret: ${e}\n`,exitCode:1}}const
|
|
3516
|
+
`}function g8(e){if(e===void 0||e.startsWith(`-`))return null;let t=e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return t.length===0?null:t}function _8(e){return{stdout:``,stderr:`secret: ${e}\n`,exitCode:1}}const Bge={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},Vge=new Set;function v8(e,t){if(e===t)return!0;try{return pi(e).test(t)}catch{return!1}}function Hge(e,t){for(let n of e)if(v8(n,t))return!0;return!1}function y8(e){return{stdout:``,stderr:`${yi(`secret`,e)}\n`,exitCode:1}}function Uge(e){let t=rn(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??Lge(t),i=e.grants??Vge,a=e.broker,o=()=>(a??=tb(null),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(Hge(i,n))return`ok`;let r=await o().requestApproval({kind:`secret`,detail:`${Bge[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return r;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&v8(e,n)?e:n)}return`ok`},injectMaskedEnv:async t=>{if(e.setEnv&&tw(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}},clearMaskedEnv:t=>{e.unsetEnv&&tw(t)&&e.unsetEnv(t)}}}function Wge(e){let t=mo(e);if(t.length!==0)return t.endsWith(`\r
|
|
3517
3517
|
`)?t.slice(0,-2):t.endsWith(`
|
|
3518
|
-
`)?t.slice(0,-1):t}async function
|
|
3519
|
-
`,exitCode:1};let a=r.positionals[1],o=
|
|
3518
|
+
`)?t.slice(0,-1):t}async function Gge(e,t,n,r){let i=await r.gate(`persist`,e);return i===`ok`?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):y8(i)}async function Kge(e,t,n,r){if(await r.backend.getInfo(e)){let t=await r.gate(`value`,e);if(t!==`ok`)return y8(t)}return await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}" (domains: ${n.join(`, `)}) — in-memory only, not persisted.\n`,stderr:``,exitCode:0}}async function qge(e,t,n){let r=H(e.slice(1),{value:h8,bool:Rge});if(`error`in r)return _8(r.error);let i=r.positionals[0];if(!i||i.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
|
|
3519
|
+
`,exitCode:1};let a=r.positionals[1],o=Wge(t.stdin);if(a!==void 0&&o!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
|
|
3520
3520
|
`,exitCode:1};let s=a??o;if(s===void 0)return{stdout:``,stderr:`secret: set requires a <value>: secret set <name> <value> --domain <patterns> [--persist]
|
|
3521
3521
|
or pipe the value on stdin: echo "$TOKEN" | secret set <name> --domain <patterns>
|
|
3522
|
-
`,exitCode:1};let c=g8(r.values.get(`--domain`));return c?r.bools.has(`--persist`)?
|
|
3523
|
-
`,exitCode:1}}async function
|
|
3524
|
-
`,exitCode:1};let i=await t.backend.getMasked(r);return i?{stdout:`${i.name}=${i.maskedValue}\n domains: ${i.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function
|
|
3525
|
-
`,exitCode:1};let i=await t.backend.peek(r);return i?{stdout:`${i.name}: ${i.preview}\n domains: ${i.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function
|
|
3522
|
+
`,exitCode:1};let c=g8(r.values.get(`--domain`));return c?r.bools.has(`--persist`)?Gge(i,s,c,n):Kge(i,s,c,n):{stdout:``,stderr:`secret: set requires --domain <patterns>
|
|
3523
|
+
`,exitCode:1}}async function Jge(e,t){let n=H(e.slice(1),{});if(`error`in n)return _8(n.error);let r=n.positionals[0];if(!r)return{stdout:``,stderr:`secret: get requires a <name>
|
|
3524
|
+
`,exitCode:1};let i=await t.backend.getMasked(r);return i?{stdout:`${i.name}=${i.maskedValue}\n domains: ${i.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function Yge(e,t){let n=H(e.slice(1),{});if(`error`in n)return _8(n.error);let r=n.positionals[0];if(!r)return{stdout:``,stderr:`secret: peek requires a <name>
|
|
3525
|
+
`,exitCode:1};let i=await t.backend.peek(r);return i?{stdout:`${i.name}: ${i.preview}\n domains: ${i.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function Xge(e,t){let n=H(e.slice(1),{value:h8});if(`error`in n)return _8(n.error);let r=n.positionals[0];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
|
|
3526
3526
|
`,exitCode:1};let i=g8(n.values.get(`--domain`));if(!i)return{stdout:``,stderr:`secret: scope requires --domain <patterns>
|
|
3527
|
-
`,exitCode:1};let a=await t.gate(`scope`,r);return a===`ok`?(await t.backend.setScope(r,i),{stdout:`Updated scope for "${r}" (domains: ${i.join(`, `)})\n`,stderr:``,exitCode:0}):y8(a)}async function
|
|
3528
|
-
`,stderr:a,exitCode:o};let s=Math.max(4,...r.map(e=>e.name.length)),c=`${`NAME`.padEnd(s)} TYPE DOMAINS\n`;for(let e of r){let t=e.persisted?`SAVED`:`SESSION`;c+=`${e.name.padEnd(s)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:c,stderr:a,exitCode:o}}async function
|
|
3529
|
-
`,exitCode:1};let a;try{a=new URL(i).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${i}"\n`,exitCode:1}}let{entries:o,warnings:s}=await t.backend.list(),c=o.find(e=>e.name===r);return c?Is(c.domains,a)?{stdout:`✓ ${r} is allowed for ${a}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${r} is NOT allowed for ${a}\n Allowed domains: ${c.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:s.length>0?s.map(e=>`secret: ${e}\n`).join(``):`secret: no secret named "${r}"\n`,exitCode:1}}async function
|
|
3527
|
+
`,exitCode:1};let a=await t.gate(`scope`,r);return a===`ok`?(await t.backend.setScope(r,i),{stdout:`Updated scope for "${r}" (domains: ${i.join(`, `)})\n`,stderr:``,exitCode:0}):y8(a)}async function Zge(e,t){let n=H(e.slice(1),{});if(`error`in n)return _8(n.error);let{entries:r,warnings:i}=await t.backend.list(),a=i.map(e=>`secret: ${e}\n`).join(``),o=+(i.length>0);if(r.length===0)return{stdout:i.length>0?``:`No secrets stored
|
|
3528
|
+
`,stderr:a,exitCode:o};let s=Math.max(4,...r.map(e=>e.name.length)),c=`${`NAME`.padEnd(s)} TYPE DOMAINS\n`;for(let e of r){let t=e.persisted?`SAVED`:`SESSION`;c+=`${e.name.padEnd(s)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:c,stderr:a,exitCode:o}}async function Qge(e,t,n){let r=H(e.slice(1),{});if(`error`in r)return _8(r.error);let i=r.positionals[0];if(!i)return{stdout:``,stderr:`secret: ${t} requires a <name>\n`,exitCode:1};let a=await n.backend.delete(i);return a.removed?(n.clearMaskedEnv(i),{stdout:`Removed ${a.fromSession===!0?`session`:`persisted`} secret "${i}"\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`secret: no secret named "${i}"\n`,exitCode:1}}async function $ge(e,t){let n=H(e.slice(1),{});if(`error`in n)return _8(n.error);let r=n.positionals[0],i=n.positionals[1];if(!r||!i)return{stdout:``,stderr:`secret: test requires <name> <url>
|
|
3529
|
+
`,exitCode:1};let a;try{a=new URL(i).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${i}"\n`,exitCode:1}}let{entries:o,warnings:s}=await t.backend.list(),c=o.find(e=>e.name===r);return c?Is(c.domains,a)?{stdout:`✓ ${r} is allowed for ${a}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${r} is NOT allowed for ${a}\n Allowed domains: ${c.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:s.length>0?s.map(e=>`secret: ${e}\n`).join(``):`secret: no secret named "${r}"\n`,exitCode:1}}async function e_e(e,t){let n=H(e.slice(1),{});if(`error`in n)return _8(n.error);if(!t.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
|
|
3530
3530
|
(changes are picked up on the next request — no restart needed)
|
|
3531
3531
|
`,stderr:``,exitCode:0};try{return await chrome.runtime.openOptionsPage(),{stdout:`Opened Mount Secrets options page in a new tab.
|
|
3532
|
-
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function
|
|
3532
|
+
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function t_e(e,t,n){let r=e[0];switch(r){case`set`:return qge(e,t,n);case`get`:case`read`:return Jge(e,n);case`peek`:return Yge(e,n);case`scope`:return Xge(e,n);case`list`:return Zge(e,n);case`delete`:case`rm`:return Qge(e,r,n);case`test`:return $ge(e,n);case`edit`:return e_e(e,n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function n_e(e={}){let t=Uge(e);return V(`secret`,async(e,n)=>{if(e.length===0||oi(e,{valueFlags:h8}))return{stdout:zge(),stderr:``,exitCode:0};try{return await t_e(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function r_e(){return null}function b8(){return null}function x8(){return{stdout:`usage: serve [--entry <relative-path>] [--ttl <duration>] [--bridge | --no-bridge] [--max-tabs <n>] [--quiet] [--stop <token>] [--list] <directory>
|
|
3533
3533
|
serve --logs [<token>] [--lines <n>]
|
|
3534
3534
|
serve --truncate [<token>]
|
|
3535
3535
|
|
|
@@ -3551,28 +3551,28 @@ Examples:
|
|
|
3551
3551
|
--truncate [t] Clear lifecycle records and re-arm the announcement latch.
|
|
3552
3552
|
--project Obsolete; ignored. Root-absolute paths work natively
|
|
3553
3553
|
under unified preview.
|
|
3554
|
-
`,stderr:``,exitCode:0}}function
|
|
3555
|
-
`}:(n.lines=i,{skip:+(e===`--lines`)})}}function
|
|
3554
|
+
`,stderr:``,exitCode:0}}function i_e(e){return`error`in e}function a_e(e,t,n){if(e===`--list`)return n.list=!0,{skip:0};if(e===`--logs`||e===`--truncate`){let r=e===`--logs`?`logs`:`truncate`;return t&&!t.startsWith(`-`)?(n[r]=t,{skip:1}):(n[r]=!0,{skip:0})}if(e.startsWith(`--logs=`)||e.startsWith(`--truncate=`)){let t=e.startsWith(`--logs=`)?`logs`:`truncate`,r=e.slice(e.indexOf(`=`)+1);return r?(n[t]=r,{skip:0}):{error:`serve: missing value for --${t}\n`}}if(e===`--lines`||e.startsWith(`--lines=`)){let r=e===`--lines`?t:e.slice(8),i=r===void 0?NaN:Number(r);return!Number.isSafeInteger(i)||i<=0?{error:`serve: --lines must be a positive integer
|
|
3555
|
+
`}:(n.lines=i,{skip:+(e===`--lines`)})}}function o_e(e,t,n){if(e!==`--ttl`&&!e.startsWith(`--ttl=`))return;let r=e===`--ttl`?t:e.slice(6);if(!r)return{error:`serve: missing value for --ttl
|
|
3556
3556
|
`};let i=/^([1-9][0-9]*)([mhdw])$/.exec(r);if(!i)return{error:`serve: --ttl must be a positive whole duration (m, h, d, or w)
|
|
3557
3557
|
`};let a=Number(i[1])*{m:6e4,h:36e5,d:864e5,w:6048e5}[i[2]];return Number.isSafeInteger(a)?a>2592e6?{error:`serve: --ttl cannot exceed 30d; longer retention requires a Sliccy Deluxe De-Enshittification plan.
|
|
3558
3558
|
`}:(n.ttlMs=a,{skip:+(e===`--ttl`)}):{error:`serve: --ttl must be a positive whole duration (m, h, d, or w)
|
|
3559
|
-
`}}function
|
|
3559
|
+
`}}function s_e(e,t){let n={"--bridge":`bridge`,"--no-bridge":`noBridge`,"--project":`project`,"--quiet":`quiet`}[e];if(n)return t[n]=!0,{skip:0}}function c_e(e,t,n){let r=o_e(e,t,n);if(r)return r;let i=s_e(e,n);if(i)return i;if(e===`--entry`)return t?(n.entry=t,{skip:1}):{error:`serve: missing value for --entry
|
|
3560
3560
|
`};if(e.startsWith(`--entry=`))return n.entry=e.slice(8),{skip:0};if(e===`--stop`)return t?(n.stop=t,{skip:1}):{error:`serve: missing value for --stop
|
|
3561
|
-
`};if(e.startsWith(`--stop=`))return n.stop=e.slice(7),{skip:0};let a=
|
|
3561
|
+
`};if(e.startsWith(`--stop=`))return n.stop=e.slice(7),{skip:0};let a=a_e(e,t,n);if(a)return a;if(e===`--max-tabs`){if(!t)return{error:`serve: missing value for --max-tabs
|
|
3562
3562
|
`};let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?{error:`serve: --max-tabs must be a positive integer
|
|
3563
3563
|
`}:(n.maxTabs=e,{skip:1})}if(e.startsWith(`--max-tabs=`)){let t=Number.parseInt(e.slice(11),10);return!Number.isFinite(t)||t<=0?{error:`serve: --max-tabs must be a positive integer
|
|
3564
3564
|
`}:(n.maxTabs=t,{skip:0})}return e.startsWith(`-`)?{error:`serve: unknown option: ${e}\n`}:n.directory?{error:`serve: expected a single directory argument
|
|
3565
|
-
`}:(n.directory=e,{skip:0})}function
|
|
3566
|
-
`,exitCode:1};if(t.webhookId){let n=await f1();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function
|
|
3565
|
+
`}:(n.directory=e,{skip:0})}function l_e(e){let t={entry:`index.html`,bridge:!1,noBridge:!1,project:!1,list:!1,quiet:!1};for(let n=0;n<e.length;n+=1){let r=c_e(e[n],e[n+1],t);if(i_e(r))return{...t,error:r.error};n+=r.skip}return t}async function u_e(e,t,n,r){if(!Ua(t))return{stdout:``,stderr:`serve: invalid entry file: ${t}\n`,exitCode:1};let i=n.resolvePath(r,e),a;try{a=await n.stat(i)}catch{return{stdout:``,stderr:`serve: no such directory: ${e}\n`,exitCode:1}}if(!a.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${e}\n`,exitCode:1};let o=Za(i,t),s;try{s=await n.stat(o)}catch{return{stdout:``,stderr:`serve: entry file not found: ${o}\n`,exitCode:1}}return s.isFile?{fullDirectory:i,entryPath:o}:{stdout:``,stderr:`serve: entry is not a file: ${o}\n`,exitCode:1}}function d_e(e){return`exitCode`in e}async function f_e(e){let t,n=b8();if(n)t=await n({type:`stop`,previewToken:e});else{let n=u();if(!n)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=await n.call(`tray-revoke-preview`,{previewToken:e})}if(!t.revoked)return{stdout:``,stderr:`serve: preview token not found or already revoked
|
|
3566
|
+
`,exitCode:1};if(t.webhookId){let n=await f1();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function p_e(){let e=b8();if(e){let t=(await e({type:`list`})).previews??[];return t.length===0?{stdout:`No active previews
|
|
3567
3567
|
`,stderr:``,exitCode:0}:{stdout:S8(t),stderr:``,exitCode:0}}let t=u();if(!t)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};let n=(await t.call(`tray-list-previews`,void 0)).previews??[];return n.length===0?{stdout:`No active previews
|
|
3568
|
-
`,stderr:``,exitCode:0}:{stdout:S8(n),stderr:``,exitCode:0}}function S8(e){return`Active previews:\n TOKEN MODE EXPIRES URL ROOT CREATED\n${e.map(e=>` ${e.previewToken} ${e.mode??`live`} ${e.expiresAt??`-`} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`}function
|
|
3569
|
-
`,stderr:``,exitCode:0}:{stdout:`Preview lifecycle records (oldest to newest):\n${t.map(
|
|
3568
|
+
`,stderr:``,exitCode:0}:{stdout:S8(n),stderr:``,exitCode:0}}function S8(e){return`Active previews:\n TOKEN MODE EXPIRES URL ROOT CREATED\n${e.map(e=>` ${e.previewToken} ${e.mode??`live`} ${e.expiresAt??`-`} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`}function m_e(e){let t=e.announced?`announced`:`suppressed`,n=e.previewToken??`-`,r=e.lifecycle===`connected`?`origin=${e.origin??`-`} userAgent=${e.userAgent??`-`}`:`reason=${e.reason??`-`}`;return`${e.timestamp} ${e.lifecycle.padEnd(12)} ${t.padEnd(10)} preview=${n} conn=${e.connId} ${r}\n`}async function h_e(e){let t,n=b8();if(n)t=(await n({type:`logs`,previewToken:e.previewToken})).lifecycleRecords??[];else{let n=u();if(!n)return{stdout:``,stderr:"serve --logs: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=(await n.call(`tray-preview-logs`,{previewToken:e.previewToken})).lifecycleRecords}return e.lines!==void 0&&(t=t.slice(-e.lines)),t.length===0?{stdout:`No preview lifecycle records. The recorder is leader-memory-only and resets on leader restart.
|
|
3569
|
+
`,stderr:``,exitCode:0}:{stdout:`Preview lifecycle records (oldest to newest):\n${t.map(m_e).join(``)}`,stderr:``,exitCode:0}}async function g_e(e){let t,n,r=b8();if(r){let i=await r({type:`truncate`,previewToken:e});t=i.cleared??0,n=i.rearmed??0}else{let r=u();if(!r)return{stdout:``,stderr:"serve --truncate: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};let i=await r.call(`tray-preview-truncate`,{previewToken:e});t=i.cleared,n=i.rearmed}return{stdout:`Cleared ${t} preview lifecycle record${t===1?``:`s`}; re-armed ${n} preview announcement${n===1?``:`s`}.\n`,stderr:``,exitCode:0}}async function __e(e,t){let n=[],r=0;for await(let i of e.walk(t)){if(n.length>=1e3)throw Error(`persistent preview exceeds 1000 file limit`);let a=await e.readFile(i,{encoding:`binary`}),o=typeof a==`string`?new TextEncoder().encode(a):a,s=i.slice(t===`/`?1:t.length+1);if(o.byteLength>26214400)throw Error(`preview file exceeds 25 MiB limit: ${s}`);if(r+=o.byteLength,r>52428800)throw Error(`persistent preview exceeds 50 MiB total limit`);n.push({path:s,content:o,mime:Na(s)})}return n}function C8(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function v_e(e){let t=r_e();if(t)return t(e);let n=u();if(!n)throw Error("no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.");return e.ttlMs===void 0?n.call(`tray-open-preview`,e):n.call(`tray-open-preview`,e,{timeoutMs:6e5})}async function y_e(e,t){if(t)return t.createPage(e);typeof window<`u`&&typeof window.open==`function`&&window.open(e,`_blank`,`noopener,noreferrer`)}async function b_e(e,t){if(!e)return{ok:!0};let n=await f1();if(!n)return{ok:!1,result:{stdout:``,stderr:`${t}serve: --bridge requires an active lick manager\n`,exitCode:1}};try{return{ok:!0,webhookId:(await n.createWebhook(`preview-bridge`)).id}}catch(e){return{ok:!1,result:{stdout:``,stderr:`${t}serve: webhook creation failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}}async function x_e(e,t,n,r,i,a,o){let s;try{s=await v_e({entryPath:n,servedRoot:t,bridge:e.bridge,noBridge:e.ttlMs!==void 0||e.noBridge,maxTabs:e.maxTabs,quiet:e.quiet,webhookId:r,ttlMs:e.ttlMs,snapshotFiles:a})}catch(e){if(r){let e=await f1();e&&await e.deleteWebhook(r).catch(()=>{})}return{stdout:``,stderr:`${i}serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let c=await y_e(s.url,o),l=`${s.pushed} follower${s.pushed===1?``:`s`}`,u=c?` (targetId: ${c})`:``;return{stdout:`Preview URL: ${s.url}${u}\nPushed to ${l}\n`,stderr:i,exitCode:0}}async function S_e(e){if(e.stop){let t=e.stop;return C8(()=>f_e(t))}if(e.list)return C8(()=>p_e());if(e.logs&&e.truncate)return{stdout:``,stderr:`serve: --logs and --truncate are mutually exclusive
|
|
3570
3570
|
`,exitCode:1};if(e.lines!==void 0&&!e.logs)return{stdout:``,stderr:`serve: --lines requires --logs
|
|
3571
|
-
`,exitCode:1};if(e.logs){let t=typeof e.logs==`string`?e.logs:void 0;return C8(()=>
|
|
3571
|
+
`,exitCode:1};if(e.logs){let t=typeof e.logs==`string`?e.logs:void 0;return C8(()=>h_e({previewToken:t,lines:e.lines}))}if(e.truncate){let t=typeof e.truncate==`string`?e.truncate:void 0;return C8(()=>g_e(t))}}function C_e(e){if(e.ttlMs!==void 0&&e.bridge)return{stdout:``,stderr:`serve: --ttl cannot be combined with --bridge
|
|
3572
3572
|
`,exitCode:1};if(e.ttlMs!==void 0&&e.maxTabs!==void 0)return{stdout:``,stderr:`serve: --ttl cannot be combined with --max-tabs
|
|
3573
|
-
`,exitCode:1}}async function
|
|
3574
|
-
`:``,f=await
|
|
3575
|
-
`;function
|
|
3573
|
+
`,exitCode:1}}async function w_e(e,t,n){if(e.ttlMs!==void 0){if(!t)throw Error(`persistent snapshot filesystem unavailable`);return __e(t,n)}}async function T_e(e,t,n,r){if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return x8();let i=l_e(e);if(i.error)return{stdout:``,stderr:i.error,exitCode:1};let a=await S_e(i);if(a)return a;if(!i.directory)return x8();let o=C_e(i);if(o)return o;let s=await u_e(i.directory,i.entry,t.fs,t.cwd);if(d_e(s))return s;let{fullDirectory:c,entryPath:l}=s,u;try{u=await w_e(i,r,c)}catch(e){return{stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let d=i.project?`serve: --project is obsolete; ignored (root-absolute paths work natively under unified preview)
|
|
3574
|
+
`:``,f=await b_e(!i.noBridge&&i.bridge,d);return f.ok?x_e(i,c,l,f.webhookId,d,u,n):f.result}function E_e(e,t){return V(`serve`,(n,r)=>T_e(n,r,e,t))}const w8=`usage: session export [--id <id>] [--output <path>]
|
|
3575
|
+
`;function D_e(e){if(e.includes(`\0`))return{ok:!1,reason:`path must not contain NUL bytes`};if(e.includes(`\\`))return{ok:!1,reason:`path must not contain backslashes`};let t=e.split(`/`);for(let e of t)if(e===`..`)return{ok:!1,reason:`path must not contain ".."/traversal segments`};return{ok:!0}}function O_e(e){let t=null,n=null,r=e.slice(1);for(let e=0;e<r.length;e++){let i=r[e];if(i===`--id`){if(t!==null)return{ok:!1,stderr:`session export: duplicate flag --id\n${w8}`};let n=r[e+1];if(!n||n.startsWith(`-`))return{ok:!1,stderr:`session export: --id requires a value\n${w8}`};t=n,e++}else if(i===`--output`){if(n!==null)return{ok:!1,stderr:`session export: duplicate flag --output\n${w8}`};let t=r[e+1];if(!t||t.startsWith(`-`))return{ok:!1,stderr:`session export: --output requires a path\n${w8}`};n=t,e++}else if(i.startsWith(`-`))return{ok:!1,stderr:`session export: unknown flag ${i}\n${w8}`};else return{ok:!1,stderr:`session export: unexpected argument ${JSON.stringify(i)}\n${w8}`}}return{ok:!0,args:{sessionId:t,outputPath:n}}}async function k_e(e){let t=[],n=0;for await(let r of e.chunks)t.push(r),n+=r.byteLength;let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.byteLength;let a=await e.completion;if(a.byteLength!==n||gx(r)!==a.sha256)throw new Vs(`transfer-corrupt`);return r}async function A_e(e,t){let n=O_e(e);if(!n.ok)return{stdout:``,stderr:n.stderr,exitCode:1};let{sessionId:r,outputPath:i}=n.args;if(i!==null){let e=D_e(i);if(!e.ok)return{stdout:``,stderr:`session export: --output ${e.reason}\n${w8}`,exitCode:1}}let a=r==null?{kind:`active`}:{kind:`frozen`,sessionId:r};try{let e=await mb().export(a,{}),n=await k_e(e),r=i??`/workspace/${e.filename}`;return await t.fs.writeFile(r,n),{stdout:`exported ${r}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`session export: ${e instanceof Vs?e.code:e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function j_e(){return V(`session`,async(e,t)=>{if(e[0]===`export`&&!oi(e))return A_e(e,t);let{dispatchSessionMemoryAware:n}=await import(`./session-command-memory-CkF1Wu0O.js`);return n(e,t,w8)})}function M_e(){return V(`slicc`,async(e,t)=>{let{runSlicc:n}=await import(`./run-B5YOTTPD.js`);return await n(e,t)})}const T8=`leader`;function N_e(){try{let e=globalThis.localStorage?.getItem(`slicc.leaderSprinkleInstances`);if(e)return JSON.parse(e)}catch{}return[]}function P_e(e){return+!!e.leader+e.followers.length}function E8(){return{stdout:`usage: sprinkle <subcommand> [args]
|
|
3576
3576
|
|
|
3577
3577
|
list [--runtime <id>] List sprinkles + an instance line per runtime
|
|
3578
3578
|
open <name> Open a sprinkle by name
|
|
@@ -3590,22 +3590,22 @@ Examples:
|
|
|
3590
3590
|
chat <html> Show inline HTML in chat (Tool UI)
|
|
3591
3591
|
Use data-action="name" on buttons for callbacks
|
|
3592
3592
|
Pipe HTML: echo "<div>...</div>" | sprinkle chat
|
|
3593
|
-
`,stderr:``,exitCode:0}}function
|
|
3593
|
+
`,stderr:``,exitCode:0}}function F_e(){return globalThis.__slicc_sprinkleManager??null}function D8(e,t){return{stdout:``,stderr:`sprinkle ${e}: ${t}\n`,exitCode:1}}function O8(){return[T8,...BQ().map(e=>e.runtimeId)]}function k8(e){return`unknown runtime "${e}"\nknown runtimes: ${O8().join(`, `)}\nRun \`host\` to see connected followers.`}async function I_e(e,t){let n=e.slice(1).join(` `);if(!n){let e=mo(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
|
|
3594
3594
|
`,exitCode:1};let r=await Xt({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
|
|
3595
3595
|
`,exitCode:1}:{stdout:JSON.stringify(r)+`
|
|
3596
|
-
`,stderr:``,exitCode:0}}function
|
|
3597
|
-
`,stderr:``,exitCode:0};let a=new Set(e.opened()),o=
|
|
3596
|
+
`,stderr:``,exitCode:0}}function L_e(e){return e.map(e=>{let t=e.runtime?` (${e.runtime})`:``;return` instance: ${e.runtimeId}${t}`})}function R_e(e){return[...e.map(e=>({name:e,runtimeId:T8})),...N_e()]}async function z_e(e,t){let n=H(t.slice(1),{value:[`--runtime`]});if(`error`in n)return D8(`list`,n.error);let r=n.values.get(`--runtime`);if(r!==void 0&&!O8().includes(r))return D8(`list`,k8(r));await e.refresh();let i=e.available();if(i.length===0)return{stdout:`No .shtml sprinkles found.
|
|
3597
|
+
`,stderr:``,exitCode:0};let a=new Set(e.opened()),o=R_e([...a]).filter(e=>r===void 0||e.runtimeId===r),s=[];for(let e of i){let t=o.filter(t=>t.name===e.name);if(r!==void 0&&t.length===0)continue;let n=a.has(e.name)?` [open]`:``;s.push(` ${e.name}${n} ${e.title} (${e.path})`),s.push(...L_e(t))}return s.length===0?{stdout:`No sprinkles are open on runtime "${r}".\n`,stderr:``,exitCode:0}:{stdout:s.join(`
|
|
3598
3598
|
`)+`
|
|
3599
|
-
`,stderr:``,exitCode:0}}function
|
|
3599
|
+
`,stderr:``,exitCode:0}}function B_e(e,t){return!t||yv(e)?null:(bv(e,t),yv(e)===t?t:null)}async function V_e(e,t,n){let r=H(t.slice(1),{});if(`error`in r)return D8(`open`,r.error);let i=r.positionals[0];if(!i)return D8(`open`,`name required`);let a=Ho(void 0,n),o=B_e(i,a);try{a?await e.open(i,void 0,{lickOriginTarget:a}):await e.open(i)}catch(e){return o&&xv(i),D8(`open`,e instanceof Error?e.message:String(e))}return{stdout:`Sprinkle "${i}" opened${o?`; licks route to "${o}"`:``}.\n`,stderr:``,exitCode:0}}function H_e(e,t){let n=H(t.slice(1),{});if(`error`in n)return D8(`close`,n.error);let r=n.positionals[0];return r?(e.close(r),{stdout:`Sprinkle "${r}" closed.\n`,stderr:``,exitCode:0}):D8(`close`,`name required`)}async function U_e(e,t){let n=H(t.slice(1),{});if(`error`in n)return D8(`reload`,n.error);let r=n.positionals[0];if(!r)return D8(`reload`,`name required`);try{return await e.reload(r),{stdout:`Sprinkle "${r}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return D8(`reload`,e instanceof Error?e.message:String(e))}}async function W_e(e,t){let n=H(t.slice(1),{});if(`error`in n)return D8(`refresh`,n.error);await e.refresh();let r=e.available().length;return{stdout:`Found ${r} sprinkle${r===1?``:`s`}.\n`,stderr:``,exitCode:0}}function G_e(e){let t=H(e.slice(1),{value:[`--scoop`],bool:[`--clear`]});if(`error`in t)return D8(`route`,t.error);let n=t.positionals[0];if(!n){let e=Sv(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
|
|
3600
3600
|
`,stderr:``,exitCode:0}:{stdout:`Sprinkle routes (applied to every runtime — the leader resolves the
|
|
3601
3601
|
route for follower-forwarded licks too):
|
|
3602
3602
|
`+t.map(([e,t])=>` ${e} -> ${t}`).join(`
|
|
3603
3603
|
`)+`
|
|
3604
|
-
`,stderr:``,exitCode:0}}if(t.bools.has(`--clear`))return xv(n),{stdout:`Route cleared for sprinkle "${n}" (licks will go to cone).\n`,stderr:``,exitCode:0};let r=t.values.get(`--scoop`);if(!r){let e=yv(n);return e?{stdout:`${n} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${n} -> cone (default)\n`,stderr:``,exitCode:0}}return bv(n,r),{stdout:`Sprinkle "${n}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function
|
|
3605
|
-
`,exitCode:1};switch(n){case`list`:return
|
|
3606
|
-
`,stderr:``,exitCode:0}}function
|
|
3607
|
-
`)}\n`:``}async function
|
|
3608
|
-
`)?e:`${e}\n`,exitCode:1}}function
|
|
3604
|
+
`,stderr:``,exitCode:0}}if(t.bools.has(`--clear`))return xv(n),{stdout:`Route cleared for sprinkle "${n}" (licks will go to cone).\n`,stderr:``,exitCode:0};let r=t.values.get(`--scoop`);if(!r){let e=yv(n);return e?{stdout:`${n} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${n} -> cone (default)\n`,stderr:``,exitCode:0}}return bv(n,r),{stdout:`Sprinkle "${n}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function K_e(e){let t=[];return e.leader&&t.push(T8),t.push(...e.followers),t.join(`, `)}async function q_e(e,t){let n=H(t.slice(1),{value:[`--runtime`]});if(`error`in n)return D8(`send`,n.error);let r=n.positionals[0];if(!r)return D8(`send`,`name required`);let i=n.positionals.slice(1).join(` `);if(!i)return D8(`send`,`JSON data required`);let a;try{a=JSON.parse(i)}catch{return D8(`send`,`invalid JSON`)}let o=n.values.get(`--runtime`);if(o!==void 0&&!O8().includes(o))return D8(`send`,k8(o));let s=await e.sendToSprinkle(r,a,o?{runtime:o}:void 0);if(!s)return D8(`send`,`sprinkle manager returned no delivery report — push not confirmed`);if(s.unknownRuntime)return D8(`send`,k8(s.unknownRuntime));let c=P_e(s);return c===0?D8(`send`,o?`"${r}" is not open on runtime "${o}" — nothing was delivered`:`"${r}" is not open on the leader or any connected follower — nothing was delivered`):{stdout:`Data sent to sprinkle "${r}" — ${c} instance${c===1?``:`s`} (${K_e(s)}).\n`,stderr:``,exitCode:0}}function J_e(){return V(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return E8();let n=e[0];if(oi(e.slice(1),{valueFlags:[`--scoop`,`--runtime`]}))return{stdout:ai(`sprinkle`,n,E8().stdout),stderr:``,exitCode:0};if(n===`chat`)return I_e(ii(e),t);let r=F_e();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
|
|
3605
|
+
`,exitCode:1};switch(n){case`list`:return z_e(r,e);case`open`:return V_e(r,e,t.env);case`close`:return H_e(r,e);case`reload`:return U_e(r,e);case`refresh`:return W_e(r,e);case`route`:return G_e(e);case`send`:return q_e(r,e);default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function Y_e(){return{stdout:`usage: sqlite3 [database] [sql]
|
|
3606
|
+
`,stderr:``,exitCode:0}}function X_e(e,t){let n=e.length>0&&!e[0].startsWith(`-`);return{database:n?e[0]:`:memory:`,sql:(n?e.slice(1):e).join(` `).trim()||mo(t.stdin).trim()}}function Z_e(e,t){return e===`:memory:`?e:t.fs.resolvePath(t.cwd,e)}async function Q_e(e,t,n){return t===`:memory:`||!await n.fs.exists(t)?new e.Database:new e.Database(await n.fs.readFileBuffer(t))}async function $_e(e,t,n){t!==`:memory:`&&await n.fs.writeFile(t,e.export())}function eve(e){let t=e.flatMap(e=>e.values.map(e=>e.map(Ha).join(`|`)));return t.length>0?`${t.join(`
|
|
3607
|
+
`)}\n`:``}async function tve(e,t,n){let r=await Xa(),i=Z_e(e,n),a=await Q_e(r,i,n),o=a.exec(t);return await $_e(a,i,n),a.close(),eve(o)}function A8(e,t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}function j8(e=`sqlite3`){return V(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return Y_e();let{database:r,sql:i}=X_e(t,n);if(!i)return A8(e,`interactive mode is not supported; provide SQL as argument or stdin`);try{return{stdout:await tve(r,i,n),stderr:``,exitCode:0}}catch(t){return A8(e,t)}})}function M8(e){return{stdout:``,stderr:e.endsWith(`
|
|
3608
|
+
`)?e:`${e}\n`,exitCode:1}}function nve(){return{stdout:`ssh - run a command on a connected tray follower
|
|
3609
3609
|
|
|
3610
3610
|
Usage: ssh [--cwd <dir>] [--timeout <seconds>] <runtime-id> <command...>
|
|
3611
3611
|
ssh --list
|
|
@@ -3628,11 +3628,11 @@ Examples:
|
|
|
3628
3628
|
ssh --list
|
|
3629
3629
|
ssh follower-abc123 "uname -a"
|
|
3630
3630
|
ssh --cwd /tmp follower-abc123 "ls -la"
|
|
3631
|
-
`,stderr:``,exitCode:0}}function
|
|
3631
|
+
`,stderr:``,exitCode:0}}function rve(e){let t=e.filter(e=>e.exec);if(t.length===0)return`No exec-capable followers connected.
|
|
3632
3632
|
Start one with: slicc <join-url> follow sh -c
|
|
3633
3633
|
`;let n=[`exec targets:`];for(let e of t){let t=[e.runtimeId];e.runtime&&t.push(`(${e.runtime})`),n.push(` - ${t.join(` `)}`),e.motd&&n.push(` ${e.motd}`)}return`${n.join(`
|
|
3634
|
-
`)}\n`}function
|
|
3635
|
-
Usage: ssh <runtime-id> <command...>`);let r=u();if(!r)return M8(`ssh: not available in this environment (needs the standalone app)`);let i=`ssh-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,a=()=>{r.call(`tray-exec-signal`,{execToken:i}).catch(()=>{})};t.signal?.addEventListener(`abort`,a,{once:!0});try{let e=n.timeoutSec?n.timeoutSec*1e3:void 0,a=await r.call(`tray-exec`,{runtimeId:n.runtimeId,command:n.command,cwd:n.cwd,execToken:i,timeoutMs:e,stdin:
|
|
3634
|
+
`)}\n`}function ive(e){if(e.stdin===void 0)return;let t=po(e.stdin);if(t.length===0)return;let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return v(n)}function ave(e){let t=!1,n,r,i=0;for(;i<e.length;){let a=e[i];if(a===`--help`||a===`-h`)return{help:!0};if(a===`--list`||a===`-l`){t=!0,i+=1;continue}if(a===`--cwd`){let t=e[i+1];if(t===void 0)return{error:`ssh: --cwd requires a directory argument`};n=t,i+=2;continue}if(a===`--timeout`){let t=e[i+1],n=Number(t);if(t===void 0||!Number.isFinite(n)||n<=0)return{error:`ssh: --timeout requires a positive number of seconds`};r=n,i+=2;continue}if(a.startsWith(`-`)&&a!==`-`)return{error:`ssh: unknown flag: ${a}`};break}let a=e[i],o=e.slice(i+1).join(` `);return{list:t,cwd:n,timeoutSec:r,runtimeId:a,command:o}}function ove(){return V(`ssh`,async(e,t)=>{let n=ave(e);if(`help`in n)return nve();if(`error`in n)return M8(n.error);if(n.list||n.runtimeId===void 0)return{stdout:rve(BQ()),stderr:``,exitCode:0};if(!n.command)return M8(`ssh: missing command
|
|
3635
|
+
Usage: ssh <runtime-id> <command...>`);let r=u();if(!r)return M8(`ssh: not available in this environment (needs the standalone app)`);let i=`ssh-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,a=()=>{r.call(`tray-exec-signal`,{execToken:i}).catch(()=>{})};t.signal?.addEventListener(`abort`,a,{once:!0});try{let e=n.timeoutSec?n.timeoutSec*1e3:void 0,a=await r.call(`tray-exec`,{runtimeId:n.runtimeId,command:n.command,cwd:n.cwd,execToken:i,timeoutMs:e,stdin:ive(t)},{timeoutMs:(e??864e5)+5e3});return a.error?{stdout:a.stdout,stderr:`${a.stderr}ssh: ${a.error}\n`,exitCode:a.exitCode||1}:{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}catch(e){return M8(`ssh: ${e instanceof Error?e.message:String(e)}`)}finally{t.signal?.removeEventListener(`abort`,a)}})}function sve(e){return{stdout:``,stderr:`${yi(`sudo`,e)}\n`,exitCode:1}}function cve(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return V(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
|
|
3636
3636
|
`,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
|
|
3637
3637
|
|
|
3638
3638
|
Request human approval to run <command> with elevation. If approved, the
|
|
@@ -3646,14 +3646,14 @@ Options:
|
|
|
3646
3646
|
-h, --help Show this help message and exit.
|
|
3647
3647
|
`,stderr:``,exitCode:0};if(!t)return{stdout:``,stderr:`sudo: command-level approval is not configured
|
|
3648
3648
|
`,exitCode:1};if(!i.exec)return{stdout:``,stderr:`sudo: cannot dispatch inner command in this context
|
|
3649
|
-
`,exitCode:1};let a=YJ(e[0],e.slice(1)),o=await t.requestApproval({kind:`command`,detail:a});if(o.decision===`deny`)return
|
|
3650
|
-
`,exitCode:1};let i=await Promise.all(r.map(e=>
|
|
3651
|
-
`,exitCode:1};let r=await Promise.all(n.paths.map(e=>
|
|
3652
|
-
`,exitCode:1};let a=await Promise.all(i.map(e=>
|
|
3653
|
-
`,stderr:``,exitCode:0}}function I8(e){return{stdout:``,stderr:`tar: ${e}\n`,exitCode:1}}function
|
|
3654
|
-
`)}\n`:``,stderr:``,exitCode:0}}async function
|
|
3655
|
-
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=
|
|
3656
|
-
`)}\n`:``,stderr:``,exitCode:0}}function
|
|
3649
|
+
`,exitCode:1};let a=YJ(e[0],e.slice(1)),o=await t.requestApproval({kind:`command`,detail:a});if(o.decision===`deny`)return sve(o);if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}function N8(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|no such file/i.test(t)?`No such file or directory`:/ENOTEMPTY|not empty/i.test(t)?`Directory not empty`:t.replace(/^\w+:\s*/,``)}async function P8(e,t){return e.fs.lstat?e.fs.lstat(t):e.fs.stat(t)}function F8(e,t){return e.some(e=>/^-[^-]/.test(e)&&e.slice(1).includes(t))}async function lve(e,t,n){let r=e.fs.resolvePath(e.cwd,t);try{let i=await P8(e,r);return i.isDirectory&&!i.isSymbolicLink&&!n.recursive?{stdout:``,stderr:`rm: cannot remove '${t}': Is a directory\n`}:(await e.fs.rm(r,{recursive:n.recursive,force:n.force}),{stdout:n.verbose?`removed '${t}'\n`:``,stderr:``})}catch(e){return{stdout:``,stderr:n.force?``:`rm: cannot remove '${t}': ${N8(e)}\n`}}}function uve(){return V(`rm`,async(e,t)=>{let n={recursive:F8(e,`r`)||F8(e,`R`)||e.includes(`--recursive`),force:F8(e,`f`)||e.includes(`--force`),verbose:F8(e,`v`)||e.includes(`--verbose`)},r=e.filter(e=>!e.startsWith(`-`));if(r.length===0)return n.force?{stdout:``,stderr:``,exitCode:0}:{stdout:``,stderr:`rm: missing operand
|
|
3650
|
+
`,exitCode:1};let i=await Promise.all(r.map(e=>lve(t,e,n))),a=i.map(e=>e.stdout).join(``),o=i.map(e=>e.stderr).join(``);return{stdout:a,stderr:o,exitCode:+!!o}})}function dve(e,t,n){let r=n.isSymbolicLink?`symbolic link`:n.isDirectory?`directory`:`regular file`;return e.replace(/%n/g,t).replace(/%N/g,`'${t}'`).replace(/%s/g,String(n.size)).replace(/%F/g,r).replace(/%a/g,n.mode.toString(8))}function fve(e){let t={follow:!1,paths:[]};for(let n=0;n<e.length;n++){let r=e[n];r===`-L`||r===`--dereference`?t.follow=!0:r===`-c`&&e[n+1]?t.format=e[++n]:r.startsWith(`--format=`)?t.format=r.slice(9):r.startsWith(`-`)||t.paths.push(r)}return t}async function pve(e,t,n){try{let r=e.fs.resolvePath(e.cwd,t),i=n.follow?await e.fs.stat(r):await P8(e,r);return{stdout:n.format?`${dve(n.format,t,i)}\n`:` File: ${t}\n Size: ${i.size}\n`,stderr:``}}catch{return{stdout:``,stderr:`stat: cannot stat '${t}': No such file or directory\n`}}}function mve(){return V(`stat`,async(e,t)=>{let n=fve(e);if(n.paths.length===0)return{stdout:``,stderr:`stat: missing operand
|
|
3651
|
+
`,exitCode:1};let r=await Promise.all(n.paths.map(e=>pve(t,e,n))),i=r.map(e=>e.stdout).join(``),a=r.map(e=>e.stderr).join(``);return{stdout:i,stderr:a,exitCode:+!!a}})}function hve(e){let t=e.replace(/\/+$/,``),n=t.lastIndexOf(`/`);return n<=0?`/`:t.slice(0,n)}async function gve(e,t,n,r){let i=e.fs.resolvePath(`/`,t).split(`/`).filter(Boolean),a=e.fs.resolvePath(e.cwd,t),o=``;for(let s=0;s<i.length;s++){try{let t=await P8(e,a);if(!t.isDirectory||t.isSymbolicLink)throw Error(`Not a directory`);await e.fs.rm(a,{recursive:!1,force:!1}),r&&(o+=`rmdir: removing directory, '${a}'\n`)}catch(e){return{stdout:o,stderr:`rmdir: failed to remove '${t}': ${N8(e)}\n`}}if(!n||s===i.length-1)return{stdout:o,stderr:``};a=hve(a)}return{stdout:o,stderr:``}}function _ve(){return V(`rmdir`,async(e,t)=>{let n=e.some(e=>e===`-p`||e===`--parents`),r=e.some(e=>e===`-v`||e===`--verbose`),i=e.filter(e=>!e.startsWith(`-`));if(i.length===0)return{stdout:``,stderr:`rmdir: missing operand
|
|
3652
|
+
`,exitCode:1};let a=await Promise.all(i.map(e=>gve(t,e,n,r))),o=a.map(e=>e.stdout).join(``),s=a.map(e=>e.stderr).join(``);return{stdout:o,stderr:s,exitCode:+!!s}})}function vve(){return{stdout:`usage: tar (-c|-x|-t) [-zv] -f <archive> [-C <dir>] [paths...]
|
|
3653
|
+
`,stderr:``,exitCode:0}}function I8(e){return{stdout:``,stderr:`tar: ${e}\n`,exitCode:1}}function yve(e,t){if(e.mode)return I8(`exactly one of -c, -x, or -t is required`);e.mode=t}function bve(e,t,n){if(n)return[n,t];let r=e[t+1];return r===void 0?void 0:[r,t+1]}const xve={c:`create`,x:`extract`,t:`list`};function Sve(e,t,n,r,i){let a=xve[e];if(a)return{nextIndex:r,error:yve(i,a)};if(e===`z`)return i.gzip=!0,{nextIndex:r};if(e===`v`)return i.verbose=!0,{nextIndex:r};if(e!==`f`&&e!==`C`)return{nextIndex:r,error:I8(`unsupported option -${e}`)};let o=bve(n,r,t);return o?(e===`f`?i.archive=o[0]:i.directory=o[0],{nextIndex:o[1],consumedValue:!0}):{nextIndex:r,error:I8(`option -${e} requires an argument`)}}function Cve(e,t,n){let r=e[t];for(let i=1;i<r.length;i++){let a=Sve(r[i],r.slice(i+1),e,t,n);if(a.error||a.consumedValue)return a}return{nextIndex:t}}function wve(e){let t={gzip:!1,verbose:!1,directory:`.`,paths:[]};for(let n=0;n<e.length;n++){let r=e[n];if(!r.startsWith(`-`)||r===`-`){t.paths.push(r);continue}if(r.startsWith(`--`))return I8(`unsupported option ${r}`);let i=Cve(e,n,t);if(i.error)return i.error;n=i.nextIndex}return t}function Tve(e,t){let n=e.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^(?:\.\/)+/,``);return n?n===`.`?`.`:n.replace(/\/+$/,``):Ba(t)}async function L8(e,t,n,r){let i=await e.fs.stat(t);if(i.isFile){r.push({path:n,bytes:await e.fs.readFileBuffer(t)});return}if(!i.isDirectory)throw Error(`unsupported file type: ${t}`);let a=n.endsWith(`/`)?n:`${n}/`;r.push({path:a,bytes:new Uint8Array,directory:!0});for(let n of await e.fs.readdir(t))await L8(e,za(t,n),`${a}${n}`,r)}function Eve(e,t){let n=e.length>=2&&e[0]===31&&e[1]===139,r=t||n?Wee(e):e;return Bee(r,{stripNpmPrefix:!1,includeDirectories:!0,preserveRawPaths:!0})}function Dve(e,t,n){let r=n.replace(/\\/g,`/`);if(!r||r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)||r.split(`/`).includes(`..`))return;let i=e.fs.resolvePath(t,r);return Ja(t,i)?i:void 0}async function Ove(e,t){if(e.paths.length===0)return I8(`create mode requires at least one input path`);let n=[],r=t.fs.resolvePath(t.cwd,e.directory);for(let i of e.paths){let e=t.fs.resolvePath(r,i);await L8(t,e,Tve(i,e),n)}let i=t.fs.resolvePath(t.cwd,e.archive),a=Kee(n);return await t.fs.writeFile(i,e.gzip?Iee(a):a),{stdout:e.verbose?`${n.map(e=>e.path).join(`
|
|
3654
|
+
`)}\n`:``,stderr:``,exitCode:0}}async function kve(e,t){if(e.paths.length>0)return I8(`${e.mode} mode does not accept input paths`);let n=t.fs.resolvePath(t.cwd,e.archive),r=Eve(await t.fs.readFileBuffer(n),e.gzip);if(e.mode===`list`){let e=r.map(e=>e.path).join(`
|
|
3655
|
+
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=Dve(t,i,e.path);if(!n)return I8(`blocked suspicious path ${e.path}`);if(e.directory)await t.fs.mkdir(n,{recursive:!0});else{let r=Ga(n);r!==`/`&&await t.fs.mkdir(r,{recursive:!0}),await t.fs.writeFile(n,e.bytes)}a.push(e.path)}return{stdout:e.verbose?`${a.join(`
|
|
3656
|
+
`)}\n`:``,stderr:``,exitCode:0}}function Ave(){return V(`tar`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return vve();let n=wve(e);return`exitCode`in n?n:n.mode?n.archive?n.mode===`list`&&n.directory!==`.`?I8(`-C is only supported in create or extract mode`):n.mode===`create`?Ove(n,t):kve(n,t):I8(`option -f requires an archive path`):I8(`exactly one of -c, -x, or -t is required`)})}var jve=`/**
|
|
3657
3657
|
* Standalone assertions - no dependency on test runner
|
|
3658
3658
|
*
|
|
3659
3659
|
* Each assertion:
|
|
@@ -3841,7 +3841,7 @@ function sameMembers(a, b) {
|
|
|
3841
3841
|
}
|
|
3842
3842
|
|
|
3843
3843
|
const slice = a => (isPrimitive(a) ? a : a.slice ? a.slice() : Object.assign({}, a))
|
|
3844
|
-
`,
|
|
3844
|
+
`,Mve=`/**
|
|
3845
3845
|
* tst - minimal test runner
|
|
3846
3846
|
*
|
|
3847
3847
|
* - Standalone assertions (assert.js works anywhere)
|
|
@@ -4495,27 +4495,27 @@ Install:
|
|
|
4495
4495
|
Then \`tsc --version\` and the transpile commands above. There is no
|
|
4496
4496
|
bundled binary, no CDN fallback; a missing package exits non-zero
|
|
4497
4497
|
with a clear \`ipk add\` hint.
|
|
4498
|
-
`;function
|
|
4499
|
-
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function
|
|
4500
|
-
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function
|
|
4498
|
+
`;function Nve(e){let t=[],n=!1,r=null,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s===`-h`||s===`--help`){i=!0;continue}if(s===`-v`||s===`--version`){a=!0;continue}if(s===`--noEmit`){n=!0;continue}if(s===`--outDir`){let t=e[o+1];if(typeof t!=`string`||t.startsWith(`-`))throw Error(`tsc: --outDir requires a value`);r=t,o+=1;continue}if(s.startsWith(`--outDir=`)){r=s.slice(9);continue}if(s.startsWith(`-`))throw Error(`tsc: unknown option: ${s}`);t.push(s)}return{files:t,noEmit:n,outDir:r,showHelp:i,showVersion:a}}function Pve(e,t){let n=`${Ba(e).replace(/\.(ts|tsx|mts|cts)$/i,``)}.js`;return t?`${t.endsWith(`/`)?t.slice(0,-1):t}/${n}`:`${Ga(e)}/${n}`}async function Fve(e,t){let n=t||`/`,r=``;for(;n&&n!==r;){let t=n===`/`?`/tsconfig.json`:`${n}/tsconfig.json`;if(await e.exists(t))return t;r=n,n=Ga(n)}return null}function Ive(e){return{target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0}}function Lve(e){if(typeof e!=`object`||!e)return{};let{compilerOptions:t}=e;return t??{}}async function Rve(e,t,n){let r=Ive(t),i=await Fve(e,n);if(!i)return{compilerOptions:{...r}};let a;try{a=await e.readFile(i)}catch{return{compilerOptions:{...r}}}let{config:o,error:s}=t.parseConfigFileTextToJson(i,a);return s||!o?{compilerOptions:{...r}}:{compilerOptions:{...r,...Lve(o)}}}function B8(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
|
|
4499
|
+
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function zve(e,t){let n=t.toLowerCase();return n.endsWith(`.tsx`)?e.ScriptKind.TSX:n.endsWith(`.jsx`)?e.ScriptKind.JSX:n.endsWith(`.js`)||n.endsWith(`.mjs`)||n.endsWith(`.cjs`)?e.ScriptKind.JS:e.ScriptKind.TS}function V8(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Bve(e,t,n,r){let{outputText:i,diagnostics:a}=V8(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>B8(e,t)),s=o.length>0?`${o.join(`
|
|
4500
|
+
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function Vve(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,n);if(!await t.fs.exists(a))return{stderr:`tsc: ${n}: no such file\n`,hadError:!0};let o;try{o=await t.fs.readFile(a)}catch(e){return{stderr:`tsc: ${n}: ${e instanceof Error?e.message:String(e)}\n`,hadError:!0}}zve(e,a);let{outputText:s,diagnostics:c}=V8(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${B8(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,Pve(a,r.outDir));try{await t.fs.writeFile(d,s)}catch(e){l.push(`tsc: ${d}: ${e instanceof Error?e.message:String(e)}\n`),u=!0}return{stderr:l.join(``),hadError:u}}async function Hve(e,t){let n;try{n=Nve(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:z8,stderr:``,exitCode:0}};let r;try{r=await Ia(R8(t))}catch(e){return{done:{stdout:``,stderr:`tsc: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}return n.showVersion?{done:{stdout:`Version ${r.version}\n`,stderr:``,exitCode:0}}:{parsed:n,ts:r}}function Uve(){return V(`tsc`,async(e,t)=>{let n=await Hve(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await Rve(t.fs,i,t.cwd);if(r.files.length===0){let e=mo(t.stdin);return e?Bve(i,r,a,e):{stdout:z8,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await Vve(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const Wve=[`**/*.test.{js,ts}`];function Gve(e){let t=[],n=`tap`,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`-h`||a===`--help`){r=!0;continue}if(a===`--reporter`){let t=e[i+1];if(t!==`tap`&&t!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=t,i+=1;continue}if(a.startsWith(`--reporter=`)){let e=a.slice(11);if(e!==`tap`&&e!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=e;continue}if(a.startsWith(`-`))throw Error(`test: unknown option: ${a}`);t.push(a)}return{globs:t.length>0?t:[...Wve],reporter:n,showHelp:r}}function H8(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=e.indexOf(`}`,t);if(n===-1)return[e];let r=e.slice(0,t),i=e.slice(n+1),a=e.slice(t+1,n).split(`,`),o=[];for(let e of a)for(let t of H8(`${r}${e}${i}`))o.push(t);return o}function Kve(e){let t=``,n=0;for(;n<e.length;){let r=e[n];r===`*`&&e[n+1]===`*`?(t+=`(?:.*/)?`,n+=2,e[n]===`/`&&(n+=1)):r===`*`?(t+=`[^/]*`,n+=1):r===`?`?(t+=`[^/]`,n+=1):`.+^$()[]|\\`.includes(r)?(t+=`\\${r}`,n+=1):(t+=r,n+=1)}return RegExp(`^${t}$`)}async function qve(e,t,n){let r=n.flatMap(H8).map(Kve),i=new Set,a=t===`/`?``:t;async function o(t){let n;try{n=await e.readdir(t)}catch{return}for(let s of n){if(s===`node_modules`||s.startsWith(`.`))continue;let n=t===`/`?`/${s}`:`${t}/${s}`,c=!1;try{c=(await e.stat(n)).isDirectory}catch{continue}if(c){await o(n);continue}let l=n.startsWith(`${a}/`)?n.slice(a.length+1):n;r.some(e=>e.test(l))&&i.add(n)}}return await o(t),[...i].sort()}let U8=null;async function Jve(e){if(U8)return U8;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return U8=`
|
|
4501
4501
|
if (typeof process !== 'undefined' && !process.versions) {
|
|
4502
4502
|
try { process.versions = { node: '20.0.0' }; } catch (_) { /* readonly process.versions is fine */ }
|
|
4503
4503
|
}
|
|
4504
4504
|
const __tst_assert_exports = (function () {
|
|
4505
4505
|
const module = { exports: {} };
|
|
4506
4506
|
const exports = module.exports;
|
|
4507
|
-
${e.transpileModule(
|
|
4507
|
+
${e.transpileModule(jve,{compilerOptions:t,fileName:`assert.js`}).outputText}
|
|
4508
4508
|
return module.exports;
|
|
4509
4509
|
})();
|
|
4510
4510
|
const __tst_module_exports = (function () {
|
|
4511
4511
|
const module = { exports: {} };
|
|
4512
4512
|
const exports = module.exports;
|
|
4513
|
-
${e.transpileModule(
|
|
4513
|
+
${e.transpileModule(Mve,{compilerOptions:t,fileName:`tst.js`}).outputText.replace(/require\(["']\.\/assert\.js["']\)/g,`__tst_assert_exports`).replace(/\bimport\.meta\b/g,`({url:""})`).replace(/await\s+import\(['"](?:worker_threads|fs|path)['"]\)/g,`await Promise.reject(new Error("test: fork mode is not supported in the realm"))`)}
|
|
4514
4514
|
return module.exports;
|
|
4515
4515
|
})();
|
|
4516
4516
|
const __tst = __tst_module_exports.default || __tst_module_exports;
|
|
4517
4517
|
__tst.manual = true;
|
|
4518
|
-
`.trim(),U8}function W8(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function
|
|
4518
|
+
`.trim(),U8}function W8(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function Yve(e){let t=new Set,n=/(?:^|[^\w$.])require\(\s*(["'`])([^"'`]+)\1\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[2]);return[...t]}async function Xve(e,t,n){let r=_n(`${t}/${n}`),i=[r];r.endsWith(`.js`)&&i.push(`${r.slice(0,-3)}.ts`),/\.[a-zA-Z0-9]+$/.test(r)||i.push(`${r}.ts`,`${r}.js`);for(let t of i)if(await e.exists(t))return t;return null}async function Zve(e,t,n,r,i){let a=new Map,o=new Map,s=[{path:n,cjs:r}];for(;s.length>0;){let{path:n,cjs:r}=s.shift(),c=Ga(n),l=new Map;for(let n of Yve(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await Xve(e,c,n);if(!r||(l.set(n,r),a.has(r)))continue;let o=await e.readFile(r),u=t.transpileModule(o,{compilerOptions:i,fileName:r}).outputText;a.set(r,u),s.push({path:r,cjs:u})}o.set(n,l)}return{modules:a,edgeRewrites:o}}function Qve(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=W8(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
|
|
4519
4519
|
${e}
|
|
4520
4520
|
const __tstReq = (id) => {
|
|
4521
4521
|
if (id === "tst") return __tst_module_exports;
|
|
@@ -4547,7 +4547,7 @@ const __state = await __tst.run({ format: ${JSON.stringify(o)} });
|
|
|
4547
4547
|
await Promise.resolve();
|
|
4548
4548
|
await new Promise((resolve) => setTimeout(resolve));
|
|
4549
4549
|
if (__state && __state.failed && __state.failed.length > 0) process.exit(1);
|
|
4550
|
-
`}const
|
|
4550
|
+
`}const $ve={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function eye(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...$ve}}async function tye(e,t){let n;try{n=Gve(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:`test - run *.test.{js,ts} files with the bundled tst runner
|
|
4551
4551
|
|
|
4552
4552
|
Usage:
|
|
4553
4553
|
test [options] [glob...]
|
|
@@ -4560,7 +4560,7 @@ Notes:
|
|
|
4560
4560
|
- Default glob: **/*.test.{js,ts}, walked from the current cwd.
|
|
4561
4561
|
- .ts files are transpiled via the bundled typescript package.
|
|
4562
4562
|
- Each file runs in its own realm (same engine as 'node').
|
|
4563
|
-
`,stderr:``,exitCode:0}};let r=await
|
|
4563
|
+
`,stderr:``,exitCode:0}};let r=await qve(t.fs,t.cwd,n.globs);if(r.length===0)return{done:{stdout:``,stderr:`test: no test files matched ${n.globs.join(` `)}\n`,exitCode:1}};let i;try{i=await Ia(R8(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await Jve(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:eye(i)}}function nye(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function rye(e,t,n,r){let{ts:i,harness:a,userOpts:o,parsed:s}=t,c;try{c=await e.fs.readFile(n)}catch(e){return{stdout:``,stderr:`test: ${n}: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let l;try{l=i.transpileModule(c,{compilerOptions:o,fileName:n}).outputText}catch(e){return{stdout:``,stderr:`test: ${n}: transpile error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let u,d;try{({modules:u,edgeRewrites:d}=await Zve(e.fs,i,n,l,o))}catch(e){return{stdout:``,stderr:`test: ${n}: local-require resolve error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let f=await lJ(Qve(a,n,l,s.reporter,u,d),[`node`,n],e,void 0,{filename:n});return{stdout:r?`# ${n}\n${f.stdout}`:f.stdout,stderr:f.stderr,failed:f.exitCode!==0||nye(f.stdout)}}function iye(){return V(`test`,async(e,t)=>{let n=await tye(e,t);if(`done`in n)return n.done;let r=n.files.length>1,i=``,a=``,o=!1;for(let e of n.files){let s=await rye(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}const G8=[],K8=`usage: theme <subcommand> [args]
|
|
4564
4564
|
|
|
4565
4565
|
Subcommands:
|
|
4566
4566
|
list List available preset and custom themes
|
|
@@ -4569,23 +4569,23 @@ Subcommands:
|
|
|
4569
4569
|
reset Reset to the default theme
|
|
4570
4570
|
current Show the currently active theme
|
|
4571
4571
|
export <id> <path> Export a theme to a VFS path
|
|
4572
|
-
`;function q8(e,t){return{stdout:``,stderr:`theme ${e}: ${t}\n`,exitCode:1}}function
|
|
4573
|
-
`),stderr:``,exitCode:0}}async function
|
|
4574
|
-
`,stderr:``,exitCode:0}}async function
|
|
4572
|
+
`;function q8(e,t){return{stdout:``,stderr:`theme ${e}: ${t}\n`,exitCode:1}}function aye(){return V(`theme`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return{stdout:K8,stderr:``,exitCode:0};let n=e[0];return oi(e.slice(1),{valueFlags:G8})?{stdout:ai(`theme`,n,K8),stderr:``,exitCode:0}:n===`list`?oye(e):n===`current`?sye(e):n===`reset`?cye(e):n===`apply`?lye(e.slice(1),t):n===`export`?uye(e.slice(1),t):{stdout:``,stderr:`theme: unknown subcommand "${n}"\n${K8}`,exitCode:1}})}async function oye(e){let t=H(e.slice(1),{value:G8});if(`error`in t)return q8(`list`,t.error);let{PRESETS:n}=await import(`./theme-presets-xiOb9AFN.js`),r=[`Presets:`];for(let e of n)r.push(` ${e.id.padEnd(16)} ${e.name}`);return r.push(``),{stdout:r.join(`
|
|
4573
|
+
`),stderr:``,exitCode:0}}async function sye(e){let t=H(e.slice(1),{value:G8});return`error`in t?q8(`current`,t.error):{stdout:`Check the Theme settings dialog for the active theme.
|
|
4574
|
+
`,stderr:``,exitCode:0}}async function cye(e){let t=H(e.slice(1),{value:G8});if(`error`in t)return q8(`reset`,t.error);let n=u();return n?(await n.call(`theme-apply`,{action:`reset`}),{stdout:`Theme reset to default.
|
|
4575
4575
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
4576
|
-
`,exitCode:1}}async function
|
|
4576
|
+
`,exitCode:1}}async function lye(e,t){let n=H(e,{value:G8});if(`error`in n)return q8(`apply`,n.error);if(n.positionals.length===0)return{stdout:``,stderr:`theme apply: missing theme id or path
|
|
4577
4577
|
`,exitCode:1};let r=u();if(!r)return{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
4578
4578
|
`,exitCode:1};let i=n.positionals[0],{PRESETS:a}=await import(`./theme-presets-xiOb9AFN.js`),o=a.find(e=>e.id===i);if(o){let e=JSON.stringify(o);return await r.call(`theme-apply`,{themeJson:e,action:`apply`}),{stdout:`Applied theme: ${o.name}\n`,stderr:``,exitCode:0}}let s=t.fs.resolvePath(t.cwd,i),c;try{c=await t.fs.readFile(s)}catch{return{stdout:``,stderr:`theme apply: "${i}" is not a known preset id and file not found at ${s}\n`,exitCode:1}}try{let e=JSON.parse(c);if(!e.id||!e.name||!e.base||!e.tokens)return{stdout:``,stderr:`theme apply: invalid theme file (missing id, name, base, or tokens)
|
|
4579
4579
|
`,exitCode:1}}catch{return{stdout:``,stderr:`theme apply: file is not valid JSON
|
|
4580
|
-
`,exitCode:1}}return{stdout:`Applied theme: ${(await r.call(`theme-apply`,{themeJson:c,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function
|
|
4581
|
-
`,exitCode:1};let[r,i]=n.positionals,{PRESETS:a}=await import(`./theme-presets-xiOb9AFN.js`),o=a.find(e=>e.id===r);if(!o)return{stdout:``,stderr:`theme export: unknown preset id "${r}"\n`,exitCode:1};let s=t.fs.resolvePath(t.cwd,i);try{await t.fs.writeFile(s,JSON.stringify(o,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${o.name}" to ${s}\n`,stderr:``,exitCode:0}}const J8=`unknown`,Y8=`usage: uname [-amnorsv]`,X8=[`s`,`n`,`r`,`v`,`m`,`o`];function
|
|
4582
|
-
`),stderr:``,exitCode:0}}function
|
|
4580
|
+
`,exitCode:1}}return{stdout:`Applied theme: ${(await r.call(`theme-apply`,{themeJson:c,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function uye(e,t){let n=H(e,{value:G8});if(`error`in n)return q8(`export`,n.error);if(n.positionals.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
|
|
4581
|
+
`,exitCode:1};let[r,i]=n.positionals,{PRESETS:a}=await import(`./theme-presets-xiOb9AFN.js`),o=a.find(e=>e.id===r);if(!o)return{stdout:``,stderr:`theme export: unknown preset id "${r}"\n`,exitCode:1};let s=t.fs.resolvePath(t.cwd,i);try{await t.fs.writeFile(s,JSON.stringify(o,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${o.name}" to ${s}\n`,stderr:``,exitCode:0}}const J8=`unknown`,Y8=`usage: uname [-amnorsv]`,X8=[`s`,`n`,`r`,`v`,`m`,`o`];function dye(){return{stdout:[Y8,` -s kernel name (SLICC) -n nodename (leader/follower/standalone)`,` -r release (SLICC version) -v build stamp`,` -m machine (realm platform) -o operating system (user agent)`,` -a all of the above, in uname order`,``].join(`
|
|
4582
|
+
`),stderr:``,exitCode:0}}function fye(){let{releasedAt:e,buildId:t}=ti();return e?`${t} (${e})`:t}function pye(){let e=globalThis.navigator,t=e?.userAgentData?.platform||e?.platform;return typeof t==`string`&&t.length>0?t:J8}function mye(){let e=globalThis.navigator?.userAgent;return typeof e==`string`&&e.length>0?e:J8}function hye(e){switch(e){case`s`:return`SLICC`;case`n`:return Mr();case`r`:return ti().version;case`v`:return fye();case`m`:return pye();case`o`:return mye()}}function gye(e){return{stdout:``,stderr:`uname: ${e}\n${Y8}\n`,exitCode:1}}function _ye(e){let t=new Set;for(let n of e){if(!n.startsWith(`-`)||n===`-`)return{error:`extra operand '${n}'`};if(n.startsWith(`--`))return{error:`unrecognized option '${n}'`};for(let e of n.slice(1)){if(e===`a`){for(let e of X8)t.add(e);continue}if(!X8.includes(e))return{error:`unrecognized option '-${e}'`};t.add(e)}}return t}function vye(){return V(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return dye();let t=_ye(e);return`error`in t?gye(t.error):{stdout:`${(t.size>0?X8.filter(e=>t.has(e)):[`s`]).map(hye).join(` `)}\n`,stderr:``,exitCode:0}})}function yye(){return V(`unlink`,async(e,t)=>{if(e.includes(`--help`))return{stdout:`Usage: unlink FILE
|
|
4583
4583
|
Remove FILE. Symbolic links are removed without following their target.
|
|
4584
4584
|
`,stderr:``,exitCode:0};if(e.length!==1||e[0].startsWith(`-`))return{stdout:``,stderr:e.length===0?`unlink: missing operand
|
|
4585
4585
|
`:`unlink: extra operand
|
|
4586
|
-
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e[0]);try{let r=t.fs.lstat?await t.fs.lstat(n):await t.fs.stat(n);return r.isDirectory&&!r.isSymbolicLink?{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': Is a directory\n`,exitCode:1}:(await t.fs.rm(n,{recursive:!1,force:!1}),{stdout:``,stderr:``,exitCode:0})}catch(t){let n=t instanceof Error?t.message:String(t);return{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': ${n}\n`,exitCode:1}}})}function
|
|
4587
|
-
`,stderr:``,exitCode:0}}function
|
|
4588
|
-
`,exitCode:1}}:{kind:`ok`,archive:n[0],destination:t||`.`}}async function
|
|
4586
|
+
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e[0]);try{let r=t.fs.lstat?await t.fs.lstat(n):await t.fs.stat(n);return r.isDirectory&&!r.isSymbolicLink?{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': Is a directory\n`,exitCode:1}:(await t.fs.rm(n,{recursive:!1,force:!1}),{stdout:``,stderr:``,exitCode:0})}catch(t){let n=t instanceof Error?t.message:String(t);return{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': ${n}\n`,exitCode:1}}})}function bye(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
4587
|
+
`,stderr:``,exitCode:0}}function xye(e){let t=`.`,n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`-d`){t=e[r+1]??``,r++;continue}if(i.startsWith(`-`))return{kind:`error`,result:{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1}};n.push(i)}return n.length<1?{kind:`error`,result:{stdout:``,stderr:`unzip: expected archive path
|
|
4588
|
+
`,exitCode:1}}:{kind:`ok`,archive:n[0],destination:t||`.`}}async function Sye(e,t,n,r){let i=n.replace(/\\/g,`/`);if(!i||i.endsWith(`/`))return!1;let a=e.fs.resolvePath(t,i);if(!Ja(t,a))return{stdout:``,stderr:`unzip: blocked suspicious path ${n}\n`,exitCode:1};let o=Ga(a);return o!==`/`&&await e.fs.mkdir(o,{recursive:!0}),await e.fs.writeFile(a,r),!0}function Cye(){return V(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return bye();let n=xye(e);if(n.kind===`error`)return n.result;let r=t.fs.resolvePath(t.cwd,n.archive),i=t.fs.resolvePath(t.cwd,n.destination);await t.fs.mkdir(i,{recursive:!0});let a=await t.fs.readFileBuffer(r),o=Wi(a),s=0;for(let[e,n]of Object.entries(o)){let r=await Sye(t,i,e,n);if(r===!0)s++;else if(r!==!1)return r}return{stdout:`extracted ${s} file(s) to ${i}\n`,stderr:``,exitCode:0}})}const Z8=`ai-ecoverse/slicc`,Q8=`usage: upgrade status | upgrade apply --from=<version> --to=<version>`,$8=`packages/vfs-root`,e5=3e4,wye=[`${$8}/workspace/skills/`,`${$8}/shared/sprinkles/`,`${$8}/shared/sounds/`,`${$8}/shared/MEMORY.md`,`${$8}/shared/DREAMING.md`,`${$8}/shared/GELATIERE.md`,`${$8}/shared/wiki/WIKI.md`,`${$8}/etc/`],Tye=[`auto-applied`,`merged-clean`,`kept-local`,`needs-review`,`unchanged`,`added-new`];function Eye(){return Object.fromEntries(Tye.map(e=>[e,0]))}function t5(e,t,n,r){let i=Eye();for(let e of n)i[e.classification]+=1;return`${JSON.stringify({ok:r.length===0&&i[`needs-review`]===0,from:e,to:t,results:n.map(({path:e,classification:t,sidecar:n})=>({path:e,status:t,...n?{sidecar:n}:{}})),summary:i,errors:r})}\n`}function Dye(e){if(e[0]!==`apply`)throw Error(Q8);let t=new Map;for(let n of e.slice(1)){let e=n.match(/^--(from|to)=(.+)$/);if(!e)throw Error(`unsupported argument: ${n}`);t.set(e[1],e[2])}let n=t.get(`from`)??``,r=t.get(`to`)??``,i=/^v?[0-9][0-9A-Za-z.+_-]*$/;if(!i.test(n)||!i.test(r))throw Error(`both --from and --to must be release versions`);return{from:n,to:r}}function n5(e){return e.startsWith(`v`)?e:`v${e}`}function Oye(e){if(!wye.some(t=>e.startsWith(t)))return null;let t=e.slice(17);return!t||t.split(`/`).some(e=>e===`.`||e===`..`)?null:t}async function r5(e,t){let n,r;try{n=await Promise.race([e(t,{method:`GET`,headers:{Accept:`application/json`}}),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`request timed out after ${e5}ms`)),e5)})])}catch(e){let n=e instanceof Error?e.message:String(e);throw Error(`fetch failed for ${t}: ${n}`)}finally{r!==void 0&&clearTimeout(r)}if(n.status<200||n.status>=300)throw Error(`fetch failed for ${t}: HTTP ${n.status} ${n.statusText}`);return n}async function i5(e,t){let n=await r5(t,`https://api.github.com/repos/${Z8}/git/trees/${encodeURIComponent(e)}?recursive=1`),r=Se(n.body);if(r.truncated)throw Error(`bundled file discovery was truncated for ${e}`);if(!Array.isArray(r.tree))throw Error(`invalid bundled file discovery response for ${e}`);let i=new Map;for(let e of r.tree){if(e.type!==`blob`||typeof e.path!=`string`)continue;let t=Oye(e.path);t&&i.set(t,e.path)}return i}function a5(e,t){let n=t.split(`/`).map(encodeURIComponent).join(`/`);return`https://raw.githubusercontent.com/${Z8}/${encodeURIComponent(e)}/${n}`}function o5(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}function kye(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}async function s5(e,t){if(!await e.exists(t))return;let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async function c5(e,t,n,r,i){let a=`${t}.upgrade-${n5(n)}-to-${n5(r)}.conflict`;if(!i.has(a)&&!await e.exists(a))return i.add(a),a;for(let t=1;;t+=1){let n=`${a}.${t}`;if(!i.has(n)&&!await e.exists(n))return i.add(n),n}}async function Aye(e,t,n,r,i,a,o){let s=await s5(e.fs,t);if(!a)return{path:t,classification:s?`kept-local`:`unchanged`};if(!i)return s?{path:t,classification:o5(s,a)?`unchanged`:`kept-local`}:{path:t,classification:`added-new`,content:a};if(o5(i,a)||o5(s,a))return{path:t,classification:`unchanged`};if(!s)return{path:t,classification:`kept-local`};if(o5(s,i))return{path:t,classification:`auto-applied`,content:a};let[c,l,u]=[s,i,a].map(kye);if(c!==null&&l!==null&&u!==null){let i=bn(c,l,u,{diff3:!0,labels:{current:`local:${t}`,base:`${n5(n)}:${t}`,other:`${n5(r)}:${t}`}}),a=new TextEncoder().encode(i.content);return i.conflicts===0?{path:t,classification:`merged-clean`,content:a}:{path:t,classification:`needs-review`,content:a,sidecar:await c5(e.fs,t,n,r,o)}}return{path:t,classification:`needs-review`,content:a,sidecar:await c5(e.fs,t,n,r,o)}}async function jye(e,t){t.content?await e.writeFile(t.path,t.content):await e.exists(t.path)&&await e.rm(t.path)}async function Mye(e,t){let n=t.filter(e=>e.content!==void 0),r=await Promise.all(n.map(async t=>{let n=t.sidecar??t.path;return{path:n,content:await s5(e,n)}})),i=[];for(let t=0;t<n.length;t+=1){let a=n[t],o=r[t];try{await e.writeFile(o.path,a.content),i.push(o)}catch(t){let n=[];for(let t of[o,...i.slice().reverse()])try{await jye(e,t)}catch(e){n.push(`${t.path}: ${e instanceof Error?e.message:String(e)}`)}let r=t instanceof Error?t.message:String(t),a=n.length===0?`all writes rolled back`:`rollback failed (${n.join(`; `)})`;throw Error(`apply failed for ${o.path}: ${r}; ${a}`)}}}async function Nye(e,t,n){let r=n5(t),i=n5(n),[a,o]=await Promise.all([i5(r,e.fetch),i5(i,e.fetch)]),s=[...new Set([...a.keys(),...o.keys()])].sort(),c=await Promise.all(s.map(async t=>{let[n,s]=await Promise.all([a.has(t)?r5(e.fetch,a5(r,a.get(t))).then(e=>j(e.body)):void 0,o.has(t)?r5(e.fetch,a5(i,o.get(t))).then(e=>j(e.body)):void 0]);return{path:t,base:n,theirs:s}})),l=new Set(s),u=[];for(let{path:r,base:i,theirs:a}of c)u.push(await Aye(e,r,t,n,i,a,l));return await Mye(e.fs,u),u}async function Pye(e){let{version:t,releasedAt:n,buildId:r}=ti(),i=[],a=null,o=e.getLastSeen??vee();if(!o)i.push(`last-seen version unavailable: no reader registered in this runtime`);else try{a=await o()}catch(e){i.push(`last-seen version unavailable: ${e instanceof Error?e.message:String(e)}`)}let s=a!==null&&a!==t;return`${JSON.stringify({ok:i.length===0,version:t,releasedAt:n,build:r,lastSeen:a,mergePending:s,...s?{apply:`upgrade apply --from=${a} --to=${t}`}:{},errors:i})}\n`}function Fye(e){return V(`upgrade`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`${Q8}\n`,stderr:``,exitCode:0};if(t[0]===`status`)return t.length>1?{stdout:t5(``,``,[],[`unsupported argument: ${t[1]}`]),stderr:``,exitCode:1}:{stdout:await Pye(e),stderr:``,exitCode:0};let n=``,r=``;try{({from:n,to:r}=Dye(t));let i=await Nye(e,n,r),a=i.some(e=>e.classification===`needs-review`);return{stdout:t5(n,r,i,[]),stderr:``,exitCode:+!!a}}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:t5(n,r,[],[t]),stderr:``,exitCode:1}}})}const l5=`usage: uptime [-p|--pretty] [-s|--since]`,Iye=`${l5}
|
|
4589
4589
|
|
|
4590
4590
|
Print how long this SLICC has been running. The clock starts when the browser
|
|
4591
4591
|
window was last loaded — a reload is a reboot.
|
|
@@ -4601,7 +4601,7 @@ The load average is the average number of live kernel processes over the last
|
|
|
4601
4601
|
processes are retained in bounded numbers, so a long burst of short commands
|
|
4602
4602
|
can under-report the older windows. The user count is always 1: a SLICC
|
|
4603
4603
|
runtime has one user identity (see \`id\`).
|
|
4604
|
-
`,
|
|
4604
|
+
`,Lye=[1,5,15],u5=6e4,d5=60*u5,f5=24*d5;function Rye(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.list==`function`?e:null}function zye(e,t,n,r){let i=Math.min(n,Math.max(1,t-r)),a=t-i,o=0;for(let n of e){let e=Math.min(n.finishedAt??t,t);o+=Math.max(0,e-Math.max(n.startedAt,a))}return o/i}function Bye(e){let t=Math.max(0,e),n=Math.floor(t/f5),r=Math.floor(t%f5/d5),i=Math.floor(t%d5/u5),a=r>0?`${r}:${String(i).padStart(2,`0`)}`:`${i} min`;return n===0?a:`${n} ${n===1?`day`:`days`}, ${a}`}function Vye(e){let t=Math.max(0,e),n=[],r=(e,t)=>{e>0&&n.push(`${e} ${t}${e===1?``:`s`}`)};return r(Math.floor(t/f5),`day`),r(Math.floor(t%f5/d5),`hour`),r(Math.floor(t%d5/u5),`minute`),n.length===0?`up ${Math.floor(t/1e3)} seconds`:`up ${n.join(`, `)}`}function Hye(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}`} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Uye(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function Wye(e,t,n){let r=Lye.map(r=>zye(e,t,r*u5,n).toFixed(2));return` ${Uye(t)} up ${Bye(t-n)}, 1 user, load average: ${r.join(`, `)}\n`}function Gye(e){let t=`default`;for(let n of e)switch(n){case`-p`:case`--pretty`:t=`pretty`;break;case`-s`:case`--since`:t=`since`;break;case`-h`:case`--help`:return`help`;case`--version`:return`version`;default:return{error:`unrecognized option '${n}'`}}return t}function Kye(e={}){return V(`uptime`,async t=>{let n=Gye(t);if(typeof n!=`string`)return{stdout:``,stderr:`uptime: ${n.error}\n${l5}\n`,exitCode:1};if(n===`help`)return{stdout:Iye,stderr:``,exitCode:0};if(n===`version`)return{stdout:`uptime (SLICC) ${ti().version}\n`,stderr:``,exitCode:0};let r=e.now?e.now():Date.now(),i=e.bootedAt?e.bootedAt():$ee();if(n===`since`)return p5(`${Hye(i)}\n`);if(n===`pretty`)return p5(`${Vye(r-i)}\n`);let a=e.processManager??Rye();return p5(Wye(a?a.list():[],r,i))})}function p5(e){return{stdout:e,stderr:``,exitCode:0}}const qye=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function Jye(e){return Ji(e,qye)}function m5(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function Yye(e){let t={};return e.has(`--vid`)&&(t.vendorId=m5(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=m5(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=m5(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=m5(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=m5(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const Xye=new Set([`standard`,`class`,`vendor`]),Zye=new Set([`device`,`interface`,`endpoint`,`other`]);function h5(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!Xye.has(t))throw Error(`invalid --request-type: '${t}'`);if(!Zye.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:m5(e.get(`--request`)??`0`,`request`),value:m5(e.get(`--value`)??`0`,`value`),index:m5(e.get(`--index`)??`0`,`index`)}}function g5(e){let t=po(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function Qye(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function _5(e){return`0x${e.toString(16).padStart(4,`0`)}`}function v5(e){let t=[e.manufacturerName,e.productName].filter(Boolean).join(` `)||`(unknown)`,n=e.serialNumber?` serial=${e.serialNumber}`:``,r=e.opened?` [open]`:``;return`${e.handle}\t${_5(e.vendorId)}:${_5(e.productId)}\t${t}${n}${r}`}function y5(e){return{stdout:e,stderr:``,exitCode:0}}function b5(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const $ye=`usb - access USB devices via WebUSB
|
|
4605
4605
|
|
|
4606
4606
|
Usage: usb <subcommand> [options]
|
|
4607
4607
|
|
|
@@ -4640,9 +4640,9 @@ Options:
|
|
|
4640
4640
|
-h, --help
|
|
4641
4641
|
|
|
4642
4642
|
Transfers are capped at ${fo} bytes (4 MiB).
|
|
4643
|
-
`;function x5(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return y5(t)}return y5(e.length?`${
|
|
4643
|
+
`;function x5(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return y5(t)}return y5(e.length?`${Qye(e)}\n`:``)}async function ebe(e){let t=await e.list();return t.length===0?y5(`no granted USB devices
|
|
4644
4644
|
`):y5(`${t.map(v5).join(`
|
|
4645
|
-
`)}\n`)}async function
|
|
4645
|
+
`)}\n`)}async function tbe(e,t){let n=e.get(`--__resolved`);if(n)return y5(`${v5(await t.info(n))}\n`);let r=Yye(e),i=tn();if(i){let e=await b2(`usb-device`,r,i);if(e.handle)return y5(`${v5(await t.info(e.handle))}\n`);let n=e.info,a=lo();if(!a)return b5(`request: WebUSB unavailable for device re-acquire`);let o=(await a.getDevices()).find(e=>e.vendorId===n.vendorId&&e.productId===n.productId&&(!n.serialNumber||e.serialNumber===n.serialNumber));if(!o)return b5(`request: granted device could not be re-acquired`);let s=uo().register(o);return y5(`${v5(oo(s,o))}\n`)}return y5(`${v5(await t.request(r))}\n`)}async function nbe(e,t,n,r){let i=t[1];if(!i)return b5(`${e}: handle required`);let a=r.has(`--force`);return e===`open`?await n.open(i):e===`close`?await n.close(i,{force:a}):await n.reset(i,{force:a}),y5(``)}async function rbe(e,t){let[,n,r,i]=e;return!n||r===void 0||i===void 0?b5(`clear-halt: handle, direction and endpoint required`):r!==`in`&&r!==`out`?b5(`clear-halt: direction must be 'in' or 'out', got '${r}'`):(await t.clearHalt(n,r,m5(i,`endpoint`)),y5(``))}async function ibe(e,t){let[,n,r]=e;return!n||r===void 0?b5(`select-config: handle and value required`):(await t.selectConfig(n,m5(r,`configuration`)),y5(``))}async function abe(e,t,n,r){let[,i,a]=t;if(!i||a===void 0)return b5(`${e}: handle and interface required`);let o=m5(a,`interface`);return e===`claim`?await n.claim(i,o,{wait:r.has(`--wait`)}):await n.release(i,o),y5(``)}async function obe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return b5(`control-in: handle and length required`);let o=m5(a,`length`);return o>4194304?b5(`control-in length exceeds 4 MiB limit`):x5((await n.controlIn(i,h5(t),o)).bytes,r)}async function sbe(e,t,n,r){let i=e[1];if(!i)return b5(`control-out: handle required`);let a=g5(t);return a.length>4194304?b5(`control-out payload exceeds 4 MiB limit`):y5(`${(await r.controlOut(i,h5(n),a)).bytesWritten} bytes written\n`)}async function cbe(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return b5(`transfer-in: handle, endpoint and length required`);let s=m5(o,`length`);return s>4194304?b5(`transfer-in length exceeds 4 MiB limit`):x5((await n.transferIn(i,m5(a,`endpoint`),s)).bytes,r)}async function lbe(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return b5(`transfer-out: handle and endpoint required`);let o=g5(t);return o.length>4194304?b5(`transfer-out payload exceeds 4 MiB limit`):y5(`${(await r.transferOut(i,m5(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function ube(e,t,n){let{positionals:r,flags:i,bools:a}=Jye(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return ebe(n);case`request`:return tbe(i,n);case`open`:case`close`:case`reset`:return nbe(o,r,n,a);case`clear-halt`:return rbe(r,n);case`select-config`:return ibe(r,n);case`claim`:case`release`:return abe(o,r,n,a);case`control-in`:return obe(r,i,n,s);case`control-out`:return sbe(r,t,i,n);case`transfer-in`:return cbe(r,i,n,s);case`transfer-out`:return lbe(r,t,i,n);default:return b5(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function dbe(){return V(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return y5($ye);let n=eq(d(),u());if(!n)return b5(`WebUSB is unavailable in this environment`);try{return await ube(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?b5(`user cancelled or no device selected`):b5(t)}})}const S5=new Map;function C5(e){return S5.get(e)}function fbe(){return[...S5.values()]}function pbe(e){S5.set(e.name,e)}function mbe(e){S5.delete(e)}function w5(e){e.serve&&=(clearInterval(e.serve.timer),null)}function hbe(e){let{emulator:t}=e;t.add_listener(`serial0-output-byte`,t=>{e.serial.buffer+=String.fromCharCode(t),e.serial.buffer.length>262144&&(e.serial.buffer=e.serial.buffer.slice(-262144))}),t.v86?.cpu?.devices?.vga?.graphical_mode&&(e.screen.mode=`graphical`);let n=t.screen_adapter;if(!n)return;let r=n.set_mode;n.set_mode=t=>{e.screen.mode=t?`graphical`:`text`,r?.call(n,t)};let i=n.set_size_graphical;n.set_size_graphical=(t,r,a,o)=>{e.screen.width=t,e.screen.height=r,e.screen.frame=null,i?.call(n,t,r,a,o)};let a=n.update_buffer;n.update_buffer=t=>{let r=t[t.length-1];r&&(e.screen.frame={data:r.image_data.data,width:r.image_data.width,height:r.image_data.height}),a?.call(n,t)}}function T5(e){e.emulator.v86?.cpu?.devices?.vga?.screen_fill_buffer();let t=e.screen.frame;return!t||t.width===0||t.height===0?null:{data:new Uint8ClampedArray(t.data.slice(0,t.width*t.height*4)),width:t.width,height:t.height}}function E5(e){let t=e.emulator.screen_adapter?.get_text_screen?.();return t?t.map(e=>e.replace(/\s+$/u,``)).join(`
|
|
4646
4646
|
`):null}const D5=`/workspace/.v86`,O5=`v86 - run an x86 virtual machine (v86 wasm engine)
|
|
4647
4647
|
|
|
4648
4648
|
Requires: ${Ya} v86@${v3}
|
|
@@ -4696,10 +4696,10 @@ Notes:
|
|
|
4696
4696
|
mkdir -p ${D5}
|
|
4697
4697
|
curl -o ${D5}/seabios.bin https://raw.githubusercontent.com/copy/v86/master/bios/seabios.bin
|
|
4698
4698
|
curl -o ${D5}/vgabios.bin https://raw.githubusercontent.com/copy/v86/master/bios/vgabios.bin
|
|
4699
|
-
or pass -bios / -vgabios with explicit VFS paths.`,A5={"-n":j5,"-name":j5,"--name":j5,"-m":(e,t)=>{let n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?`-m requires a positive MiB value`:n>512?`-m ${n} exceeds the 512 MiB cap`:(e.memoryMib=n,null)},"-vga":(e,t)=>{let n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?`-vga requires a positive MiB value`:n>64?`-vga ${n} exceeds the 64 MiB cap`:(e.vgaMemoryMib=n,null)},"-cdrom":(e,t)=>M5(e,`cdrom`,t),"-hda":(e,t)=>M5(e,`hda`,t),"-fda":(e,t)=>M5(e,`fda`,t),"-kernel":(e,t)=>M5(e,`kernel`,t),"-initrd":(e,t)=>M5(e,`initrd`,t),"-append":(e,t)=>M5(e,`append`,t),"-bios":(e,t)=>M5(e,`bios`,t),"-vgabios":(e,t)=>M5(e,`vgabios`,t),"-state":(e,t)=>M5(e,`state`,t),"-fs9p":(e,t)=>/^https?:\/\//u.test(t)?(e.fs9p=t,null):`-fs9p requires an http(s) base URL`,"-net":(e,t)=>{let[n,...r]=t.split(`,`);if(n!==`ne2k`&&n!==`virtio`)return`-net requires ne2k or virtio`;for(let t of r){if(t!==`relay=fetch`)return`-net: unknown option '${t}' (only relay=fetch)`;e.netRelay=`fetch`}return e.net=n,null},"-boot":(e,t)=>t!==`a`&&t!==`c`&&t!==`d`?`-boot requires a, c, or d`:(e.boot=t,null)};function j5(e,t){return/^[A-Za-z0-9_-]+$/.test(t)?(e.name=t,null):`invalid VM name '${t}'`}function M5(e,t,n){return e[t]=n,null}const
|
|
4699
|
+
or pass -bios / -vgabios with explicit VFS paths.`,A5={"-n":j5,"-name":j5,"--name":j5,"-m":(e,t)=>{let n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?`-m requires a positive MiB value`:n>512?`-m ${n} exceeds the 512 MiB cap`:(e.memoryMib=n,null)},"-vga":(e,t)=>{let n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0?`-vga requires a positive MiB value`:n>64?`-vga ${n} exceeds the 64 MiB cap`:(e.vgaMemoryMib=n,null)},"-cdrom":(e,t)=>M5(e,`cdrom`,t),"-hda":(e,t)=>M5(e,`hda`,t),"-fda":(e,t)=>M5(e,`fda`,t),"-kernel":(e,t)=>M5(e,`kernel`,t),"-initrd":(e,t)=>M5(e,`initrd`,t),"-append":(e,t)=>M5(e,`append`,t),"-bios":(e,t)=>M5(e,`bios`,t),"-vgabios":(e,t)=>M5(e,`vgabios`,t),"-state":(e,t)=>M5(e,`state`,t),"-fs9p":(e,t)=>/^https?:\/\//u.test(t)?(e.fs9p=t,null):`-fs9p requires an http(s) base URL`,"-net":(e,t)=>{let[n,...r]=t.split(`,`);if(n!==`ne2k`&&n!==`virtio`)return`-net requires ne2k or virtio`;for(let t of r){if(t!==`relay=fetch`)return`-net: unknown option '${t}' (only relay=fetch)`;e.netRelay=`fetch`}return e.net=n,null},"-boot":(e,t)=>t!==`a`&&t!==`c`&&t!==`d`?`-boot requires a, c, or d`:(e.boot=t,null)};function j5(e,t){return/^[A-Za-z0-9_-]+$/.test(t)?(e.name=t,null):`invalid VM name '${t}'`}function M5(e,t,n){return e[t]=n,null}const gbe=[...Object.keys(A5),`--fps`,`--tail`,`--send`,`--to`];function _be(e){let t={name:`vm0`,memoryMib:128,vgaMemoryMib:8,nographic:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r===`-nographic`){t.nographic=!0;continue}let i=Object.hasOwn(A5,r)?A5[r]:void 0;if(!i)return{ok:!1,error:`unknown option '${r}'`};let a=n+1<e.length?e[n+1]:null;if(a===null)return{ok:!1,error:`${r} requires a value`};let o=i(t,a);if(o)return{ok:!1,error:o};n++}return!t.cdrom&&!t.hda&&!t.fda&&!t.kernel&&!t.state?{ok:!1,error:`no bootable media (-cdrom, -hda, -fda, -kernel, or -state required)`}:{ok:!0,parsed:t}}const N5={enter:[28],tab:[15],esc:[1],escape:[1],space:[57],backspace:[14],delete:[224,83],up:[224,72],down:[224,80],left:[224,75],right:[224,77],home:[224,71],end:[224,79],pageup:[224,73],pagedown:[224,81],insert:[224,82],f1:[59],f2:[60],f3:[61],f4:[62],f5:[63],f6:[64],f7:[65],f8:[66],f9:[67],f10:[68],f11:[87],f12:[88]},P5={ctrl:[29],alt:[56],shift:[42]};function vbe(e){let t=`1234567890`.indexOf(e);if(t!==-1)return[t===9?11:2+t];let n=[16,17,18,19,20,21,22,23,24,25,30,31,32,33,34,35,36,37,38,44,45,46,47,48,49,50],r=`qwertyuiopasdfghjklzxcvbnm`.indexOf(e.toLowerCase());return r===-1?null:[n[r]]}function ybe(e){let t=e.toLowerCase().split(/[-+]/u).filter(Boolean);if(t.length===0)return null;let n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(e!==t.length-1&&P5[i]){n.push(P5[i]);continue}let a=N5[i]??(i===`del`?N5.delete:void 0)??P5[i]??(i.length===1?vbe(i):null);if(!a)return null;r.push(a)}if(r.length===0)return null;let i=e=>e,a=e=>e.length===2?[e[0],e[1]|128]:[e[0]|128],o=[];for(let e of n)o.push(...i(e));for(let e of r)o.push(...i(e),...a(e));for(let e of[...n].reverse())o.push(...a(e));return o}function F5(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}function I5(e){return{stdout:``,stderr:`v86: ${e}\n`,exitCode:1}}function L5(e=``){return{stdout:e,stderr:``,exitCode:0}}function R5(e){let t=[],n=`vm0`;for(let r=0;r<e.length;r++){if(e[r]===`-n`||e[r]===`-name`||e[r]===`--name`){let t=e[r+1];if(t){n=t,r++;continue}}t.push(e[r])}return{name:n,rest:t}}function z5(e){return C5(e)||I5(`no VM named '${e}' — boot one with \`v86 start -n ${e} ...\``)}function B5(e){return`exitCode`in e}async function V5(e){if(typeof OffscreenCanvas>`u`)throw Error(`screenshot requires OffscreenCanvas, unavailable in this runtime`);let t=new OffscreenCanvas(e.width,e.height),n=t.getContext(`2d`);if(!n)throw Error(`could not acquire 2d canvas context`);let r=e.data;n.putImageData(new ImageData(r,e.width,e.height),0,0);let i=await t.convertToBlob({type:`image/png`});return new Uint8Array(await i.arrayBuffer())}async function H5(e,t,n){let r=e.fs.resolvePath(e.cwd,t);if(!await e.fs.exists(r))return I5(`${n}: no such file: ${t}`);let i=await e.fs.readFileBuffer(r),a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),{buffer:a}}const bbe={a:801,c:306,d:531};function U5(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.signal==`function`?e:null}function xbe(e={}){return V(`v86`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`||t[0]===`help`)return L5(O5);if(t[0]===`--version`)return Sbe(n,e);let r=t[0];if(oi(t.slice(1),{valueFlags:gbe}))return L5(ai(`v86`,r,O5,{prefix:`v86`}));let i=ii(t.slice(1));try{switch(r){case`start`:return await Dbe(i,n,e);case`ls`:return Obe();case`type`:return kbe(i);case`key`:return Abe(i);case`mouse`:return Mbe(i);case`screenshot`:return await Nbe(i,n);case`text`:return Pbe(i);case`serve`:return await Ibe(i,n);case`serial`:return Lbe(i);case`state`:return await Rbe(i,n);case`stop`:return await zbe(i,e);default:return I5(`unknown subcommand '${r}' — see \`v86 --help\``)}}catch(e){return I5(e instanceof Error?e.message:String(e))}})}async function Sbe(e,t){if(t.loadEngine)return L5(`v86 ${(await t.loadEngine(F5(e))).version} (qemu-flavored CLI)\n`);let n=await x3(F5(e));return n?L5(`v86 ${n.version} (qemu-flavored CLI)\n`):I5(y3)}async function Cbe(e,t,n){if(e.state&&!e.bios&&!e.vgabios)return null;let r=await H5(t,e.bios??`${D5}/seabios.bin`,`-bios`);if(`exitCode`in r)return e.bios?r:I5(k5.replace(/^v86: /u,``));if(n.bios=r,e.nographic)return null;let i=await H5(t,e.vgabios??`${D5}/vgabios.bin`,`-vgabios`);return`exitCode`in i?e.vgabios?i:I5(k5.replace(/^v86: /u,``)):(n.vga_bios=i,null)}async function wbe(e,t,n){let r=await Cbe(e,t,n);if(r)return r;for(let[r,i]of[[`cdrom`,`cdrom`],[`hda`,`hda`],[`fda`,`fda`],[`kernel`,`bzimage`],[`initrd`,`initrd`]]){let a=e[r];if(!a)continue;let o=await H5(t,a,`-${r}`);if(`exitCode`in o)return o;n[i]=o}if(e.append&&(n.cmdline=e.append),e.boot&&(n.boot_order=bbe[e.boot]),e.state){let r=await H5(t,e.state,`-state`);if(`exitCode`in r)return r;n.initial_state=r}return e.fs9p&&(n.filesystem={baseurl:e.fs9p}),e.net&&(n.net_device=e.netRelay===`fetch`?{type:e.net,relay_url:`fetch`}:{type:e.net}),null}const W5=6e4;function Tbe(e){return e.v86?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>n(Error(`engine init timed out after ${W5/1e3}s`)),W5);e.add_listener(`emulator-loaded`,()=>{clearTimeout(r),t()})})}function Ebe(e,t){let n=e.network_adapter;if(!n||typeof n.fetch!=`function`)return I5(`relay=fetch: engine exposed no fetch-relay network adapter`);let r=t.proxiedFetch??ge();return n.fetch=async(e,t)=>{let n=e.replace(/^http:\/\/(?!localhost[:/]|127\.0\.0\.1[:/])/u,`https://`),i={};t?.headers?.forEach((e,t)=>{i[t]=e});let a;if(t?.body){let e=``;for(let n of t.body)e+=String.fromCharCode(n);a=e}let o=await r(n,{method:t?.method,headers:i,body:a}),s=o.body,c=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);return{status:o.status,statusText:o.statusText,headers:new Headers(o.headers),redirected:!1,url:o.url,arrayBuffer:async()=>c}},null}async function Dbe(e,t,n){let r=_be(e);if(!r.ok)return I5(r.error);let i=r.parsed;if(C5(i.name))return I5(`VM '${i.name}' already running — stop it first or pick another -n name`);let a=F5(t),o=n.loadEngine?await n.loadEngine(a):await Efe({ipk:a}),s={wasm_fn:Afe(o.wasmModule),memory_size:i.memoryMib*1024*1024,vga_memory_size:i.vgaMemoryMib*1024*1024,autostart:!1,disable_speaker:!0,fastboot:!0},c=await wbe(i,t,s);if(c)return c;let l=new o.V86(s),u={name:i.name,emulator:l,engineVersion:o.version,pid:null,startedAt:Date.now(),bootArgv:[`v86`,`start`,...e],serial:{buffer:``},screen:{mode:`text`,width:0,height:0,frame:null},serve:null},d=n.processManager??U5();if(d){let e=d.spawn({kind:`net`,argv:u.bootArgv,cwd:t.cwd,owner:{kind:`system`}});u.pid=e.pid,e.abort.signal.addEventListener(`abort`,()=>{G5(u,d)})}pbe(u);try{if(await Tbe(l),i.netRelay===`fetch`){let e=Ebe(l,n);if(e)return await G5(u,d),e}hbe(u),await l.run()}catch(e){return await G5(u,d),I5(`boot failed: ${e instanceof Error?e.message:String(e)}`)}let f=u.pid===null?``:` (pid ${u.pid})`;return L5(`VM '${i.name}' booting in the background${f}.\nDrive it with: v86 text -n ${i.name} | v86 screenshot -n ${i.name} | v86 type -n ${i.name} "..."\n`)}async function G5(e,t){w5(e),mbe(e.name);try{e.emulator.is_running()&&await e.emulator.stop()}catch{}try{await e.emulator.destroy()}catch{}t&&e.pid!==null&&t.exit(e.pid,null)}function Obe(){let e=fbe();if(e.length===0)return L5(`no VMs running
|
|
4700
4700
|
`);let t=[`NAME PID STATE UP BOOT`];for(let n of e){let e=Math.round((Date.now()-n.startedAt)/1e3),r=e>=60?`${Math.floor(e/60)}m${e%60}s`:`${e}s`;t.push(`${n.name.padEnd(10)} ${String(n.pid??`-`).padEnd(6)} ${(n.emulator.is_running()?`running`:`stopped`).padEnd(9)} ${r.padEnd(9)} `+n.bootArgv.slice(2).join(` `))}return L5(`${t.join(`
|
|
4701
|
-
`)}\n`)}function
|
|
4702
|
-
`).replace(/\\t/gu,` `);return r.emulator.keyboard_send_text(i),L5()}function
|
|
4701
|
+
`)}\n`)}function kbe(e){let{name:t,rest:n}=R5(e),r=z5(t);if(B5(r))return r;if(n.length===0)return I5(`type: no text supplied`);let i=n.join(` `).replace(/\\n/gu,`
|
|
4702
|
+
`).replace(/\\t/gu,` `);return r.emulator.keyboard_send_text(i),L5()}function Abe(e){let{name:t,rest:n}=R5(e),r=z5(t);if(B5(r))return r;if(n.length===0)return I5(`key: no chord supplied`);let i=[];for(let e of n){let t=ybe(e);if(!t)return I5(`key: unknown chord '${e}'`);i.push(t)}for(let e of i)r.emulator.keyboard_send_scancodes(e);return L5()}const jbe=[`left`,`middle`,`right`];function K5(e,t){let n=[t===`left`,t===`middle`,t===`right`];e.emulator.bus.send(`mouse-click`,n),e.emulator.bus.send(`mouse-click`,[!1,!1,!1])}function Mbe(e){let{name:t,rest:n}=R5(e),r=z5(t);if(B5(r))return r;let i=n.indexOf(`--to`);if(i!==-1){let e=n[i+1],t=e?/^(\d+),(\d+)$/u.exec(e):null;if(!t)return I5(`mouse: --to requires <x>,<y>`);let[a,o]=[Number(t[1]),Number(t[2])];return r.emulator.bus.send(`mouse-delta`,[-16384,16384]),r.emulator.bus.send(`mouse-delta`,[a,-o]),L5()}let a=n[0];if(a===`move`){let e=Number.parseInt(n[1]??``,10),t=Number.parseInt(n[2]??``,10);return!Number.isFinite(e)||!Number.isFinite(t)?I5(`mouse: move requires <dx> <dy>`):(r.emulator.bus.send(`mouse-delta`,[e,-t]),L5())}if(a===`click`){let e=n[1]??`left`;return jbe.includes(e)?(K5(r,e),n.includes(`--double`)&&K5(r,e),L5()):I5(`mouse: unknown button '${n[1]}'`)}return I5(`mouse: expected move <dx> <dy>, click [button], or --to <x>,<y>`)}async function Nbe(e,t){let{name:n,rest:r}=R5(e),i=z5(n);if(B5(i))return i;let a=T5(i);if(!a)return I5(`no graphical frame for '${n}' — the guest is in text mode; use \`v86 text -n ${n}\``);let o=t.fs.resolvePath(t.cwd,r[0]??`${eo(t.env)}/v86-${n}.png`),s=await V5(a);return await t.fs.writeFile(o,s),L5(`${o} (${a.width}x${a.height})\n`)}function Pbe(e){let{name:t}=R5(e),n=z5(t);if(B5(n))return n;let r=E5(n);return r===null?I5(n.screen.mode===`graphical`?`'${t}' is in graphical mode — use \`v86 screenshot -n ${t}\``:`text screen unavailable for '${t}'`):L5(`${r}\n`)}function Fbe(e,t){return`<!DOCTYPE html>
|
|
4703
4703
|
<html lang="en"><head><meta charset="utf-8"><title>v86 — ${e}</title><style>
|
|
4704
4704
|
html,body{margin:0;height:100%;background:#111;color:#ddd;font-family:monospace}
|
|
4705
4705
|
body{display:flex;align-items:center;justify-content:center}
|
|
@@ -4731,10 +4731,10 @@ async function tick() {
|
|
|
4731
4731
|
}
|
|
4732
4732
|
tick();
|
|
4733
4733
|
<\/script></body></html>
|
|
4734
|
-
`}async function q5(e,t,n,r){let i=`text`,a=e.screen.mode===`graphical`?T5(e):null;if(a)await t.fs.writeFile(`${n}/frame.png`,await V5(a)),i=`graphical`;else{let r=E5(e);await t.fs.writeFile(`${n}/screen.txt`,r??`(no screen output yet)`)}let o={name:e.name,mode:i,seq:r,ts:Date.now()};await t.fs.writeFile(`${n}/state.json`,JSON.stringify(o))}async function
|
|
4734
|
+
`}async function q5(e,t,n,r){let i=`text`,a=e.screen.mode===`graphical`?T5(e):null;if(a)await t.fs.writeFile(`${n}/frame.png`,await V5(a)),i=`graphical`;else{let r=E5(e);await t.fs.writeFile(`${n}/screen.txt`,r??`(no screen output yet)`)}let o={name:e.name,mode:i,seq:r,ts:Date.now()};await t.fs.writeFile(`${n}/state.json`,JSON.stringify(o))}async function Ibe(e,t){let{name:n,rest:r}=R5(e),i=z5(n);if(B5(i))return i;if(r.includes(`--stop`)){if(!i.serve)return I5(`serve: no screen serve running for '${n}'`);let e=i.serve.dir;return w5(i),L5(`screen serve for '${n}' stopped (${e} left in place)\n`)}if(i.serve)return I5(`serve: already serving '${n}' at ${i.serve.dir} — --stop first`);let a=2,o=r.indexOf(`--fps`);if(o!==-1&&(a=Number.parseInt(r[o+1]??``,10),!Number.isFinite(a)||a<1||a>10))return I5(`serve: --fps requires 1-10`);let s=`${eo(t.env)}/v86-serve-${n}`;await t.fs.mkdir(s,{recursive:!0}),await t.fs.writeFile(`${s}/index.html`,Fbe(n,a));let c=0,l=!1,u=setInterval(()=>{l||(l=!0,q5(i,t,s,c++).catch(()=>{}).finally(()=>{l=!1}))},Math.round(1e3/a));return i.serve={dir:s,fps:a,timer:u},await q5(i,t,s,c++).catch(()=>{}),L5(`serving '${n}' screen at ${s} (${a} fps).\nMint an iframe-able URL with: serve ${s}\nStop with: v86 serve -n ${n} --stop\n`)}function Lbe(e){let{name:t,rest:n}=R5(e),r=z5(t);if(B5(r))return r;let i=n.indexOf(`--send`);if(i!==-1){let e=n.slice(i+1).join(` `).replace(/\\n/gu,`
|
|
4735
4735
|
`);return e?(r.emulator.serial0_send(e),L5()):I5(`serial: --send requires text`)}let a=n.indexOf(`--tail`);if(a!==-1){let e=Number.parseInt(n[a+1]??`25`,10);return L5(`${r.serial.buffer.split(`
|
|
4736
4736
|
`).slice(-Math.max(1,e)).join(`
|
|
4737
|
-
`)}\n`)}return L5(r.serial.buffer?`${r.serial.buffer}\n`:``)}async function
|
|
4737
|
+
`)}\n`)}return L5(r.serial.buffer?`${r.serial.buffer}\n`:``)}async function Rbe(e,t){let{name:n,rest:r}=R5(e),i=z5(n);if(B5(i))return i;let[a,o]=r;if(a!==`save`&&a!==`load`||!o)return I5(`state: expected save|load <file>`);let s=t.fs.resolvePath(t.cwd,o);if(a===`save`){let e=await i.emulator.save_state();return await t.fs.writeFile(s,new Uint8Array(e)),L5(`${s} (${e.byteLength} bytes)\n`)}if(!await t.fs.exists(s))return I5(`state: no such file: ${o}`);let c=await t.fs.readFileBuffer(s),l=new ArrayBuffer(c.byteLength);return new Uint8Array(l).set(c),await i.emulator.restore_state(l),L5()}async function zbe(e,t){let{name:n,rest:r}=R5(e),i=z5(n);if(B5(i))return i;let a=t.processManager??U5();return r.includes(`--force`)&&a&&i.pid!==null?(a.signal(i.pid,`SIGKILL`),L5(`VM '${n}' killed\n`)):(await G5(i,a),L5(`VM '${n}' stopped\n`))}const J5=[`--name`,`--filter`,`--scoop`],Bbe={state:`inactive`,session:null};function Y5(){return{stdout:`usage: webhook <command> [options]
|
|
4738
4738
|
|
|
4739
4739
|
Commands:
|
|
4740
4740
|
create [--scoop <name>] [--name <name>] [--filter <code>] Create a new webhook endpoint
|
|
@@ -4754,21 +4754,21 @@ Examples:
|
|
|
4754
4754
|
webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
|
|
4755
4755
|
webhook list
|
|
4756
4756
|
webhook delete abc123
|
|
4757
|
-
`,stderr:``,exitCode:0}}function X5(e){return e().session?.webhookUrl??null}function Z5(e,t,n){return t?Pr(t,e):n()?Ir(self.location.href,e):`(URL unavailable — connect a leader tray)`}function Q5(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function
|
|
4757
|
+
`,stderr:``,exitCode:0}}function X5(e){return e().session?.webhookUrl??null}function Z5(e,t,n){return t?Pr(t,e):n()?Ir(self.location.href,e):`(URL unavailable — connect a leader tray)`}function Q5(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function Vbe(e){if(e.length!==1)return{stdout:``,stderr:`webhook rotate: takes no arguments
|
|
4758
4758
|
`,exitCode:1};let t=u();if(!t)return{stdout:``,stderr:`webhook rotate: no leader panel connected
|
|
4759
4759
|
`,exitCode:1};try{return await t.call(`tray-webhook-rotate`,void 0),{stdout:`Rotated webhook delivery secret. Old URLs no longer work; run webhook list for replacement URLs.
|
|
4760
4760
|
`,stderr:``,exitCode:0}}catch{return{stdout:``,stderr:`webhook rotate: rotation failed; reconnect the leader and retry
|
|
4761
|
-
`,exitCode:1}}}async function
|
|
4762
|
-
`,exitCode:1};let s=
|
|
4763
|
-
`,stderr:``,exitCode:0};let{trayUrlBase:a,urlResolutionError:o}=
|
|
4761
|
+
`,exitCode:1}}}async function Hbe(e,t,n){let r=H(e.slice(1),{value:J5});if(`error`in r)return{stdout:``,stderr:`webhook create: ${r.error}\n`,exitCode:1};let i=r.values.get(`--name`)??`default`,a=r.values.get(`--filter`),o=Ho(r.values.get(`--scoop`),n);if(!t.hasLocalNodeServer()&&a)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
|
|
4762
|
+
`,exitCode:1};let s=Gbe(t);if(s)return s;let c=await f1();if(!c)return Q5(`create`);let l=await m1(c,`webhook create`,r.values.get(`--scoop`));if(l)return{stdout:``,stderr:l,exitCode:1};let u=await c.createWebhook(i,o,a),d=Kbe(u.id,t),f=`Created webhook "${u.name}"\nID: ${u.id}\nURL: ${d}\n`;return u.scoop&&(f+=`Scoop: ${u.scoop}\n`),u.filter&&(f+=`Filter: ${u.filter}\n`),{stdout:f,stderr:``,exitCode:0}}async function Ube(e,t){let n=H(e.slice(1),{});if(`error`in n)return{stdout:``,stderr:`webhook list: ${n.error}\n`,exitCode:1};let r=await f1();if(!r)return Q5(`list`);let i=await r.listWebhooks();if(i.length===0)return{stdout:`No active webhooks
|
|
4763
|
+
`,stderr:``,exitCode:0};let{trayUrlBase:a,urlResolutionError:o}=qbe(t);return{stdout:Jbe(i.map(e=>({id:e.id,name:e.name,url:Z5(e.id,a,t.hasLocalNodeServer),createdAt:e.createdAt,filter:e.filter,scoop:e.scoop})),a,o,t.hasLocalNodeServer),stderr:``,exitCode:0}}async function Wbe(e,t){let n=H(e.slice(1),{});if(`error`in n)return{stdout:``,stderr:`webhook delete: ${n.error}\n`,exitCode:1};let r=n.positionals[0];if(n.positionals.length>1)return{stdout:``,stderr:`webhook delete: requires exactly one ID
|
|
4764
4764
|
`,exitCode:1};if(!r)return{stdout:``,stderr:`webhook delete: requires an ID
|
|
4765
4765
|
`,exitCode:1};let i=await f1();if(!i)return Q5(`delete`);let a=u();try{if(a){if((await a.call(`tray-webhook-revoke`,{webhookId:r}))?.ok!==!0)throw Error(`revocation not acknowledged`)}else if(t.getLeaderStatus().session?.webhookUrl?.includes(`/wh/`))throw Error(`no leader panel`)}catch{return{stdout:``,stderr:`webhook delete: revocation failed; registration retained, reconnect the leader and retry
|
|
4766
|
-
`,exitCode:1}}return await i.deleteWebhook(r)?{stdout:`Deleted webhook "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${r}" not found\n`,exitCode:1}}function
|
|
4767
|
-
`,exitCode:1}}return null}function
|
|
4766
|
+
`,exitCode:1}}return await i.deleteWebhook(r)?{stdout:`Deleted webhook "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${r}" not found\n`,exitCode:1}}function Gbe(e){if(e.hasLocalNodeServer())return null;if(!X5(e.getLeaderStatus)){let t=e.getLeaderStatus().state;return{stdout:``,stderr:(t===`leader`?`webhook create: tray session is not connected yet — wait for the leader to attach`:`webhook create: requires extension-leader mode with a tray worker URL configured (current state: "${t}")`)+`
|
|
4767
|
+
`,exitCode:1}}return null}function Kbe(e,t){try{return Z5(e,X5(t.getLeaderStatus),t.hasLocalNodeServer)}catch(e){return`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}}function qbe(e){try{return{trayUrlBase:X5(e.getLeaderStatus),urlResolutionError:null}}catch(e){return{trayUrlBase:null,urlResolutionError:e instanceof Error?e.message:String(e)}}}function Jbe(e,t,n,r){let i=`Active webhooks:
|
|
4768
4768
|
`;for(let t of e)i+=` ${t.id} ${t.name.padEnd(20)} ${t.url}`,t.scoop&&(i+=` -> ${t.scoop}`),t.filter&&(i+=` [filtered]`),i+=`
|
|
4769
4769
|
`;return n?i+=`\nNote: webhook URL resolution failed (${n}). Try again once the tray is connected.\n`:!r()&&!t&&(i+=`
|
|
4770
4770
|
Note: webhook URLs require a leader tray. Configure one in Settings to expose POST endpoints.
|
|
4771
|
-
`),i}function
|
|
4771
|
+
`),i}function Ybe(e={}){let t={hasLocalNodeServer:e.hasLocalNodeServer??(()=>!0),getLeaderStatus:e.getLeaderStatus??(()=>Bbe)};return V(`webhook`,async(e,n)=>{if(e.length===0)return Y5();let r=e[0];if(oi(e,{valueFlags:r===`create`?J5:void 0}))return Y5();try{switch(r){case`create`:return await Hbe(e,t,n.env);case`list`:return await Ube(e,t);case`delete`:return await Wbe(e,t);case`rotate`:return await Vbe(e);default:return{stdout:``,stderr:`webhook: unknown command "${r}"\n`,exitCode:1}}}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`webhook ${r??`?`}: ${t}\n`,exitCode:1}}})}function Xbe(){return{text:!0,binary:!1,oneMessage:!1,noClose:!1,exitOnEof:!1,unidirectional:!1,unidirectionalReverse:!1,insecure:!1,quiet:!1,verbose:0,nullTerminated:!1,base64:!1,jsonrpc:!1,jsonrpcOmit:!1,bufferSize:65536,connTimeoutMs:3e4,customHeaders:[],showHelp:!1}}function Zbe(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
|
|
4772
4772
|
|
|
4773
4773
|
Minimal websocat client. Sends stdin lines as WebSocket messages and prints
|
|
4774
4774
|
received messages to stdout. Server mode and advanced specifiers (exec:, tcp:,
|
|
@@ -4810,14 +4810,14 @@ EXAMPLES:
|
|
|
4810
4810
|
echo 'Page.navigate {"url":"https://example.com"}' \\
|
|
4811
4811
|
| websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc \\
|
|
4812
4812
|
ws://127.0.0.1:9222/devtools/page/<id>
|
|
4813
|
-
`,stderr:``,exitCode:0}}const $5=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function e7(e,t,n,r){let i=e[t].indexOf(`=`);if(i!==-1&&e[t].startsWith(n))return{value:e[t].slice(i+1),next:t};let a=e[t+1];return a===void 0?(r.error=`websocat: missing value for ${n}\n`,null):{value:a,next:t+1}}function
|
|
4814
|
-
`)}function
|
|
4815
|
-
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function
|
|
4813
|
+
`,stderr:``,exitCode:0}}const $5=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function e7(e,t,n,r){let i=e[t].indexOf(`=`);if(i!==-1&&e[t].startsWith(n))return{value:e[t].slice(i+1),next:t};let a=e[t+1];return a===void 0?(r.error=`websocat: missing value for ${n}\n`,null):{value:a,next:t+1}}function Qbe(e,t,n,r=`positive integer`){let i=Number(t);return!Number.isFinite(i)||i<=0?(e.error=`websocat: ${n} expects ${r}\n`,null):i}function $be(e,t){let n=Number(t);return!Number.isFinite(n)||n<1e3||n>4999?(e.error=`websocat: --close-status-code expects 1000..4999, got '${t}'\n`,null):n}function exe(e,t){let n={"-t":()=>{e.text=!0,e.binary=!1},"--text":()=>{e.text=!0,e.binary=!1},"-b":()=>{e.binary=!0,e.text=!1},"--binary":()=>{e.binary=!0,e.text=!1},"-1n":()=>{e.oneMessage=!0,e.noClose=!0},"-n1":()=>{e.oneMessage=!0,e.noClose=!0},"-1":()=>{e.oneMessage=!0},"--one-message":()=>{e.oneMessage=!0},"-n":()=>{e.noClose=!0},"--no-close":()=>{e.noClose=!0},"-E":()=>{e.exitOnEof=!0},"--exit-on-eof":()=>{e.exitOnEof=!0},"-u":()=>{e.unidirectional=!0},"--unidirectional":()=>{e.unidirectional=!0},"-U":()=>{e.unidirectionalReverse=!0},"--unidirectional-reverse":()=>{e.unidirectionalReverse=!0},"-k":()=>{e.insecure=!0},"--insecure":()=>{e.insecure=!0},"-q":()=>{e.quiet=!0},"-0":()=>{e.nullTerminated=!0},"--null-terminated":()=>{e.nullTerminated=!0},"--base64":()=>{e.base64=!0},"--jsonrpc":()=>{e.jsonrpc=!0},"--jsonrpc-omit-jsonrpc":()=>{e.jsonrpcOmit=!0,e.jsonrpc=!0}}[t];return n?(n(),!0):!1}function txe(e,t){return t===`-v`?(e.verbose+=1,!0):t===`-vv`&&(e.verbose+=2,!0)}function t7(e,t,n,r,i){let a=e7(t,n,r,e);return a?(i(a.value),{nextIndex:a.next}):{stop:!0}}function n7(e,t,n,r,i,a,o){let s=e7(t,n,r,e);if(!s)return{stop:!0};let c=Qbe(e,s.value,i,o);return c===null?{stop:!0}:(a(c),{nextIndex:s.next})}function r7(e,t){return t.some(t=>e===t||e.startsWith(`${t}=`))}const nxe=[(e,t,n,r)=>{if(!r7(r,[`--close-status-code`]))return null;let i=e7(t,n,`--close-status-code`,e);if(!i)return{stop:!0};let a=$be(e,i.value);return a===null?{stop:!0}:(e.closeStatus=a,{nextIndex:i.next})},(e,t,n,r)=>r7(r,[`--close-reason`])?t7(e,t,n,`--close-reason`,t=>{e.closeReason=t}):null,(e,t,n,r)=>r7(r,[`-B`,`--buffer-size`])?n7(e,t,n,r===`-B`?`-B`:`--buffer-size`,`--buffer-size`,t=>{e.bufferSize=t}):null,(e,t,n,r)=>r7(r,[`--max-messages`])?n7(e,t,n,`--max-messages`,`--max-messages`,t=>{e.maxMessages=t}):null,(e,t,n,r)=>r7(r,[`--protocol`])?t7(e,t,n,`--protocol`,t=>{e.protocol=t}):null,(e,t,n,r)=>{if(!r7(r,[`--ping-interval`]))return null;let i=e7(t,n,`--ping-interval`,e);return i?(e.pingInterval=Number(i.value),{nextIndex:i.next}):{stop:!0}},(e,t,n,r)=>r7(r,[`--conn-timeout`])?n7(e,t,n,`--conn-timeout`,`--conn-timeout`,t=>{e.connTimeoutMs=Math.round(t*1e3)},`positive seconds`):null,(e,t,n,r)=>r7(r,[`-H`,`--header`])?t7(e,t,n,r===`-H`?`-H`:`--header`,t=>{e.customHeaders.push(t)}):null];function rxe(e,t,n,r){for(let i of nxe){let a=i(e,t,n,r);if(a)return a}return null}function ixe(e){e.closeReason!==void 0&&e.closeStatus===void 0&&(e.error=`websocat: --close-reason requires --close-status-code (the WebSocket close frame cannot carry a reason without a status code)
|
|
4814
|
+
`)}function axe(e){let t=Xbe();for(let n=0;n<e.length;n+=1){let r=e[n];if(r===`-h`||r===`--help`)return t.showHelp=!0,t;if($5.has(r)||$5.has(r.split(`=`)[0]))return t.error=`websocat: flag '${r}' is not supported in slicc's minimal client\n`,t;if(exe(t,r)||txe(t,r))continue;let i=rxe(t,e,n,r);if(i){if(`stop`in i)return t;n=i.nextIndex;continue}if(r.startsWith(`-`))return t.error=`websocat: unknown flag '${r}'\n`,t;if(t.url)return t.error=`websocat: extra positional argument '${r}' — advanced mode is not supported\n`,t;t.url=r}return ixe(t),t}function oxe(e,t){if(!e)return[];let n=t?`\0`:`
|
|
4815
|
+
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function sxe(e,t,n){let r=e.trim();if(!r)return e;let i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1).trim(),s=[];if(o)try{s=JSON.parse(o)}catch{s=[o]}let c={id:t,method:a,params:s};return n||(c.jsonrpc=`2.0`),JSON.stringify(c)}function cxe(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return v(e)}}function lxe(e){if(typeof e==`string`)return{bytes:new TextEncoder().encode(e),isBinary:!1};if(e instanceof ArrayBuffer)return{bytes:new Uint8Array(e),isBinary:!0};if(ArrayBuffer.isView(e)){let t=e;return{bytes:new Uint8Array(t.buffer,t.byteOffset,t.byteLength),isBinary:!0}}return{bytes:new TextEncoder().encode(String(e)),isBinary:!1}}const i7=1e4;function a7(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function uxe(){let e=!1,t=a7();return{...t,settle:n=>{e||(e=!0,t.resolve(n))}}}function o7(e,t){return e.length?e.join(t)+t:``}function s7(e){return e.length?e.join(`
|
|
4816
4816
|
`)+`
|
|
4817
|
-
`:``}function c7(e,t,n){e.quiet||t.push(`websocat: ${n}`)}function
|
|
4818
|
-
`,a=
|
|
4819
|
-
`);if(!/^wss?:\/\//i.test(r.url))return d7(`websocat: URL must start with ws:// or wss://, got '${r.url}'\n`);let i=
|
|
4820
|
-
`,exitCode:1}}function
|
|
4817
|
+
`:``}function c7(e,t,n){e.quiet||t.push(`websocat: ${n}`)}function dxe(e,t){e.verbose<1||(e.customHeaders.length>0&&c7(e,t,`-H/--header is accepted for parity but browsers do not allow setting WebSocket request headers; only --protocol is honored`),e.pingInterval!==void 0&&c7(e,t,`--ping-interval has no effect in browsers (no ping API exposed)`),e.insecure&&c7(e,t,`-k/--insecure has no effect in browsers`))}function fxe(e,t){try{let n=t.protocol?new e(t.url,t.protocol):new e(t.url);return n.binaryType=`arraybuffer`,{ws:n}}catch(e){return{error:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`}}}function pxe(e,t,n,r){if(n.outLines.length<i7){n.outLines.push(r);return}n.droppedForOverflow===0&&c7(e,t,`output buffer reached ${i7} messages; dropping further inbound messages — use -1, --max-messages, or pipe to a file with a different tool for long-running streams`),n.droppedForOverflow+=1}function mxe(e,t,n){let{bytes:r,isBinary:i}=lxe(n);return r.length>e.bufferSize&&(c7(e,t,`inbound message of ${r.length} bytes exceeds --buffer-size ${e.bufferSize}; truncating`),r=r.slice(0,e.bufferSize)),i&&e.base64?v(r):cxe(r)}function hxe(e,t){return e.maxMessages!==void 0&&t>=e.maxMessages||e.oneMessage}function l7(e,t,n){try{n===void 0?e.close(t):e.close(t,n)}catch{}}function u7(e,t){setTimeout(()=>{l7(t,e.closeStatus??1e3,e.closeReason)},0)}function gxe(e,t,n){let r=oxe(n,t.nullTerminated),i=1,a=0,o=t.oneMessage?r.slice(0,1):r;for(let n of o){let r=n;t.jsonrpc&&(r=sxe(n,i,t.jsonrpcOmit),i+=1),t.binary?e.send(new TextEncoder().encode(r).buffer):e.send(r),a+=1}return a}function _xe(e,t,n){!t.oneMessage&&!t.noClose&&(t.exitOnEof||n===0)&&u7(t,e)}async function vxe(e,t,n){let r=[];dxe(e,r);let i=e.nullTerminated?`\0`:`
|
|
4818
|
+
`,a=fxe(n,e);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let{ws:o}=a,s={outLines:[],droppedForOverflow:0,received:0,finishing:!1},c=!1,l=a7(),u=uxe(),d=0,f=!1,p=setTimeout(()=>{f=!0,l7(o,1e3),c||l.reject(Error(`connect timeout`))},e.connTimeoutMs),m=()=>{if(e.noClose){u.settle(d);return}l7(o,e.closeStatus??1e3,e.closeReason)};o.onopen=()=>{clearTimeout(p),c=!0,l.resolve()},o.onmessage=t=>{if(!s.finishing){if(!e.unidirectional){let n=mxe(e,r,t.data);pxe(e,r,s,n)}s.received+=1,hxe(e,s.received)&&(s.finishing=!0,m())}},o.onerror=()=>{f||(c7(e,r,`websocket error`),d=1,c||l.reject(Error(`connect failed`)))},o.onclose=t=>{if(clearTimeout(p),f){u.settle(124);return}e.verbose>=1&&c7(e,r,`closed code=${t.code} reason=${JSON.stringify(t.reason||``)}`),d===0&&t.code!==1e3&&t.code!==1005&&t.code!==1001&&(d=1),c||l.reject(Error(`connect closed (code ${t.code})`)),u.settle(d)};try{await l.promise}catch(e){clearTimeout(p);let t=e instanceof Error?e.message:String(e);return{stdout:o7(s.outLines,i),stderr:s7(r.concat([`websocat: ${t}`])),exitCode:t===`connect timeout`?124:1}}e.unidirectionalReverse?!e.noClose&&e.exitOnEof&&!e.oneMessage&&u7(e,o):_xe(o,e,gxe(o,e,t));let h=await u.promise;return s.droppedForOverflow>0&&c7(e,r,`dropped ${s.droppedForOverflow} inbound message(s) due to output buffer cap`),{stdout:o7(s.outLines,i),stderr:s7(r),exitCode:h}}function d7(e){return{stdout:``,stderr:e,exitCode:2}}function yxe(e){return e.WebSocketCtor??(typeof WebSocket<`u`?WebSocket:void 0)}async function bxe(e,t,n={}){let r=axe(e);if(r.showHelp)return Zbe();if(r.error)return d7(r.error);if(!r.url)return d7(`websocat: missing ws:// or wss:// URL (use --help for usage)
|
|
4819
|
+
`);if(!/^wss?:\/\//i.test(r.url))return d7(`websocat: URL must start with ws:// or wss://, got '${r.url}'\n`);let i=yxe(n);return i?vxe(r,t.stdin,i):{stdout:``,stderr:`websocat: no WebSocket implementation available in this runtime
|
|
4820
|
+
`,exitCode:1}}function xxe(){return V(`websocat`,async(e,t)=>bxe(e,{stdin:mo(t.stdin)}))}function Sxe(){return V(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function Cxe(e,t){let n=t===void 0?void 0:ya(t);return e.scriptCatalog?e.scriptCatalog.getJshCommands(n):e.fs?Ca(e.fs,n):new Map}async function wxe(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?ba(e.fs):new Map}function Txe(e,t,n,r,i,a){if(r.has(e)){let r=[`/usr/bin/${e}`];return(t||n)&&r.push(` (shadowed by built-in ${e})`),{lines:r,found:!0}}if(t){let e=[t];return n&&e.push(` ${n.path} (workflow, shadowed by .jsh)`),{lines:e,found:!0}}return n?{lines:[`${n.path} (workflow)`],found:!0}:i.has(e)&&!a.has(e)?{lines:[`/usr/bin/${e}`],found:!0}:{lines:[],found:!1}}function Exe(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return V(`which`,async(e,n)=>{if(oi(e))return{stdout:`which - locate a command
|
|
4821
4821
|
|
|
4822
4822
|
Usage: which <command> [command...]
|
|
4823
4823
|
|
|
@@ -4827,9 +4827,9 @@ Prints the path of the given command(s).
|
|
|
4827
4827
|
|
|
4828
4828
|
Exit code 0 if all commands found, 1 if any not found.
|
|
4829
4829
|
`,stderr:``,exitCode:0};let r=H(e,{});if(`error`in r)return{stdout:``,stderr:`which: ${r.error}\n`,exitCode:1};if(r.positionals.length===0)return{stdout:``,stderr:`which: missing argument
|
|
4830
|
-
`,exitCode:1};let i=n.getRegisteredCommands?.()??[],a=new Set(i),o=await
|
|
4830
|
+
`,exitCode:1};let i=n.getRegisteredCommands?.()??[],a=new Set(i),o=await Cxe(t,n.env.get(`PATH`)),s=await wxe(t),c=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):a,l=new Set(t.getScriptRegisteredNames?.()??[]),u=[],d=!0;for(let e of r.positionals){let t=Txe(e,o.get(e),s.get(e),c,a,l);u.push(...t.lines),t.found||(d=!1)}return{stdout:u.length>0?u.join(`
|
|
4831
4831
|
`)+`
|
|
4832
|
-
`:``,stderr:``,exitCode:+!d}})}const f7=`__slicc_workflows`,
|
|
4832
|
+
`:``,stderr:``,exitCode:+!d}})}const f7=`__slicc_workflows`,Dxe=String.raw`
|
|
4833
4833
|
class WorkflowError extends Error {}
|
|
4834
4834
|
class WorkflowDeterminismError extends WorkflowError {}
|
|
4835
4835
|
class WorkflowAgentCapError extends WorkflowError {}
|
|
@@ -4942,40 +4942,40 @@ function log(message) {
|
|
|
4942
4942
|
}
|
|
4943
4943
|
const budget = { total: (__WF.budget == null ? null : __WF.budget), spent() { return 0; }, remaining() { return this.total == null ? Infinity : Math.max(0, this.total - this.spent()); } };
|
|
4944
4944
|
function workflow() { throw new WorkflowNestingUnsupportedError('nested workflow() unsupported in SP1'); }
|
|
4945
|
-
`;function p7(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function
|
|
4945
|
+
`;function p7(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function Oxe(e){let t=jxe(e);return t===null?{name:null,description:null}:{name:h7(t,`name`),description:h7(t,`description`)}}function kxe(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function Axe(e){return`const __emit = console.log.bind(console);
|
|
4946
4946
|
const __stringify = JSON.stringify.bind(JSON);
|
|
4947
|
-
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${
|
|
4947
|
+
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${kxe(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function m7(e,t){let n=e.split(`
|
|
4948
4948
|
`);for(let e=n.length-1;e>=0;e--)if(n[e].startsWith(t)){let r=[...n.slice(0,e),...n.slice(e+1)].join(`
|
|
4949
|
-
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function
|
|
4949
|
+
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function jxe(e){let t=/\bmeta\s*=\s*\{/.exec(e);if(!t)return null;let n=t.index+t[0].length-1,r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&--r===0)return e.slice(n+1,t);return null}function h7(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const g7=r(`workflow-command`),_7=`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
|
|
4950
4950
|
workflow run --script '<inline js>' [...]
|
|
4951
4951
|
workflow list
|
|
4952
4952
|
workflow status <runId>
|
|
4953
4953
|
workflow stop <runId>
|
|
4954
4954
|
workflow save <runId> <name> [--force]
|
|
4955
4955
|
Runs a Claude-Code-format dynamic workflow. Default is non-blocking (returns a run id);
|
|
4956
|
-
pass --wait to block and print the full result.`,
|
|
4957
|
-
`,stderr:``,exitCode:0};if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return
|
|
4956
|
+
pass --wait to block and print the full result.`,Mxe=new Set([`list`,`status`,`stop`,`save`]);function v7(){return globalThis[f7]}function Nxe(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function Pxe(e,t,n,r){let i=t[n];switch(i){case`-h`:case`--help`:return{i:n,help:!0};case`--script`:return e.script=t[++n],{i:n};case`--wait`:return e.wait=!0,{i:n};case`--args`:try{e.args=JSON.parse(t[++n]??``),e.hasArgs=!0}catch{return{i:n,error:`workflow: --args must be valid JSON`}}return{i:n};case`--budget`:{let r=Number(t[++n]);return Number.isFinite(r)?(e.budget=r,{i:n}):{i:n,error:`workflow: --budget must be a number`}}case`--concurrency`:{let i=Number(t[++n]);return Number.isFinite(i)?(e.cap=Math.min(r,Math.max(1,Math.trunc(i))),{i:n}):{i:n,error:`workflow: --concurrency must be a number`}}default:return i.startsWith(`-`)?{i:n,error:`workflow: unknown flag '${i}'`}:e.file===void 0?(e.file=i,{i:n}):{i:n,error:`workflow: too many arguments`}}}function Fxe(e){if(e[0]!==`run`)return e.length===0||e.includes(`-h`)||e.includes(`--help`)?{help:!0}:{error:`workflow: unknown subcommand '${e[0]}' (only 'run' in SP1)`};let t=Nxe(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=Pxe(n,e,r,t);if(i.help)return{help:!0};if(i.error)return{error:i.error};r=i.i}return n.script===void 0&&n.file===void 0?{error:`workflow: a <file.js> or --script is required`}:n}function Ixe(e={}){return V(`workflow`,async(t,n)=>{if(Mxe.has(t[0])&&oi(t.slice(1)))return{stdout:_7+`
|
|
4957
|
+
`,stderr:``,exitCode:0};if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return Vxe(t,n);if(t[0]===`save`)return Bxe(t,n,e);let r=Fxe(t);if(r.help)return{stdout:_7+`
|
|
4958
4958
|
`,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:r.error+`
|
|
4959
|
-
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=
|
|
4960
|
-
`,exitCode:1};let s=p7().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p7(),u=
|
|
4961
|
-
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const
|
|
4962
|
-
`,exitCode:1};if(!
|
|
4959
|
+
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=Oxe(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
|
|
4960
|
+
`,exitCode:1};let s=p7().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p7(),u=Axe({prelude:Dxe,config:{...r.hasArgs?{args:r.args}:{},cap:r.cap??8,budget:r.budget??null,cwd:n.cwd,agentCwd:c},body:i,sentinel:l});return r.wait?Lxe(u,a,l,o,n):Rxe({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function Lxe(e,t,n,r,i){let a;try{a=await lJ(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return g7.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return Hxe(r,a,n)}async function Rxe(e){let t=v7();if(!t)return{stdout:``,stderr:`workflow: run manager not available
|
|
4961
|
+
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const zxe=/^[a-z0-9][a-z0-9-]*$/,y7=`/workspace/.workflows`;async function Bxe(e,t,n){let r=!1,i=[];for(let t of e.slice(1))t===`--force`?r=!0:i.push(t);let[a,o,...s]=i;if(!a||!o||s.length>0)return{stdout:``,stderr:`usage: workflow save <runId> <name> [--force]
|
|
4962
|
+
`,exitCode:1};if(!zxe.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=v7()?.getRun(a);if(!c)return{stdout:``,stderr:`workflow: no run '${a}' (only backgrounded runs are saveable; --wait runs are not)\n`,exitCode:1};if(!c.source)return{stdout:``,stderr:`workflow: run '${a}' has no source to save\n`,exitCode:1};let l=`${y7}/${o}.workflow.js`;if(await t.fs.exists(l)){if(!r)return{stdout:``,stderr:`workflow: ${l} already exists (pass --force to overwrite)\n`,exitCode:1}}else if(new Set(t.getRegisteredCommands?.()??[]).has(o))return{stdout:``,stderr:`workflow: '${o}' is already a command — choose another name\n`,exitCode:1};await t.fs.mkdir(y7,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){g7.warn(`workflow save: command re-sync failed; workflow saved, will register on next sync`,{name:o,error:e instanceof Error?e.message:String(e)})}return{stdout:`saved workflow '${o}' → ${l}\nrun it as '${o}' (or 'workflow run ${l}' if a built-in/.jsh shadows the name)\n`,stderr:``,exitCode:0}}async function Vxe(e,t){let n=v7();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
|
|
4963
4963
|
`,exitCode:1};let e=n.listRuns().map(e=>`${e.id} ${e.status.padEnd(7)} ${e.agentsDone}/${e.agentsStarted} ${e.name??``}`);return{stdout:(e.length?e.join(`
|
|
4964
4964
|
`):`(no runs)`)+`
|
|
4965
4965
|
`,stderr:``,exitCode:0}}let r=e[1],i=n?.getRun(r??``);if(!i)return{stdout:``,stderr:`workflow: no run '${r}'\n`,exitCode:1};if(e[0]===`status`)return{stdout:[`run ${i.id} (${i.name??`unnamed`}) status=${i.status}`,`agents ${i.agentsDone}/${i.agentsStarted} phase=${i.currentPhase??`-`}`,i.resultPath?`result: ${i.resultPath}`:``,i.preview?`preview: ${i.preview}`:``,i.error?`error: ${i.error}`:``].filter(Boolean).join(`
|
|
4966
4966
|
`)+`
|
|
4967
|
-
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function
|
|
4967
|
+
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function Hxe(e,t,n){let{result:r,log:i,hadResult:a}=m7(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?Uxe(i)+`
|
|
4968
4968
|
`:``;return t.exitCode!==0||!a?{stdout:o+s,stderr:t.stderr||(a?``:`workflow: script produced no result
|
|
4969
4969
|
`),exitCode:t.exitCode||1}:{stdout:o+s+(typeof r==`string`?r:JSON.stringify(r))+`
|
|
4970
|
-
`,stderr:t.stderr,exitCode:0}}function
|
|
4970
|
+
`,stderr:t.stderr,exitCode:0}}function Uxe(e){return e.split(`
|
|
4971
4971
|
`).map(e=>e.replace(/^WFPHASE/,`▸ `).replace(/^WFLOG/,`· `)).join(`
|
|
4972
|
-
`)}function b7(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function
|
|
4972
|
+
`)}function b7(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function Wxe(e){if(e==null)throw Error(`missing option value`);let t=e.startsWith(`-`),n=t||e.startsWith(`+`)?e.slice(1):e,r;if(/^0x[0-9a-fA-F]+$/.test(n))r=parseInt(n.slice(2),16);else if(/^[0-9]+$/.test(n))r=parseInt(n,10);else throw Error(`invalid number: ${e}`);return t?-r:r}function x7(e,t){let n=e.toString(16).padStart(2,`0`);return t?n.toUpperCase():n}function S7(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}function Gxe(e){return e.replace(/[^0-9a-zA-Z]/g,`_`)}function Kxe(e,t,n,r,i){let a=[];for(let o=0;o<e.length;o+=t){let s=Math.min(o+t,e.length),c=(i+o).toString(16).padStart(8,`0`),l=``;for(let i=0;i<t;i++)n>0&&i>0&&i%n===0&&(l+=` `),l+=o+i<s?x7(e[o+i],r):` `;let u=``;for(let t=o;t<s;t++)u+=e[t]>=32&&e[t]<=126?String.fromCharCode(e[t]):`.`;a.push(`${c}: ${l} ${u}`)}return a.length?a.join(`
|
|
4973
4973
|
`)+`
|
|
4974
|
-
`:``}function
|
|
4975
|
-
`}return r}function
|
|
4974
|
+
`:``}function qxe(e,t,n){let r=``;for(let i=0;i<e.length;i+=t){let a=``;for(let r=0;r<t&&i+r<e.length;r++)a+=x7(e[i+r],n);r+=a+`
|
|
4975
|
+
`}return r}function Jxe(e,t,n,r){let i=Array.from(e,e=>`0x${x7(e,n)}`),a=[];for(let e=0;e<i.length;e+=t)a.push(` `+i.slice(e,e+t).join(`, `));let o=a.join(`,
|
|
4976
4976
|
`);return r===null?i.length?o+`
|
|
4977
|
-
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function
|
|
4978
|
-
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const
|
|
4977
|
+
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function Yxe(e){let t=e.replace(/[^0-9a-fA-F]/g,``),n=Math.floor(t.length/2),r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substr(e*2,2),16);return r}function Xxe(e){let t=[],n=0;for(let r of e.split(`
|
|
4978
|
+
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const Zxe={"-u":`upper`,"-p":`plain`,"-ps":`plain`,"-postscript":`plain`,"-i":`include`,"-include":`include`,"-r":`revert`,"-revert":`revert`},Qxe=[{key:`cols`,exact:[`-c`,`-cols`],attached:/^-c(0x)?[0-9]/},{key:`group`,exact:[`-g`,`-groupsize`],attached:/^-g(0x)?[0-9]/},{key:`length`,exact:[`-l`,`-len`],attached:/^-l(0x)?[0-9]/},{key:`seek`,exact:[`-s`,`-seek`],attached:/^-s[+-]?(0x)?[0-9]/}];function $xe(e){let t={upper:!1,plain:!1,include:!1,revert:!1,positional:[]};for(let n=0;n<e.length;n++){let r=e[n],i=Zxe[r];if(i){t[i]=!0;continue}let a=Qxe.find(e=>e.exact.includes(r)||e.attached.test(r));if(a){t[a.key]=Wxe(a.exact.includes(r)?e[++n]:r.slice(2));continue}if(r!==`-`&&r.startsWith(`-`)&&r.length>1)throw Error(`invalid option ${r}`);t.positional.push(r)}return t}function eSe(e){return e.includes(`-h`)||e.includes(`--help`)||e.includes(`-help`)}async function tSe(e,t,n){if(!n&&t)return e.fs.readFileBuffer(e.fs.resolvePath(e.cwd,t));let r=po(e.stdin),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e)&255;return i}function nSe(e,t,n,r,i){let a=e.cols&&e.cols>0?e.cols:e.plain?30:e.include?12:16;return e.plain?qxe(t,a,e.upper):e.include?Jxe(t,a,e.upper,i?null:Gxe(r??``)):Kxe(t,a,e.group!=null&&e.group>=0?e.group:2,e.upper,n)}function rSe(e,t){let n=0,r=t;return e.seek!==void 0&&(n=e.seek<0?Math.max(0,r.length+e.seek):Math.min(e.seek,r.length),r=r.subarray(n)),e.length!==void 0&&(r=r.subarray(0,Math.max(0,e.length))),{data:r,base:n}}function iSe(){return V(`xxd`,async(e,t)=>{if(eSe(e))return{stdout:`usage: xxd [options] [infile [outfile]]
|
|
4979
4979
|
-c cols number of octets per line (default 16; 30 for -p; 12 for -i)
|
|
4980
4980
|
-g bytes number of octets per group (default 2; 0 disables grouping)
|
|
4981
4981
|
-l len stop after len octets
|
|
@@ -4985,34 +4985,34 @@ pass --wait to block and print the full result.`,jxe=new Set([`list`,`status`,`s
|
|
|
4985
4985
|
-i output in C include style
|
|
4986
4986
|
-r reverse: convert a hex dump back to binary (-r -p for plain)
|
|
4987
4987
|
-h show this help
|
|
4988
|
-
`,stderr:``,exitCode:0};let n;try{n
|
|
4989
|
-
`,stderr:``,exitCode:0}}function
|
|
4988
|
+
`,stderr:``,exitCode:0};let n;try{n=$xe(e)}catch(e){return b7(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await tSe(t,r,a)}catch{return b7(`${r}: No such file or directory`)}if(n.revert){let e=S7(o),r=n.plain?Yxe(e):Xxe(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:S7(r),stderr:``,exitCode:0}}let{data:s,base:c}=rSe(n,o),l=nSe(n,s,c,r,a);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),l),{stdout:``,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}})}async function C7(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=za(t,o),s=n?`${n}/${o}`:o;a+=await C7(e,i,s,r)}return a}function aSe(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
|
|
4989
|
+
`,stderr:``,exitCode:0}}function oSe(){return V(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return aSe();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
|
|
4990
4990
|
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||Ba(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await C7(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
|
|
4991
|
-
`,exitCode:1};let c=Ui(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function oSe(e){return{setEnv:e.setEnv,unsetEnv:e.unsetEnv,broker:e.sudoCommand?.broker}}function sSe(e){let{fs:t,fetch:n}=e;if(!t||!n)return[];let r={fs:t,fetch:n,scriptCatalog:e.scriptCatalog,syncScriptCommands:e.syncScriptCommands};return[_3(`ipk`,r),_3(`npm`,r),_3(`i`,r),R3(`ipx`,{fs:t,fetch:n}),R3(`npx`,{fs:t,fetch:n}),l0(`di`,{fs:t,fetch:n}),l0(`uv`,{fs:t,fetch:n}),Pye({fs:t,fetch:n})]}function cSe(e={}){let t=[lde({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),YQ(),ave(),j_e(),T_e(e.browserAPI,e.fs),the(e.browserAPI),T1(e.browserAPI),Hde(e),aSe(),Sye(),kve(),lve(),gve(),pve(),x$(),rSe(),j8(`sqlite3`),j8(`sqllite`),Hve(),rye(),Jse(),NQ(),v6({buildProcessConfig:e.buildProcessConfig}),v6({buildProcessConfig:e.buildProcessConfig},`jsh`),W6(`python3`,{buildProcessConfig:e.buildProcessConfig}),W6(`python`,{buildProcessConfig:e.buildProcessConfig}),...sSe(e),...e.fs?[Bce({fs:e.fs})]:[],...e.fs?[qpe({fs:e.fs})]:[],...e.fetch?[mde({fetch:e.fetch})]:[],jce(),Mce(),Jbe(e.webhook),bxe(),w1(e.crontask),vpe({fs:e.fs,scriptCatalog:e.scriptCatalog}),hhe({fs:e.fs,fetch:e.fetch}),zce(),q_e(),nhe(),k6(`pdftk`),k6(`pdf`),PQ(`biscotto`),PQ(`biscotti`),j6(`pdftoppm`),j6(`pdftocairo`),dhe(`pdftotext`),c1(`convert`),c1(`magick`),Txe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins,getScriptRegisteredNames:e.getScriptRegisteredNames}),iye(),_ye(),Bde(),Vde(),vye(),Jpe(),hpe(),Z0(),zme(),Rme(),fpe(),t_e(oSe(e)),sge({fs:e.fs}),Oge(),v$(),y$(),b$(`xclip`),b$(`xsel`),yge(),Yce(),aZ(),oZ(),gme(e.fs),Cee(),jme(),EZ({getParentJid:e.getParentJid}),a2(),khe({processManager:e.processManager}),Gye({processManager:e.processManager}),Ufe({processManager:e.processManager}),...kZ(),Kpe(),spe(),ube(),Ade(),Cce(),bbe({processManager:e.processManager}),Ace(),d$({registry:e.cherryRuntimeRegistry}),M1(),z1({fs:e.fs}),B1({fs:e.fs}),sve(e.sudoCommand),Fxe({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),xxe(),A_e()];return e.fs&&(phe(),t.push(...ca.map(t=>ode(t,e.browserAPI,e.fs)))),t}let w7=null;function lSe(e){w7=e}function uSe(e){w7?.(e)}const dSe=Reflect.get(yee,`DefenseInDepthBox`);function fSe(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=String.fromCharCode(e[n]);return t.join(``)}}function T7(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?`vfs-ino:${e}`:void 0}var pSe=class{vfs;registeredCommandsFn=null;listingStats=new Map;listingStatsMax;listingStatsTtlMs;constructor(e,t){this.vfs=e,this.listingStatsMax=Math.max(1,t?.listingStatsMax??2e4),this.listingStatsTtlMs=t?.listingStatsTtlMs??1e3}get listingStatsSize(){return this.listingStats.size}primeListingStats(e,t){let n=Date.now();if(t.length>this.listingStatsMax){this.listingStats.clear();return}this.sweepExpiredListingStats(n),this.listingStats.size+t.length>this.listingStatsMax&&this.listingStats.clear();let r=e===`/`?`/`:`${e}/`;for(let e of t){let t=cr(e),i=`${r}${e.name}`;this.listingStats.delete(i),t&&this.listingStats.set(i,{stats:t,at:n})}}sweepExpiredListingStats(e){for(let[t,n]of this.listingStats){if(e-n.at<=this.listingStatsTtlMs)break;this.listingStats.delete(t)}}primedStats(e){let t=this.listingStats.get(e);if(t){if(Date.now()-t.at>this.listingStatsTtlMs){this.listingStats.delete(e);return}return t.stats}}dropListingStats(){this.listingStats.clear()}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}virtualUsrStat(e){if(e===`/usr`||e===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(e.startsWith(`/usr/bin/`)){let t=e.slice(9);if(t.length>0&&!t.includes(`/`)&&this.getVirtualBinCommands().includes(t))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}return null}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=dSe?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=_n(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n),i=fSe(r);return _e(i,r),i})}async readFileBuffer(e){return this.trusted(async()=>{let t=_n(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async getNativeFile(e){return this.trusted(()=>this.vfs.getNativeFile(_n(e)))}async readFileRange(e,t,n){return this.trusted(()=>this.vfs.readFileRange(_n(e),t,n))}async writeFile(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let n=_n(e);if(typeof t==`string`){let e=xe(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let n=_n(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new lr(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof lr&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=_n(e);return this.virtualUsrStat(t)?!0:this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=_n(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.statSync(t);if(r)return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime),identity:T7(r.ino)};let i=this.primedStats(t)??await this.vfs.stat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!!i.isSymlink,mode:i.type===`directory`?493:420,size:i.size,mtime:new Date(i.mtime),identity:T7(i.ino)}})}async lstat(e){return this.trusted(async()=>{let t=_n(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.lstatSync(t);if(r)return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime),identity:T7(r.ino)};let i=this.primedStats(t)??await this.vfs.lstat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:i.type===`symlink`,mode:i.type===`directory`?493:i.type===`symlink`?511:420,size:i.size,mtime:new Date(i.mtime),identity:T7(i.ino)}})}async mkdir(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.mkdir(_n(e),t)})}async readdir(e){return this.trusted(async()=>{let t=_n(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);if(n!==null)return n.map(e=>e.name);let r=await this.vfs.readDir(t,{includeStats:!0});return this.primeListingStats(t,r),r.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=_n(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t,{includeStats:!0});return this.primeListingStats(t,r),this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.rm(_n(e),t)})}async cp(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let r=_n(e),i=_n(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new lr(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=vn(e,r.name),i=vn(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.rename(_n(e),_n(t))})}resolvePath(e,t){return t.startsWith(`/`)?_n(t):_n(vn(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.symlink(e,_n(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(_n(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(_n(e)))}async utimes(e,t,n){}invalidatePaths(e){this.dropListingStats();let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function E7(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?E7(e.getUnderlyingFS?.()):null}async function mSe(e){let t=_(`github`);if(t){if(e?.force){await t.onSilentRenew?.();return}await t.getValidAccessToken?.()}}const hSe=r(`almost-bash-shell`),D7=`__SLICC_RUN_PID`,O7=`__SLICC_OUTPUT_TEE__`;function k7(e){let t=e?.get(D7);if(t===void 0)return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function gSe(e){if(!(D7 in e)&&!(O7 in e))return{...e};let{[D7]:t,[O7]:n,...r}=e;return r}var A7=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;initialJshSync=null;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;progress;activeRunSignal;scriptRun=null;scriptRunsActive=0;registryNames=new Set;outputTees=new Map;nextOutputTeeId=0;resolveJshProcessConfig=e=>this.buildJshProcessConfig(k7(e));static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}static buildInitialEnv(e,t){return{HOME:EN,PATH:xa,USER:`user`,SHELL:`/bin/bash`,TMPDIR:`/tmp`,PWD:t,...e.env}}buildSupplementalCommands(e,t){return cSe({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],getScriptRegisteredNames:()=>[...this.registeredJshCommands.keys(),...this.registeredWorkflowCommands],fs:e.fs,fetch:t,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,webhook:e.webhook,crontask:e.crontask,getParentJid:e.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:e.processManager,sudoCommand:e.sudo?{broker:e.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t},unsetEnv:e=>{this.pendingEnvWrites.set(e,null),delete this.lastEnv[e]}})}constructor(t){this.options=t,this.vfsAdapter=new pSe(t.fs),this.progress=new hJ({scrubLabel:t.scrubProgressLabel}),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r=e.buildInitialEnv(t,n);this.gitCommands=new TN({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`,ensureFreshGithubToken:mSe}),this.mountCommands=new Nie({fs:t.fs,isScoop:t.isScoop,acquireLocalMountViaToolUI:nY});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=E7(i)??E7(a);this.scriptCatalog=t.scriptCatalog??new wa({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=ge({progress:bJ(this.progress)}),l=this.buildSupplementalCommands(t,c),u=[s,this.createMountCustomCommand(),this.createUmountCustomCommand(),UY(t.fs),BX(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...ni(),...ri()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new bee({fs:this.vfsAdapter,cwd:n,env:{},fetch:c,commands:f,customCommands:u,sleep:VJ(this.progress,{isAborted:()=>this.activeRunSignal?.aborted??!1})}),this.allowedCommands!==null){let e=this.bash;for(let t of ri())this.isCommandAllowed(t)||e.commands.delete(t)}{let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForDispatch(n));this.registryNames=new Set(e.commands.keys())}let p=u.map(e=>e.name),m=f??[...ni(),...ri()];this.builtinCommandNames=new Set([...m,...p]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.startInitialJshSync()}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}setMaskedEnvVar(e,t){this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}applySessionOverrides(e){e.cwd!==void 0&&(this.cwd=e.cwd,this.lastEnv.PWD=e.cwd),e.env&&Object.assign(this.lastEnv,e.env)}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight===null?(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight):(this.jshSyncDirty=!0,this.jshSyncInflight)}async executeCommand(e,t,n,r=``,i){let a=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);let o=i?.onOutput?`tee-${this.nextOutputTeeId+=1}`:void 0;o&&i?.onOutput&&this.outputTees.set(o,i.onOutput);try{let i=await this.runCommand(e,t,n,r,o);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}finally{this.activeShellPid=a,o&&this.outputTees.delete(o)}}async executeScriptFile(e,t=[]){return cJ(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}currentScanRoots(){return ya(this.lastEnv.PATH)}startInitialJshSync(){this.initialJshSync=this.initHomeAndProfile().then(()=>this.syncJshCommands()).catch(()=>void 0).finally(()=>{this.initialJshSync=null})}async initHomeAndProfile(){let e=this.options.fs;try{let t=this.options.env?.HOME??await DN(e);this.lastEnv.HOME=t,this.options.env?.USER||(this.lastEnv.USER=ON(t));let n=`${t.replace(/\/+$/,``)}/.profile`;if(!await e.exists(n).catch(()=>!1))return;let r=await this.bash.exec(`. "$HOME/.profile"`,{env:this.lastEnv,cwd:this.cwd});if(r.env){let{PWD:e,...t}=r.env;this.lastEnv={...t,PWD:this.lastEnv.PWD??this.cwd}}}catch(e){hSe.warn(`HOME/profile init failed; continuing with defaults`,e)}}async waitForInitialJshSync(e){let t=this.initialJshSync;if(t===null)return;if(!e){await t;return}if(e.aborted)return;let n;try{await new Promise(r=>{n=()=>r(),e.addEventListener(`abort`,n,{once:!0}),t.then(()=>r(),()=>r())})}finally{n&&e.removeEventListener(`abort`,n)}}async runCommand(e,t,n,r=``,i){uSe(e.trim().split(/\s+/)[0]||`unknown`),me(),await this.waitForInitialJshSync(t);let a={env:{...this.lastEnv,...n===void 0?{}:{[D7]:String(n)},...i===void 0?{}:{[O7]:i}},cwd:this.cwd,signal:t,...r===``?{}:{stdin:r,stdinKind:`bytes`}},o=this.lastEnv.PATH;this.activeRunSignal=t;let s=this.beginScriptRun(e),c;try{c=await this.bash.exec(e,a)}finally{this.activeRunSignal===t&&(this.activeRunSignal=void 0),this.endScriptRun(s)}if(await this.flushPendingCommandGrants(),c.env&&(this.lastEnv=gSe(c.env)),c.env&&this.lastEnv.PATH!==o&&await this.syncJshCommands().catch(()=>void 0),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)t===null?delete this.lastEnv[e]:this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(c.env?.PWD&&(this.cwd=c.env.PWD),c.exitCode===127){let t=await this.tryJshFallback(e,n);if(t)return this.syncJshCommands().catch(()=>void 0),t}return c}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForDispatch(e){let t=this.wrapCommandForSudo(e),n=e.name===`timeout`?GJ(t,this.progress):qJ(t,this.progress),r=()=>this.scriptRun?.stepDone(),i=(e,t)=>this.teeCommandOutput(e,t);return{...n,async execute(e,t){try{let r=await n.execute(e,t);return i(t.env,r),r}finally{r()}}}}teeCommandOutput(e,t){let n=e?.get(O7);if(!n)return;let r=this.outputTees.get(n);if(!r)return;let i=[t.stdout,t.stderr].filter(Boolean).join(``);i&&r(i)}beginScriptRun(e){if(this.scriptRunsActive+=1,!this.progress.hasSink())return null;if(this.scriptRunsActive>1)return this.scriptRun?.end(),this.scriptRun=null,null;let t={totalSteps:null};try{t=IJ(this.bash.transform(e).ast,this.registryNames)}catch{t={totalSteps:null}}return this.scriptRun=new RJ(t,this.progress,LJ(e)),this.scriptRun}endScriptRun(e){this.scriptRunsActive=Math.max(0,this.scriptRunsActive-1),e&&(e.end(),this.scriptRun===e&&(this.scriptRun=null))}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=YJ(e,t);if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await ZJ(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=di(e);if(!n)return;let r=`${fi}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
4992
|
-
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(this.currentScanRoots()),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForDispatch(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForDispatch(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this.options.jshDiscoveryFs??this.options.fs,r=e,i=async(e,i)=>{let a=i.exec??((e,t)=>this.bash.exec(e,{env:Object.fromEntries(i.env),cwd:t?.cwd??i.cwd,args:t?.args})),o=(await t.getJshCommands(this.currentScanRoots())).get(r);if(o){let t;try{let e=await n.readFile(o,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}return lJ(t,[`node`,o,...e],{fs:i.fs,cwd:i.cwd,env:i.env,stdin:i.stdin,exec:a},this.buildJshProcessConfig(k7(i.env)))}let s=(await t.getWorkflowCommands()).get(r);if(s){let t=Sa(s.path,e);return a(t[0],{args:t.slice(1),cwd:i.cwd})}return{stdout:``,stderr:`${r}: command no longer exists\n`,exitCode:127}};return{name:e,trusted:!0,async execute(e,t){try{return await i(e,t)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${r}: ${t}\n`,exitCode:1}}}}}createGitCustomCommand(){let e=this.gitCommands;return V(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env,mo(n.stdin));return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return V(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createUmountCustomCommand(){let e=this.mountCommands;return V(`umount`,async(t,n)=>{let r=n.cwd,i=await e.executeUmount(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(this.currentScanRoots()),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e,t){let n=e.trim(),r=n.indexOf(` `),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1).trim():``,o=(await this.getFilteredJshCommands()).get(i);if(!o)return null;let s=a?mJ(a):[],c=this.options.jshDiscoveryFs??this.options.fs,l;try{let e=await c.readFile(o,{encoding:`utf-8`});l=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127,env:this.lastEnv}}let u=[`node`,o,...s],d=await lJ(l,u,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig(t));return{stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode,env:this.lastEnv}}buildJshProcessConfig(e){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>e??this.activeShellPid??this.options.getCurrentShellPid?.()}}};function
|
|
4991
|
+
`,exitCode:1};let c=Ui(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function sSe(e){return{setEnv:e.setEnv,unsetEnv:e.unsetEnv,broker:e.sudoCommand?.broker}}function cSe(e){let{fs:t,fetch:n}=e;if(!t||!n)return[];let r={fs:t,fetch:n,scriptCatalog:e.scriptCatalog,syncScriptCommands:e.syncScriptCommands};return[_3(`ipk`,r),_3(`npm`,r),_3(`i`,r),R3(`ipx`,{fs:t,fetch:n}),R3(`npx`,{fs:t,fetch:n}),l0(`di`,{fs:t,fetch:n}),l0(`uv`,{fs:t,fetch:n}),Fye({fs:t,fetch:n})]}function lSe(e={}){let t=[lde({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),YQ(),ove(),M_e(),E_e(e.browserAPI,e.fs),the(e.browserAPI),T1(e.browserAPI),Hde(e),oSe(),Cye(),Ave(),uve(),_ve(),mve(),x$(),iSe(),j8(`sqlite3`),j8(`sqllite`),Uve(),iye(),Jse(),NQ(),v6({buildProcessConfig:e.buildProcessConfig}),v6({buildProcessConfig:e.buildProcessConfig},`jsh`),W6(`python3`,{buildProcessConfig:e.buildProcessConfig}),W6(`python`,{buildProcessConfig:e.buildProcessConfig}),...cSe(e),...e.fs?[Bce({fs:e.fs})]:[],...e.fs?[qpe({fs:e.fs})]:[],...e.fetch?[mde({fetch:e.fetch})]:[],jce(),Mce(),Ybe(e.webhook),xxe(),w1(e.crontask),vpe({fs:e.fs,scriptCatalog:e.scriptCatalog}),hhe({fs:e.fs,fetch:e.fetch}),zce(),J_e(),nhe(),k6(`pdftk`),k6(`pdf`),PQ(`biscotto`),PQ(`biscotti`),j6(`pdftoppm`),j6(`pdftocairo`),dhe(`pdftotext`),c1(`convert`),c1(`magick`),Exe({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins,getScriptRegisteredNames:e.getScriptRegisteredNames}),aye(),vye(),Bde(),Vde(),yye(),Jpe(),tge(),hpe(),Z0(),zme(),Rme(),fpe(),n_e(sSe(e)),cge({fs:e.fs}),kge(),v$(),y$(),b$(`xclip`),b$(`xsel`),bge(),Yce(),aZ(),oZ(),gme(e.fs),Cee(),jme(),EZ({getParentJid:e.getParentJid}),a2(),khe({processManager:e.processManager}),Kye({processManager:e.processManager}),Ufe({processManager:e.processManager}),...kZ(),Kpe(),spe(),dbe(),Ade(),Cce(),xbe({processManager:e.processManager}),Ace(),d$({registry:e.cherryRuntimeRegistry}),M1(),z1({fs:e.fs}),B1({fs:e.fs}),cve(e.sudoCommand),Ixe({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),Sxe(),j_e()];return e.fs&&(phe(),t.push(...ca.map(t=>ode(t,e.browserAPI,e.fs)))),t}let w7=null;function uSe(e){w7=e}function dSe(e){w7?.(e)}const fSe=Reflect.get(yee,`DefenseInDepthBox`);function pSe(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=String.fromCharCode(e[n]);return t.join(``)}}function T7(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?`vfs-ino:${e}`:void 0}var mSe=class{vfs;registeredCommandsFn=null;listingStats=new Map;listingStatsMax;listingStatsTtlMs;constructor(e,t){this.vfs=e,this.listingStatsMax=Math.max(1,t?.listingStatsMax??2e4),this.listingStatsTtlMs=t?.listingStatsTtlMs??1e3}get listingStatsSize(){return this.listingStats.size}primeListingStats(e,t){let n=Date.now();if(t.length>this.listingStatsMax){this.listingStats.clear();return}this.sweepExpiredListingStats(n),this.listingStats.size+t.length>this.listingStatsMax&&this.listingStats.clear();let r=e===`/`?`/`:`${e}/`;for(let e of t){let t=cr(e),i=`${r}${e.name}`;this.listingStats.delete(i),t&&this.listingStats.set(i,{stats:t,at:n})}}sweepExpiredListingStats(e){for(let[t,n]of this.listingStats){if(e-n.at<=this.listingStatsTtlMs)break;this.listingStats.delete(t)}}primedStats(e){let t=this.listingStats.get(e);if(t){if(Date.now()-t.at>this.listingStatsTtlMs){this.listingStats.delete(e);return}return t.stats}}dropListingStats(){this.listingStats.clear()}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}virtualUsrStat(e){if(e===`/usr`||e===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(e.startsWith(`/usr/bin/`)){let t=e.slice(9);if(t.length>0&&!t.includes(`/`)&&this.getVirtualBinCommands().includes(t))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}return null}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=fSe?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=_n(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n),i=pSe(r);return _e(i,r),i})}async readFileBuffer(e){return this.trusted(async()=>{let t=_n(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async getNativeFile(e){return this.trusted(()=>this.vfs.getNativeFile(_n(e)))}async readFileRange(e,t,n){return this.trusted(()=>this.vfs.readFileRange(_n(e),t,n))}async writeFile(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let n=_n(e);if(typeof t==`string`){let e=xe(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let n=_n(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new lr(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof lr&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=_n(e);return this.virtualUsrStat(t)?!0:this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=_n(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.statSync(t);if(r)return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime),identity:T7(r.ino)};let i=this.primedStats(t)??await this.vfs.stat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!!i.isSymlink,mode:i.type===`directory`?493:420,size:i.size,mtime:new Date(i.mtime),identity:T7(i.ino)}})}async lstat(e){return this.trusted(async()=>{let t=_n(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.lstatSync(t);if(r)return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime),identity:T7(r.ino)};let i=this.primedStats(t)??await this.vfs.lstat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:i.type===`symlink`,mode:i.type===`directory`?493:i.type===`symlink`?511:420,size:i.size,mtime:new Date(i.mtime),identity:T7(i.ino)}})}async mkdir(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.mkdir(_n(e),t)})}async readdir(e){return this.trusted(async()=>{let t=_n(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);if(n!==null)return n.map(e=>e.name);let r=await this.vfs.readDir(t,{includeStats:!0});return this.primeListingStats(t,r),r.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=_n(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t,{includeStats:!0});return this.primeListingStats(t,r),this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.rm(_n(e),t)})}async cp(e,t,n){return this.dropListingStats(),this.trusted(async()=>{let r=_n(e),i=_n(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new lr(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=vn(e,r.name),i=vn(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.rename(_n(e),_n(t))})}resolvePath(e,t){return t.startsWith(`/`)?_n(t):_n(vn(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.dropListingStats(),this.trusted(async()=>{await this.vfs.symlink(e,_n(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(_n(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(_n(e)))}async utimes(e,t,n){}invalidatePaths(e){this.dropListingStats();let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function E7(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?E7(e.getUnderlyingFS?.()):null}async function hSe(e){let t=_(`github`);if(t){if(e?.force){await t.onSilentRenew?.();return}await t.getValidAccessToken?.()}}const gSe=r(`almost-bash-shell`),D7=`__SLICC_RUN_PID`,O7=`__SLICC_OUTPUT_TEE__`;function k7(e){let t=e?.get(D7);if(t===void 0)return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function _Se(e){if(!(D7 in e)&&!(O7 in e))return{...e};let{[D7]:t,[O7]:n,...r}=e;return r}var A7=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;initialJshSync=null;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;progress;activeRunSignal;scriptRun=null;scriptRunsActive=0;registryNames=new Set;outputTees=new Map;nextOutputTeeId=0;resolveJshProcessConfig=e=>this.buildJshProcessConfig(k7(e));static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}static buildInitialEnv(e,t){return{HOME:EN,PATH:xa,USER:`user`,SHELL:`/bin/bash`,TMPDIR:`/tmp`,PWD:t,...e.env}}buildSupplementalCommands(e,t){return lSe({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],getScriptRegisteredNames:()=>[...this.registeredJshCommands.keys(),...this.registeredWorkflowCommands],fs:e.fs,fetch:t,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,webhook:e.webhook,crontask:e.crontask,getParentJid:e.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:e.processManager,sudoCommand:e.sudo?{broker:e.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t},unsetEnv:e=>{this.pendingEnvWrites.set(e,null),delete this.lastEnv[e]}})}constructor(t){this.options=t,this.vfsAdapter=new mSe(t.fs),this.progress=new hJ({scrubLabel:t.scrubProgressLabel}),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r=e.buildInitialEnv(t,n);this.gitCommands=new TN({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`,ensureFreshGithubToken:hSe}),this.mountCommands=new Nie({fs:t.fs,isScoop:t.isScoop,acquireLocalMountViaToolUI:nY});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=E7(i)??E7(a);this.scriptCatalog=t.scriptCatalog??new wa({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=ge({progress:bJ(this.progress)}),l=this.buildSupplementalCommands(t,c),u=[s,this.createMountCustomCommand(),this.createUmountCustomCommand(),UY(t.fs),BX(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...ni(),...ri()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new bee({fs:this.vfsAdapter,cwd:n,env:{},fetch:c,commands:f,customCommands:u,sleep:VJ(this.progress,{isAborted:()=>this.activeRunSignal?.aborted??!1}),executionLimits:t.executionLimits}),this.allowedCommands!==null){let e=this.bash;for(let t of ri())this.isCommandAllowed(t)||e.commands.delete(t)}{let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForDispatch(n));this.registryNames=new Set(e.commands.keys())}let p=u.map(e=>e.name),m=f??[...ni(),...ri()];this.builtinCommandNames=new Set([...m,...p]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.startInitialJshSync()}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}setMaskedEnvVar(e,t){this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}applySessionOverrides(e){e.cwd!==void 0&&(this.cwd=e.cwd,this.lastEnv.PWD=e.cwd),e.env&&Object.assign(this.lastEnv,e.env)}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight===null?(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight):(this.jshSyncDirty=!0,this.jshSyncInflight)}async executeCommand(e,t,n,r=``,i){let a=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);let o=i?.onOutput?`tee-${this.nextOutputTeeId+=1}`:void 0;o&&i?.onOutput&&this.outputTees.set(o,i.onOutput);try{let i=await this.runCommand(e,t,n,r,o);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}finally{this.activeShellPid=a,o&&this.outputTees.delete(o)}}async executeScriptFile(e,t=[]){return cJ(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}currentScanRoots(){return ya(this.lastEnv.PATH)}startInitialJshSync(){this.initialJshSync=this.initHomeAndProfile().then(()=>this.syncJshCommands()).catch(()=>void 0).finally(()=>{this.initialJshSync=null})}async initHomeAndProfile(){let e=this.options.fs;try{let t=this.options.env?.HOME??await DN(e);this.lastEnv.HOME=t,this.options.env?.USER||(this.lastEnv.USER=ON(t));let n=`${t.replace(/\/+$/,``)}/.profile`;if(!await e.exists(n).catch(()=>!1))return;let r=await this.bash.exec(`. "$HOME/.profile"`,{env:this.lastEnv,cwd:this.cwd});if(r.env){let{PWD:e,...t}=r.env;this.lastEnv={...t,PWD:this.lastEnv.PWD??this.cwd}}}catch(e){gSe.warn(`HOME/profile init failed; continuing with defaults`,e)}}async waitForInitialJshSync(e){let t=this.initialJshSync;if(t===null)return;if(!e){await t;return}if(e.aborted)return;let n;try{await new Promise(r=>{n=()=>r(),e.addEventListener(`abort`,n,{once:!0}),t.then(()=>r(),()=>r())})}finally{n&&e.removeEventListener(`abort`,n)}}async runCommand(e,t,n,r=``,i){dSe(e.trim().split(/\s+/)[0]||`unknown`),me(),await this.waitForInitialJshSync(t);let a={env:{...this.lastEnv,...n===void 0?{}:{[D7]:String(n)},...i===void 0?{}:{[O7]:i}},cwd:this.cwd,signal:t,...r===``?{}:{stdin:r,stdinKind:`bytes`}},o=this.lastEnv.PATH;this.activeRunSignal=t;let s=this.beginScriptRun(e),c;try{c=await this.bash.exec(e,a)}finally{this.activeRunSignal===t&&(this.activeRunSignal=void 0),this.endScriptRun(s)}if(await this.flushPendingCommandGrants(),c.env&&(this.lastEnv=_Se(c.env)),c.env&&this.lastEnv.PATH!==o&&await this.syncJshCommands().catch(()=>void 0),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)t===null?delete this.lastEnv[e]:this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(c.env?.PWD&&(this.cwd=c.env.PWD),c.exitCode===127){let t=await this.tryJshFallback(e,n);if(t)return this.syncJshCommands().catch(()=>void 0),t}return c}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForDispatch(e){let t=this.wrapCommandForSudo(e),n=e.name===`timeout`?GJ(t,this.progress):qJ(t,this.progress),r=()=>this.scriptRun?.stepDone(),i=(e,t)=>this.teeCommandOutput(e,t);return{...n,async execute(e,t){try{let r=await n.execute(e,t);return i(t.env,r),r}finally{r()}}}}teeCommandOutput(e,t){let n=e?.get(O7);if(!n)return;let r=this.outputTees.get(n);if(!r)return;let i=[t.stdout,t.stderr].filter(Boolean).join(``);i&&r(i)}beginScriptRun(e){if(this.scriptRunsActive+=1,!this.progress.hasSink())return null;if(this.scriptRunsActive>1)return this.scriptRun?.end(),this.scriptRun=null,null;let t={totalSteps:null};try{t=IJ(this.bash.transform(e).ast,this.registryNames)}catch{t={totalSteps:null}}return this.scriptRun=new RJ(t,this.progress,LJ(e)),this.scriptRun}endScriptRun(e){this.scriptRunsActive=Math.max(0,this.scriptRunsActive-1),e&&(e.end(),this.scriptRun===e&&(this.scriptRun=null))}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{...e,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=YJ(e,t);if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await ZJ(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=di(e);if(!n)return;let r=`${fi}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof lr&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
4992
|
+
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(this.currentScanRoots()),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForDispatch(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForDispatch(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this.options.jshDiscoveryFs??this.options.fs,r=e,i=async(e,i)=>{let a=i.exec??((e,t)=>this.bash.exec(e,{env:Object.fromEntries(i.env),cwd:t?.cwd??i.cwd,args:t?.args})),o=(await t.getJshCommands(this.currentScanRoots())).get(r);if(o){let t;try{let e=await n.readFile(o,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}return lJ(t,[`node`,o,...e],{fs:i.fs,cwd:i.cwd,env:i.env,stdin:i.stdin,exec:a},this.buildJshProcessConfig(k7(i.env)))}let s=(await t.getWorkflowCommands()).get(r);if(s){let t=Sa(s.path,e);return a(t[0],{args:t.slice(1),cwd:i.cwd})}return{stdout:``,stderr:`${r}: command no longer exists\n`,exitCode:127}};return{name:e,trusted:!0,async execute(e,t){try{return await i(e,t)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${r}: ${t}\n`,exitCode:1}}}}}createGitCustomCommand(){let e=this.gitCommands;return V(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env,mo(n.stdin));return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return V(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createUmountCustomCommand(){let e=this.mountCommands;return V(`umount`,async(t,n)=>{let r=n.cwd,i=await e.executeUmount(t,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(this.currentScanRoots()),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e,t){let n=e.trim(),r=n.indexOf(` `),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1).trim():``,o=(await this.getFilteredJshCommands()).get(i);if(!o)return null;let s=a?mJ(a):[],c=this.options.jshDiscoveryFs??this.options.fs,l;try{let e=await c.readFile(o,{encoding:`utf-8`});l=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127,env:this.lastEnv}}let u=[`node`,o,...s],d=await lJ(l,u,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig(t));return{stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode,env:this.lastEnv}}buildJshProcessConfig(e){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>e??this.activeShellPid??this.options.getCurrentShellPid?.()}}};function vSe(e){let{isCone:t,folder:n,secretEnv:r,tmpDir:i,lickTarget:a}=e,o=a?{[Pee]:a}:{};return t?{...r,TMPDIR:i,...o}:{...r,HOME:`/scoops/${n}/home`,TMPDIR:i,USER:n,PATH:[`/usr/bin`,`/scoops/${n}/workspace/skills`,`/scoops/${n}/workspace/bin`,...va].join(`:`),...o}}function ySe(e,t,n){return e.display.role===`child`?t.folder:t.jid===n?void 0:t.folder}function bSe({sudoManager:e,unit:t,folder:n,onSudoRequest:r}){if(!e)return null;let i=e,{policy:a}=t,o=a.approvalAuthority===`user`,s=r,c=o||!s?i.getBroker():{requestApproval:e=>s(e)},l=o?()=>i.getPolicy():()=>i.getPolicyForScoop(n),u=a.sudoDefaultDisposition,d=i.getShellConfig(),f=a.persistCommandGrants?d.persistCommandGrant:async()=>{},p={broker:c,getPolicy:l,defaultDisposition:u,shellConfig:{...d,broker:c,getPolicy:l,defaultDisposition:u,persistCommandGrant:f}};return a.persistCommandGrants||(p.onGrant=async()=>{}),p}const j7=r(`scoop-context`);async function xSe(e){try{let t=await e.secrets.listMaskedEnv();return t.ok?Array.isArray(t.value.entries)?Cie(t.value.entries):(j7.warn(`Masked secrets response was not an array`,{entriesType:typeof t.value.entries}),{}):(j7.warn(`Failed to fetch masked secrets`,{capability:t.capability,operation:t.operation,message:t.message,status:`status`in t?t.status:void 0}),{})}catch(e){return j7.warn(`Failed to fetch masked secrets`,{error:e instanceof Error?e.message:String(e)}),{}}}async function SSe(e){let{scoop:t,unit:n,fs:r,skillsFs:i}=e,a=n.workspace.root,o=e.getBrowserAPI();n.policy.filesystem.kind===`full-workspace`&&await qS(r,Yn);let s=i??r,c=e.capabilityBroker??Ny(),l=await xSe(c),u=await c.network.localNodeServer(),d=()=>u.ok,f=bSe({sudoManager:e.sudoManager,unit:n,folder:t.folder,onSudoRequest:e.onSudoRequest}),p=f?bi(r,{broker:f.broker,getPolicy:f.getPolicy,defaultDisposition:f.defaultDisposition,...f.onGrant?{onGrant:f.onGrant}:{}}):r,m=vSe({isCone:n.policy.filesystem.kind===`full-workspace`,folder:t.folder,secretEnv:l,tmpDir:e.tmpDir,...e.lickTarget?{lickTarget:e.lickTarget}:{}}),h=new A7({fs:p,cwd:a,env:Object.keys(m).length>0?m:void 0,browserAPI:o,webhook:{hasLocalNodeServer:d,getLeaderStatus:Nr},crontask:{hasLocalNodeServer:d},jshDiscoveryFs:i?s:void 0,allowedCommands:t.config?.allowedCommands,getParentJid:()=>t.jid,isScoop:()=>n.display.role===`child`,sudo:f?.shellConfig,scrubProgressLabel:Zt(),processManager:e.processManager??void 0,processOwner:e.processOwner,getCurrentShellPid:e.getTurnPid});return j7.info(`AlmostBashShell initialized`,{folder:t.folder}),{shell:h,gatedFs:p,skills:await US(s,Yn)}}const CSe={anthropic:`Anthropic`,openai:`OpenAI`,google:`Google`,adobe:`Adobe`,github:`GitHub`,bedrock:`AWS Bedrock`,azure:`Azure`,"azure-openai":`Azure OpenAI`,"azure-ai-foundry":`Azure AI Foundry`,groq:`Groq`,xai:`xAI`,openrouter:`OpenRouter`,local:`your local model`};function wSe(e){if(e)return CSe[e]??e}const M7=51200;function N7(e){if(e.length===0)return[];let t=e.split(`
|
|
4993
4993
|
`);return e.endsWith(`
|
|
4994
|
-
`)&&t.pop(),t}function P7(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function
|
|
4995
|
-
`),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function F7(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=N7(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=
|
|
4996
|
-
`),f=Buffer.byteLength(d,`utf-8`);return{content:d,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:f,lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function
|
|
4997
|
-
`)||e.length===0?e:`${e}\n`}${
|
|
4998
|
-
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await G7(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){I7.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){I7.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=F7(
|
|
4999
|
-
`),a=t.length,o=Math.max(0,r-1),s=o+1;if(o>=t.length)return{content:`Offset ${r} is beyond end of file (${a} lines total)`,isError:!0};let c=i===void 0?t.slice(o):t.slice(o,Math.min(o+i,t.length)),l=i===void 0?void 0:c.length,u=
|
|
5000
|
-
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${P7(new TextEncoder().encode(t[o]??``).length)}, exceeds ${P7(M7)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${M7}]`};let d=u.content,f=``;if(u.truncated){let e=s+u.outputLines-1,t=e+1;f=u.truncatedBy===`lines`?`\n\n[Showing lines ${s}-${e} of ${a}. Use offset=${t} to continue.]`:`\n\n[Showing lines ${s}-${e} of ${a} (${P7(M7)} limit). Use offset=${t} to continue.]`}else l!==void 0&&o+l<t.length&&(f=`\n\n[${t.length-(o+l)} more lines in file. Use offset=${o+l+1} to continue.]`);return{content:d+f}}catch(e){let t=e instanceof Error?e.message:String(e);return q7.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function
|
|
5001
|
-
`)}function
|
|
5002
|
-
`)}async function
|
|
5003
|
-
`)}`}}function
|
|
5004
|
-
`)}}function
|
|
5005
|
-
`)}`}}async function ICe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),Y7.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 LCe(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=>mCe(t,e)}}function RCe(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:[...a9],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=>_Ce(t,e)}}function zCe(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") — any name list_scoops shows you.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`},[X7]:i9(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>vCe(t,e)}}function BCe(e){return{name:`list_scoops`,description:`List the scoops you can manage: your own subtree, plus — leading cone only — ones tagged [INHERITED] (owning cone gone) or [FOREIGN: <cone>] (another cone owns it). These names are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait resolve; a tagged one also needs cross_cone: true.`,inputSchema:{type:`object`,properties:{}},execute:()=>bCe(e)}}function VCe(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:[...sr],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=>wCe(t,e)}}function HCe(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") — any name list_scoops shows you.`},[X7]:i9(`drop`)},required:[`scoop_name`]},execute:t=>TCe(t,e)}}function UCe(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"]).`},[X7]:i9(`mute`)},required:[`scoop_names`]},execute:t=>ECe(t,e)}}function WCe(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"]).`},[X7]:i9(`unmute`)},required:[`scoop_names`]},execute:t=>OCe(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 list_scoops shows you (e.g., ["writer-scoop", "reviewer-scoop"]).`},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."},[X7]:i9(`wait on`)},required:[`scoop_names`]},execute:t=>jCe(t,e)}}function KCe(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=>NCe(t,e)}}function qCe(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=>PCe(t,e)}}function JCe(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:()=>FCe(e)}}function YCe(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=>ICe(t,e)}}function XCe(e){let t=[],n=On(e.scoop);return Tn(e.scoop)||(t.push(LCe(e)),e.onSudoRequest&&t.push(RCe(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(VCe(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(zCe(e)),t.push(BCe(e)),e.onDropScoop&&t.push(HCe(e)),e.onMuteScoops&&t.push(UCe(e)),e.onUnmuteScoops&&t.push(WCe(e)),e.onScheduleScoopWait&&t.push(GCe(e)),e.onSudoResolve&&(t.push(KCe(e)),t.push(qCe(e))),e.onListSudoRequests&&t.push(JCe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(YCe(e))),t}const ZCe=r(`scoop-context`);function QCe(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-Mu-876Hm.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function $Ce(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:oe,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,n.workspace.root),RSe(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:Zt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){ZCe.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,iCe({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>CSe(YC(t).provider)})];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:Zt()},s=QCe(e);return e.processManager?nn(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):nn(a,void 0,o,s)}const c9=r(`scoop-context`);async function ewe(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();c9.info(`Filesystem ready`,{folder:t.folder}),await bie(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await xSe({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 $Ce({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 sie(r,n,()=>i.getGlobalMemory());if(!JC(t))return c9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=lie(t,n),p=XC(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await Sie(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>JC(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=In(t);return{kind:`ready`,agent:vie({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:ZC(QC()??v.level,f),getApiKey:()=>JC(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 l9=r(`scoop-context`);var twe=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=an(e.messages);return this.createdAt=e.createdAt,l9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){l9.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 l9.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=zi(t);if(n.length===0)return null;let r=an(n);return t&&(this.createdAt=t.createdAt),l9.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=>{l9.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=>{l9.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){l9.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 nwe(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 rwe(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function u9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const d9=r(`scoop-context`);var iwe=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;d9.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)&&(d9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:zC(r)}),!!(t<3&&(await BC(f9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return RC(e)?(d9.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 ks(e)?(d9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ms(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!zC(e)||t>=3)return!1;let r=f9(t);return d9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await BC(r,n)&&!this.deps.isDisposed()}fail(e,t){IC(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function f9(e){return 1e3*2**(e-1)}function awe(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){d9.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 p9=r(`scoop-context`);var owe=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=Kn(e),this.owner={kind:Nn(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 twe({store:r??null,canonical:c?{store:c,identity:{key:Or(e),workUnitId:e.jid,workspaceId:Dr(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:zn(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 _ie({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new iie({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new aie({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new gie({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 iwe({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 vSe(this.unit,this.scoop,Dn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Un(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 ewe({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:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});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`),p9.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);p9.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(die(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),rwe(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(awe(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=nwe(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(){u9(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 Gi(this.scoop)?!0:this.unit.parentId===null&&p(`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:on,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(!(this.unit.parentId!==null&&!p(`memory-v2`)))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-CpwRZg6K.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o?{transcriptPath:o.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-CpwRZg6K.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){p9.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 uie(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=pie(this.agent,this.scoop))}async reloadSkills(){this.agent&&await hie(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?QC()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,mie(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),u9(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||UC(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||VC(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 m9=r(`scoop-lifecycle-manager`);var swe=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 NC(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))??Dn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return kn(t.values(),e)??Dn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){m9.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 wr))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`)m9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{m9.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=Kn(t).policy.filesystem;if(a.kind===`restricted`){let e=wn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new wr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:cee(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 owe(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=>{m9.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&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),m9.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);m9.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),m9.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 m9.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(m9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){m9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){m9.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`)),m9.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(Hn(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=Fn(e.folder,n);r!==e.folder&&(m9.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),m9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&hC(`spawn`,e.folder)}catch(n){m9.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){m9.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=>{m9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(Mn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Vn(t):void 0)??aC();n&&Pn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of mee(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&Dn(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=>{m9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Or(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{m9.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&&m9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),m9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){m9.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;Pn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Pn(n,r),this.getContext(e)?.updateModel(),m9.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();m9.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=>{m9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),m9.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;lee(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){m9.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}=Kn(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}),hC(`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 An(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?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:Zn(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,Tn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(Tn(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(m9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),hC(`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`),Kn(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){m9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{m9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const h9=r(`scoop-message-router`);var cwe=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(h9.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){h9.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}`);hC(`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),h9.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);h9.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){h9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){h9.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(h9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){h9.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{h9.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);h9.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);h9.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,h9.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){h9.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){h9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){h9.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(h9.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){h9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){h9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Br($r(Wr(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){h9.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}: ${oee(e.content,e.attachments)}`).join(`
|
|
5006
|
-
`),l=s.flatMap(e=>see(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Br($r(Wr(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);h9.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=>{h9.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=>{h9.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),h9.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=>{h9.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=>{h9.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(),h9.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 g9=r(`orchestrator`),lwe={decision:`deny`};var uwe=class{scoops=new Map;workUnits=new Ar(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new QS({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new AC({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 OC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new SC({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 uC({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=>Jr(e),saveMessage:e=>Vr(e)});lickRegistry=new tC({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 cwe({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=>Vr(e),deleteMessage:e=>Ur(e),clearMessagesForScoop:e=>Zr(e),clearAllMessages:()=>Yr(),getMessagesSince:(e,t,n)=>qr(e,t,n),setState:(e,t)=>zr(e,t)},isExternalLickChannel:tv});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new swe({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=>Rr(e),deleteScoop:e=>Xr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>te(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,n)=>this.scheduleScoopWait(e,t,n),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 oC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new db({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 Ey(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new iC(e,t),await this.modelPolicyFile.init(),n(),hee()),n,{stagePrefix:`orchestrator-init`})}async init(e){await gee(),this.sharedFs=await oC(e=>Cr.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new K_,this.conversationStore=new SS,this.fsWatcher=new Sr,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=>Bn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Hn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Kr(`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)=>{g9.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(),g9.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);g9.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}`)}xee(e=>this.getSessionCostsForCommand(e)),See(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-DMq3fdAk.js`).then(e=>e.t);return e()}),this.unregisterExportService=pb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Y_;try{await gS({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){g9.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=Bn(e)?null:t??null;try{await Rr(e)}catch(t){g9.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=>!Mn(e));if(e.length===0)return;let t=aC(),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?Vn(n):void 0)??t;if(r){Pn(e,r);try{await Rr(e)}catch(t){g9.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=Jn(Xn(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,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-Df9ytmfk.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:Zn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(g9.warn(`Guest approval before SudoManager init — failing closed`),lwe)}})}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)}getDefaultConeFs(){let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null}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 Rr(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 Dn(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 fee(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return kn(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 Cr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await qS(this.sharedFs).catch(e=>{g9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new db({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 Ey(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new iC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),g9.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 Jr(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-B4efpvB9.js`).then(e=>e.r),r=await n(this.sharedFs);return[...t,...r.map(wee)]}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&&g9.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,g9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Y_,t=this.sharedFs;return new Ix({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:tS(),snapshotStore:{read:e=>qx(t,e),write:(e,n)=>Kx(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.154.5`})}};const _9=r(`workflow-run-manager`),v9=`/shared/workflow-runs`,y9=1e3;function dwe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function fwe(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){_9.warn(`observeRun handler threw`,e)}},i=(e,n)=>_we(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=dwe(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),hwe(t,n);let f=i(a.ctx,c),p=gwe(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=>_9.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=`${v9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(v9,{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);_9.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`?mwe(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){_9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function pwe(e){let t=fwe(e);return globalThis[f7]=t,_9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function mwe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function hwe(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 gwe(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 _we(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?vwe(n,t,a?.args??[],r):e===`agent`?ywe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function vwe(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>y9&&i.logs.splice(0,i.logs.length-y9),r()}return{stdout:``,stderr:``,exitCode:0}}async function ywe(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 bwe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function xwe(e,t,n){let r=Swe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=Cwe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Swe(e){let t=new Map;return b9(t,e.discoveryOrigin),b9(t,e.discoveryUrl),[...t.values()]}function b9(e,t){if(t){x9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);x9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!bwe.has(e)))x9(e,t,1,`substring`)}catch{}}}function x9(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 Cwe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Twe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)wwe(a,e)&&(r+=e.weight*o)}return r}function wwe(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 Twe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Ewe=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=w9(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:C9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===C9)throw new lr(`ENOTDIR`,`not a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);return S9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new lr(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=w9(e);if(t.length===1&&t[0]===C9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new lr(`EISDIR`,`is a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new lr(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new lr(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=w9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===C9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new lr(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new lr(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new lr(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new lr(`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 lr(`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:E9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:D9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5007
|
-
`}renderProcFile(e,t){if(e===1)return
|
|
4994
|
+
`)&&t.pop(),t}function P7(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function TSe(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=N7(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(a[0],`utf-8`)>r)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:o,totalBytes:i,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`;for(let e=0;e<a.length&&e<n;e++){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(c+n>r){l=`bytes`;break}s.push(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let u=s.join(`
|
|
4995
|
+
`),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function F7(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=N7(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=ESe(t,r);s.unshift(e),c=Buffer.byteLength(e,`utf-8`),u=!0}break}s.unshift(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let d=s.join(`
|
|
4996
|
+
`),f=Buffer.byteLength(d,`utf-8`);return{content:d,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:f,lastLinePartial:u,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function ESe(e,t){let n=Buffer.from(e,`utf-8`);if(n.length<=t)return e;let r=n.length-t;for(;r<n.length&&(n[r]&192)==128;)r++;return n.slice(r).toString(`utf-8`)}const I7=r(`tool:bash`),L7=40960,R7=1048576,z7=`\0slicc-img:`;function DSe(e){let t=fn(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:new Map};let n=new Set,r=R7;for(let e=t.length-1;e>=0;e--){let i=t[e].marker.length;if(i>r&&n.size>0)break;r-=i,n.add(e)}let i=new Map,a=``,o=0;return t.forEach((t,r)=>{if(a+=e.slice(o,t.index),n.has(r)){let e=`${z7}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${R7/1024}KB image budget. View it on its own to see it.]`;o=t.index+t.marker.length}),a+=e.slice(o),{text:a,markers:i}}function OSe(e){let t=fn(e).filter(e=>e.kind===`image`);if(t.length===0)return e;let n=``,r=0;for(let i of t)n+=`${e.slice(r,i.index)}[image]`,r=i.index+i.marker.length;return n+e.slice(r)}function kSe(e){return e.replaceAll(RegExp(`${z7}\\d+`,`g`),`[image]`)}function B7(e,t){if(t.size===0)return e;let n=e;for(let[e,r]of t)n.includes(e)&&(n=n.replace(e,()=>r));return n}async function ASe(e,t,n,r){let{text:i,markers:a}=DSe(e),o=F7(i,{maxBytes:L7});if(!o.truncated)return B7(i,a);let s=`showing the last ${P7(o.outputBytes)} of ${P7(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,kSe(i)),B7(`${o.content}\n\n[Output truncated: ${s}. Full output written to ${c} — read specific ranges with \`sed -n 'START,ENDp' ${c}\`, \`tail -n +N ${c}\`, or \`grep\`.]`,a)}catch(e){return I7.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),B7(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const jSe=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function V7(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 MSe(e){let t=e.statements[e.statements.length-1],n=t?.pipelines[t.pipelines.length-1];if(!n||n.negated)return null;let r=n.commands[n.commands.length-1];if(r?.type!==`SimpleCommand`||!r.name)return null;let i=V7(r.name);if(i!==`command`)return i;let a=r.args[0];return a?V7(a):null}function NSe(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=MSe(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&jSe.has(i)}function H7(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function PSe(e){return`Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run \`commands\` for full list. Output is capped at ${L7/1024}KB (the tail is kept); when truncated the full output is written to a temp file named in the result so you can page it. Inline images (\`open --view\`) do not count against that cap — up to ${R7/1024}KB of images per command reaches you as pictures, not base64. A command still running after background_after seconds (default ${e}) is detached: you get a job id at once and a Background Command lick delivers its exit code and output later, so a stuck command never wedges the turn.`}function FSe(e){return{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`},timeout:{type:`number`,description:`Hard ceiling in seconds: the command is killed and this call returns an error — no job, no lick. Omit for no ceiling (the default), which detaches a slow command instead of killing it.`},background_after:{type:`number`,description:`Seconds to wait before detaching the command. Defaults to ${e}. Use 0 to detach immediately (dev servers, watchers), or a large value when you must have the output in this turn. A smaller timeout wins: the command is killed, not detached.`}},required:[`command`]}}function ISe(e){return{content:`Command timed out after ${e}s and was killed; no output was captured. Re-run it with a larger timeout, a larger background_after so it detaches instead of dying, or narrow the command so it finishes sooner.`,isError:!0}}function LSe(e,t,n){let r=new AbortController,i=e.options.jobHost?.spawn(t)??null,a=()=>r.abort();n?.aborted?r.abort():n?.addEventListener(`abort`,a,{once:!0}),i&&(i.signal.aborted?r.abort():i.signal.addEventListener(`abort`,()=>r.abort(),{once:!0}));let o=[],s,c,l=Promise.resolve(),u=()=>{if(s===void 0||c===void 0)return;let t=s,n=c,r=o.join(``);l=l.then(async()=>{let i=await G7(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>I7.warn(`Failed to tee background bash output`,{jobId:n,outputPath:t,error:e instanceof Error?e.message:String(e)}))};return{job:i,controller:r,settled:e.shell.executeCommand(t,r.signal,i?.pid,void 0,{onOutput:e=>{o.push(e),u()}}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e instanceof Error?e.message:String(e)})),releaseTurnSignal:()=>n?.removeEventListener(`abort`,a),getTeedOutput:()=>o.join(``),startPersisting:(e,t)=>{s=e,c=t,u()},flushPersist:()=>l,killedByTimeout:!1}}function U7(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function W7(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function RSe(e,t,n,r,i){let a=i===void 0?``:` Its ${i}s timeout still applies.`;return{content:`Still running after ${n}s — detached as background job ${e}. This turn is NOT blocked on it: continue with other work, and do not re-run the command. A "Background Command" lick will arrive with the exit code and a preview once it finishes, and its full output is being written to ${r} as it runs.${t===void 0?``:` Pid ${t}: \`ps\` lists it, \`kill ${t}\` stops it.`}${a}`}}function zSe(e,t,n,r={}){let i=0,a=0,o={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:H7(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`};return{name:`bash`,description:PSe(o.defaultBackgroundAfter),inputSchema:FSe(o.defaultBackgroundAfter),execute:(e,t)=>GSe(o,e,t)}}async function G7(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return I7.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function BSe(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function VSe(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function HSe(e,t,n,r,i,a,o,s){await o.flushPersist();let c=o.killedByTimeout||BSe(a),l,u;if(c){let e=o.getTeedOutput();u=124,l=`${e.endsWith(`
|
|
4997
|
+
`)||e.length===0?e:`${e}\n`}${VSe(s,u)}`}else if(a.ok)l=[a.result.stdout,a.result.stderr].filter(Boolean).join(``)||`(exit code: ${a.result.exitCode})`,u=a.result.exitCode;else{let e=o.getTeedOutput();u=1,l=e?`${e.endsWith(`
|
|
4998
|
+
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await G7(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){I7.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){I7.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=F7(OSe(d),{maxBytes:2048});e.options.fireLick({type:`bash`,bashJobId:t,bashCommand:r,bashExitCode:u,...n===void 0?{}:{bashJobPid:n},resultPath:f,preview:p.content,...e.options.targetScoop?{targetScoop:e.options.targetScoop}:{},timestamp:new Date().toISOString(),body:{jobId:t,pid:n??null,command:r,exitCode:u,resultPath:f??null}})}function USe(e,t,n,r,i,a){let o=e.nextJobId(),s=t.job?.pid,c=`${e.tempDir}/bash-${o}.txt`;t.startPersisting(c,o);let l=i===void 0?void 0:i-a,u=l===void 0?void 0:setTimeout(()=>U7(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),W7(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),HSe(e,o,s,n,c,r,t,i))).catch(e=>I7.error(`Background bash delivery failed`,{jobId:o,error:e})),I7.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),RSe(o,s,r,c,i)}async function WSe(e,t,n){I7.debug(`Result`,{exitCode:n.exitCode,stdoutLength:n.stdout.length,stderrLength:n.stderr.length});let r=``;return n.stdout&&(r+=n.stdout),n.stderr&&(r+=n.stderr),r||=`(exit code: ${n.exitCode})`,{content:await ASe(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!NSe(e.shell,t,n.exitCode,n.stderr)}}async function GSe(e,t,n){let r=t.command,i=H7(t.timeout),a=H7(t.background_after)??e.defaultBackgroundAfter;I7.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=LSe(e,r,n),s=i!==void 0&&i<=a,c=s?i:a,l,u=new Promise(e=>{l=setTimeout(()=>e(`elapsed`),c*1e3)});try{let t=await Promise.race([o.settled,u]);return t===`elapsed`&&s?(U7(o,`timeout`),I7.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),ISe(c)):t===`elapsed`?USe(e,o,r,c,i,a):(W7(o,t.ok?t.result.exitCode:1),t.ok?await WSe(e,r,t.result):(I7.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const KSe={type:`object`,required:[`path`,`edits`],properties:{path:{type:`string`},edits:{type:`array`,items:{type:`object`,required:[`oldText`,`newText`],properties:{oldText:{type:`string`},newText:{type:`string`}}}}}};function K7(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function qSe(e){if(!e||typeof e!=`object`)return e;let t=e;if(typeof t.edits==`string`)try{let e=JSON.parse(t.edits);Array.isArray(e)?t.edits=e:K7(e)&&(t.edits=[e])}catch{}else K7(t.edits)&&(t.edits=[t.edits]);if(typeof t.oldText!=`string`||typeof t.newText!=`string`)return t;let n=Array.isArray(t.edits)?[...t.edits]:[];n.push({oldText:t.oldText,newText:t.newText});let{oldText:r,newText:i,...a}=t;return{...a,edits:n}}function JSe(e,t=`/workspace`){return{name:`edit`,description:`Edit one file using exact replacements. Each oldText must be unique in the original file; edits must not overlap. Combine changes to the same block in one edit.`,inputSchema:KSe,prepareArguments:qSe,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-DYRoRikS.js`);return i(e,t,n,r)}}}const q7=r(`tool:fs`);function YSe(e,t=`/workspace`){return[XSe(e),ZSe(e),JSe(e,t)]}function XSe(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${M7/1024}KB (whichever is hit first); use offset/limit for large files and the \`offset=N\` in the footer to page through the rest.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;q7.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
4999
|
+
`),a=t.length,o=Math.max(0,r-1),s=o+1;if(o>=t.length)return{content:`Offset ${r} is beyond end of file (${a} lines total)`,isError:!0};let c=i===void 0?t.slice(o):t.slice(o,Math.min(o+i,t.length)),l=i===void 0?void 0:c.length,u=TSe(c.join(`
|
|
5000
|
+
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${P7(new TextEncoder().encode(t[o]??``).length)}, exceeds ${P7(M7)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${M7}]`};let d=u.content,f=``;if(u.truncated){let e=s+u.outputLines-1,t=e+1;f=u.truncatedBy===`lines`?`\n\n[Showing lines ${s}-${e} of ${a}. Use offset=${t} to continue.]`:`\n\n[Showing lines ${s}-${e} of ${a} (${P7(M7)} limit). Use offset=${t} to continue.]`}else l!==void 0&&o+l<t.length&&(f=`\n\n[${t.length-(o+l)} more lines in file. Use offset=${o+l+1} to continue.]`);return{content:d+f}}catch(e){let t=e instanceof Error?e.message:String(e);return q7.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function ZSe(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;q7.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await Zee(e,n,r);return t?(q7.error(`Write durability check failed`,{path:n,error:t}),{content:t,isError:!0}):{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return q7.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function QSe(){return null}const J7=r(`tool:request-secret`);async function $Se(e,t){let n=QSe();if(n)return n(e);let r=t.callPanelRpc??await eCe();return r?r(e):{stored:!1,reason:`unavailable`}}async function eCe(){let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i),t=e();return t?e=>t.call(`secret-request`,e,{timeoutMs:3e5}):null}function tCe(e){try{return e.getProvider?.()||void 0}catch(e){J7.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function nCe(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0}function rCe(e,t){let n=[`The user stored the secret "${e.name}".`,`Scope: ${e.domains.join(`, `)} — it is only unmasked for requests to these hosts.`,e.persisted?`Lifetime: saved (survives this session).`:`Lifetime: this session only (held in memory).`];return e.maskedValue?(n.push(`Masked value: ${e.maskedValue}`,`Use the masked value wherever the credential goes (headers, request bodies). SLICC substitutes the real value at the network boundary. You will never see the real value.`),t&&n.push(`It is also available as $${e.name} in bash.`)):n.push(`The store did not report a masked value; run \`secret get ${e.name}\` to read it.`),n.join(`
|
|
5001
|
+
`)}function iCe(e){switch(e.reason){case`cancelled`:return`The user dismissed the secret prompt — nothing was stored. Do not retry; ask what to do instead.`;case`unavailable`:return"This float cannot prompt for a secret (no secret-entry surface). Ask the user to add it from the leader UI or with `secret set`.";default:return`The secret could not be stored${e.detail?`: ${e.detail}`:``}.`}}function aCe(e={}){return{name:`request_secret`,description:`Ask the user for a credential (API key, token, password) through a secure prompt. You never receive the real value: the result carries only the secret name, a masked stand-in to use in requests, and the domains it may be sent to. Use this instead of asking for a credential in chat, which would put it in the transcript.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Suggested secret name, e.g. GITHUB_TOKEN. Use an uppercase POSIX identifier so it is also available as $NAME in bash. The user can change it.`},reason:{type:`string`,description:`One plain sentence saying what the credential is for. Shown verbatim to the user.`},domains:{type:`array`,items:{type:`string`},description:`Suggested hosts the value may be sent to, e.g. ["api.github.com", "*.github.com"]. Be as narrow as the task allows; the user reviews and can edit this.`},persist:{type:`boolean`,description:`Suggest keeping the secret beyond this session. Defaults to false (session-only).`}},required:[`name`,`reason`]},async execute(t){let n=typeof t.name==`string`?t.name.trim():``,r=typeof t.reason==`string`?t.reason.trim():``;if(!n||!r)return{content:"request_secret needs both `name` and `reason`.",isError:!0};let i={name:n,reason:r,domains:nCe(t.domains),persist:t.persist===!0,requester:e.requester,provider:tCe(e)},a;try{a=await $Se(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return J7.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:iCe(a),isError:!0};let o=oCe(a.name,a.maskedValue,e);return J7.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:rCe(a,o)}}}}function oCe(e,t,n){if(!n.setEnv||!t||!tw(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return J7.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const Y7=r(`scoop-management-tools`),X7=`cross_cone`;function Z7(e){return En(e.getScoops(),e.scoop.jid)}function sCe(e){let t=new Set;for(let n of Z7(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function cCe(e){let t=jn(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function Q7(e){let t=e.getScoops(),n=sCe(e),r=cCe(e),i=[];for(let e of t){if(e.parentJid===null)continue;if(n.has(e.jid)){i.push({scoop:e,relation:`own`});continue}if(!r)continue;let a=pee(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function $7(e){return t=>t.folder===e||t.name===e}function e9(e,t){let n=Q7(t);return n.find(t=>t.scoop.folder===e)??n.find(t=>t.relation===`own`&&t.scoop.name===e)??n.find(t=>t.scoop.name===e)}function t9(e,t){let n=[],r=[];for(let i of e){let e=e9(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function n9(e,t){return kn(e.getScoops(),t.scoop)?.folder??`unknown`}function lCe(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${n9(e,t)}"`}function r9(e,t,n,r){let i=e.filter(e=>e.relation!==`own`);return i.length===0||t===!0?null:{content:`Refusing to ${n}: ${i.map(e=>`"${e.scoop.folder}" is ${lCe(r,e)}`).join(`; `)}. Pass ${X7}: true to act on it anyway.`,isError:!0}}function i9(e){return{type:`boolean`,description:`Set true to ${e} a scoop you do not own — inherited (its cone is gone) or another cone's. Default false; omitting it on such a scoop is an error, so the choice stays deliberate.`}}const a9=[`command`,`read`,`write`,`secret`];function uCe(e){return`${ye(e,{maxLen:50})}-scoop`}function dCe(e){return e===void 0?{ok:!0}:or(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${sr.join(`, `)}.`,isError:!0}}function fCe(e){return e===void 0?{ok:!0}:typeof e!=`number`||!Number.isFinite(e)||e<0?{ok:!1,content:`Invalid background_after "${String(e)}". Must be a number of seconds >= 0.`}:{ok:!0,seconds:e}}function pCe(e,t){if(e===void 0||!t)return{ok:!0,modelId:e};let n=t(e);return n.ok?{ok:!0,modelId:n.selection.modelId,providerId:n.selection.providerId}:{ok:!1,content:`Unknown model "${e}": ${n.error}. Run the "models" shell command to list available model IDs.`,isError:!0}}function o9(e,t){let n=Q7(t).map(e=>e.scoop.folder).join(`, `)||`(none)`;return{content:`Not found in the scoops you can manage (${t.scoop.folder}): ${e.join(`, `)}. Available: ${n}`,isError:!0}}function mCe(e,t,n=``){let r=t?.(e.jid),i=r?.status??`unknown`,a=r?.lastActivity?new Date(r.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,o=a?` — ${i} (since ${a})`:` — ${i}`;return e.parentJid===null?`- ${e.assistantLabel} (${e.folder}) [CONE]${o}`:`- ${e.name} (${e.folder})${n}${o}`}async function hCe(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),Y7.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function gCe(e){let{kind:t,detail:n,suggested_pattern:r}=e;return a9.includes(t)?typeof n!=`string`||n.trim().length===0?{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}}:{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{}}}:{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${a9.join(`, `)}.`,isError:!0}}}function _Ce(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.decision===`deny`&&t.push(`The sensitive action was not approved. Do not retry without addressing the reason for refusal.`),t.join(`
|
|
5002
|
+
`)}async function vCe(e,t){let n=gCe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return Y7.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:_Ce(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function yCe(e,t){let{scoop_name:n,prompt:r,cross_cone:i}=e;if($7(n)(t.scoop))return{content:`Cannot feed yourself.`,isError:!0};let a=e9(n,t);if(!a)return o9([n],t);let o=r9([a],i,`feed "${n}"`,t);if(o)return o;try{await t.onFeedScoop(a.scoop.jid,r),Y7.info(`Fed scoop`,{target:a.scoop.folder,relation:a.relation,promptLength:r.length});let e=a.relation===`own`?`You will be notified when it completes.`:`Its completion notice goes to its owner; use scoop_wait (${X7}: true) for the result.`;return{content:`Task sent to ${a.scoop.folder}. ${e}`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function bCe(e,t){return t.relation===`own`?``:t.relation===`inherited`?` [INHERITED]`:` [FOREIGN: ${n9(e,t)}]`}async function xCe(e){let t=new Map(Q7(e).map(e=>[e.scoop.jid,e])),n=e.getScoops().filter(n=>n.jid===e.scoop.jid||t.has(n.jid));return n.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${n.map(n=>{let r=t.get(n.jid);return mCe(n,e.getScoopTabState,r?bCe(e,r):``)}).join(`
|
|
5003
|
+
`)}`}}function SCe({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}:{},...CCe(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 CCe(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function wCe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return Y7.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 TCe(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=wn(s);if(!f.ok)return{content:f.error,isError:!0};let p=dCe(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=fCe(u);if(!m.ok)return{content:m.content,isError:!0};let h=pCe(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=uCe(n),_=Z7(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(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=Fn(g,t.getScoops().map(e=>e.folder));try{let e=SCe({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:Jn(Zn(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return Y7.info(`Scoop created`,{name:n,folder:v}),i&&t.onFeedScoop?wCe(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 ECe(e,t){let{scoop_name:n,cross_cone:r}=e;if($7(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=e9(n,t);if(!i)return o9([n],t);let a=r9([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),Y7.info(`Scoop dropped`,{name:i.scoop.name,folder:i.scoop.folder,relation:i.relation}),{content:`Scoop "${i.scoop.name}" (${i.scoop.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function s9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function DCe(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return s9();let{resolved:i,unknown:a}=t9(n,t);return i.length===0?o9(a,t):r9(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),Y7.info(`Scoops muted`,{names:i.map(e=>e.scoop.folder)}),{content:`Muted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`})}function OCe(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 kCe(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return s9();let{resolved:i,unknown:a}=t9(n,t);if(i.length===0)return o9(a,t);let o=r9(i,r,`unmute these scoops`,t);if(o)return o;let s=i.map(e=>e.scoop.jid),c=new Map(i.map(e=>[e.scoop.jid,e.scoop.folder])),l=await t.onUnmuteScoops(s);Y7.info(`Scoops unmuted`,{names:i.map(e=>e.scoop.folder),stashedCount:l.length});let u=[`Unmuted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`];return u.push(...OCe(l,c)),{content:u.join(`
|
|
5004
|
+
`)}}function ACe(e,t){return!Array.isArray(e)||e.length===0?s9():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 jCe(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 MCe(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=ACe(n,r);if(a)return a;let{resolved:o,unknown:s}=t9(n,t);if(o.length===0)return o9(s,t);let c=r9(o,i,`wait on these scoops`,t);if(c)return c;let l=o.map(e=>e.scoop.jid),u=t.onScheduleScoopWait(l,r),d=new Map(o.map(e=>[e.scoop.jid,e.scoop.folder])),f=u.scheduled.map(e=>d.get(e)??e).join(`, `),p=u.unknown.map(e=>d.get(e)??e).join(`, `);return Y7.info(`Wait scheduled`,{scheduled:u.scheduled.map(e=>d.get(e)??e),droppedAtSchedule:p?p.split(`, `):[],unknownNames:s,timeout_ms:r}),u.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${p||u.unknown.join(`, `)}).${s.length>0?` Unknown names: ${s.join(`, `)}.`:``}`,isError:!0}:{content:jCe(f,s,p,r)}}function NCe(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 PCe(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?(Y7.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:NCe(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 FCe(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?(Y7.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 ICe(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(`
|
|
5005
|
+
`)}`}}async function LCe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),Y7.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 RCe(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=>hCe(t,e)}}function zCe(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:[...a9],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=>vCe(t,e)}}function BCe(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") — any name list_scoops shows you.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`},[X7]:i9(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>yCe(t,e)}}function VCe(e){return{name:`list_scoops`,description:`List the scoops you can manage: your own subtree, plus — leading cone only — ones tagged [INHERITED] (owning cone gone) or [FOREIGN: <cone>] (another cone owns it). These names are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait resolve; a tagged one also needs cross_cone: true.`,inputSchema:{type:`object`,properties:{}},execute:()=>xCe(e)}}function HCe(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:[...sr],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=>TCe(t,e)}}function UCe(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") — any name list_scoops shows you.`},[X7]:i9(`drop`)},required:[`scoop_name`]},execute:t=>ECe(t,e)}}function WCe(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"]).`},[X7]:i9(`mute`)},required:[`scoop_names`]},execute:t=>DCe(t,e)}}function GCe(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"]).`},[X7]:i9(`unmute`)},required:[`scoop_names`]},execute:t=>kCe(t,e)}}function KCe(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 list_scoops shows you (e.g., ["writer-scoop", "reviewer-scoop"]).`},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."},[X7]:i9(`wait on`)},required:[`scoop_names`]},execute:t=>MCe(t,e)}}function qCe(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=>PCe(t,e)}}function JCe(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=>FCe(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:()=>ICe(e)}}function XCe(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=>LCe(t,e)}}function ZCe(e){let t=[],n=On(e.scoop);return Tn(e.scoop)||(t.push(RCe(e)),e.onSudoRequest&&t.push(zCe(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(HCe(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(BCe(e)),t.push(VCe(e)),e.onDropScoop&&t.push(UCe(e)),e.onMuteScoops&&t.push(WCe(e)),e.onUnmuteScoops&&t.push(GCe(e)),e.onScheduleScoopWait&&t.push(KCe(e)),e.onSudoResolve&&(t.push(qCe(e)),t.push(JCe(e))),e.onListSudoRequests&&t.push(YCe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(XCe(e))),t}const QCe=r(`scoop-context`);function $Ce(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-Mu-876Hm.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function ewe(e){let{scoop:t,unit:n,callbacks:r}=e,i=ZCe({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:oe,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=[...YSe(e.gatedFs,n.workspace.root),zSe(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:Zt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){QCe.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,aCe({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>wSe(YC(t).provider)})];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:Zt()},s=$Ce(e);return e.processManager?nn(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):nn(a,void 0,o,s)}const c9=r(`scoop-context`);async function twe(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();c9.info(`Filesystem ready`,{folder:t.folder}),await bie(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await SSe({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 ewe({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 sie(r,n,()=>i.getGlobalMemory());if(!JC(t))return c9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=lie(t,n),p=XC(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await Sie(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>JC(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=In(t);return{kind:`ready`,agent:vie({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:ZC(QC()??v.level,f),getApiKey:()=>JC(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 l9=r(`scoop-context`);var nwe=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=an(e.messages);return this.createdAt=e.createdAt,l9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){l9.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 l9.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=zi(t);if(n.length===0)return null;let r=an(n);return t&&(this.createdAt=t.createdAt),l9.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=>{l9.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=>{l9.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){l9.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 rwe(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 iwe(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function u9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const d9=r(`scoop-context`);var awe=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;d9.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)&&(d9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:zC(r)}),!!(t<3&&(await BC(f9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return RC(e)?(d9.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 ks(e)?(d9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ms(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!zC(e)||t>=3)return!1;let r=f9(t);return d9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await BC(r,n)&&!this.deps.isDisposed()}fail(e,t){IC(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function f9(e){return 1e3*2**(e-1)}function owe(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){d9.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 p9=r(`scoop-context`);var swe=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=Kn(e),this.owner={kind:Nn(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 nwe({store:r??null,canonical:c?{store:c,identity:{key:Or(e),workUnitId:e.jid,workspaceId:Dr(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:zn(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 _ie({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new iie({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new aie({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new gie({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 awe({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 ySe(this.unit,this.scoop,Dn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Un(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 twe({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:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});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`),p9.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);p9.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(die(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),iwe(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(owe(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=rwe(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(){u9(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 Gi(this.scoop)?!0:this.unit.parentId===null&&p(`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:on,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(!(this.unit.parentId!==null&&!p(`memory-v2`)))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-CpwRZg6K.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o?{transcriptPath:o.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-CpwRZg6K.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){p9.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 uie(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=pie(this.agent,this.scoop))}async reloadSkills(){this.agent&&await hie(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?QC()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,mie(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),u9(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||UC(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||VC(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 m9=r(`scoop-lifecycle-manager`);var cwe=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 NC(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))??Dn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return kn(t.values(),e)??Dn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){m9.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 wr))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`)m9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{m9.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=Kn(t).policy.filesystem;if(a.kind===`restricted`){let e=wn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new wr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:cee(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 swe(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=>{m9.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&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),m9.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);m9.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),m9.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 m9.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(m9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){m9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){m9.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`)),m9.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(Hn(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=Fn(e.folder,n);r!==e.folder&&(m9.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),m9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&hC(`spawn`,e.folder)}catch(n){m9.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){m9.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=>{m9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(Mn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Vn(t):void 0)??aC();n&&Pn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of mee(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&Dn(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=>{m9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Or(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{m9.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&&m9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),m9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){m9.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;Pn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Pn(n,r),this.getContext(e)?.updateModel(),m9.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();m9.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=>{m9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),m9.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;lee(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){m9.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}=Kn(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}),hC(`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 An(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?(t,n)=>i.scheduleScoopWait(t,n,e):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:Zn(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,Tn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(Tn(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(m9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),hC(`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`),Kn(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){m9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{m9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const h9=r(`scoop-message-router`);var lwe=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(h9.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){h9.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}`);hC(`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),h9.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);h9.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){h9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){h9.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(h9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){h9.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{h9.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);h9.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);h9.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,h9.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){h9.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){h9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){h9.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(h9.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){h9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){h9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Br($r(Wr(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){h9.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}: ${oee(e.content,e.attachments)}`).join(`
|
|
5006
|
+
`),l=s.flatMap(e=>see(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Br($r(Wr(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);h9.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=>{h9.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=>{h9.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),h9.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=>{h9.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=>{h9.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(),h9.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 g9=r(`orchestrator`),uwe={decision:`deny`};var dwe=class{scoops=new Map;workUnits=new Ar(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new QS({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new AC({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 OC({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new SC({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 uC({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=>Jr(e),saveMessage:e=>Vr(e)});lickRegistry=new tC({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 lwe({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=>Vr(e),deleteMessage:e=>Ur(e),clearMessagesForScoop:e=>Zr(e),clearAllMessages:()=>Yr(),getMessagesSince:(e,t,n)=>qr(e,t,n),setState:(e,t)=>zr(e,t)},isExternalLickChannel:tv});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new cwe({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=>Rr(e),deleteScoop:e=>Xr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>te(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,n)=>this.scheduleScoopWait(e,t,n),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 oC(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new db({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 Ey(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new iC(e,t),await this.modelPolicyFile.init(),n(),hee()),n,{stagePrefix:`orchestrator-init`})}async init(e){await gee(),this.sharedFs=await oC(e=>Cr.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new K_,this.conversationStore=new SS,this.fsWatcher=new Sr,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=>Bn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Hn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Kr(`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)=>{g9.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(),g9.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);g9.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}`)}xee(e=>this.getSessionCostsForCommand(e)),See(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-CxT001UE.js`).then(e=>e.t);return e()}),this.unregisterExportService=pb(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Y_;try{await gS({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){g9.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=Bn(e)?null:t??null;try{await Rr(e)}catch(t){g9.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=>!Mn(e));if(e.length===0)return;let t=aC(),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?Vn(n):void 0)??t;if(r){Pn(e,r);try{await Rr(e)}catch(t){g9.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=Jn(Xn(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,n){return this.completionService.scheduleScoopWait(e,t,n)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-Ce8FHRYj.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:Zn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(g9.warn(`Guest approval before SudoManager init — failing closed`),uwe)}})}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)}getDefaultConeFs(){let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null}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 Rr(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 Dn(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 fee(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return kn(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 Cr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await qS(this.sharedFs).catch(e=>{g9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new db({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 Ey(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new iC(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),g9.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 Jr(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-B4efpvB9.js`).then(e=>e.r),r=await n(this.sharedFs);return[...t,...r.map(wee)]}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&&g9.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,g9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Y_,t=this.sharedFs;return new Ix({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:tS(),snapshotStore:{read:e=>qx(t,e),write:(e,n)=>Kx(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.154.6`})}};const _9=r(`workflow-run-manager`),v9=`/shared/workflow-runs`,y9=1e3;function fwe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function pwe(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){_9.warn(`observeRun handler threw`,e)}},i=(e,n)=>vwe(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=fwe(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),gwe(t,n);let f=i(a.ctx,c),p=_we(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=>_9.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=`${v9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(v9,{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);_9.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`?hwe(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){_9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function mwe(e){let t=pwe(e);return globalThis[f7]=t,_9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function hwe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function gwe(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 _we(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 vwe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?ywe(n,t,a?.args??[],r):e===`agent`?bwe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function ywe(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>y9&&i.logs.splice(0,i.logs.length-y9),r()}return{stdout:``,stderr:``,exitCode:0}}async function bwe(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 xwe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function Swe(e,t,n){let r=Cwe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=wwe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Cwe(e){let t=new Map;return b9(t,e.discoveryOrigin),b9(t,e.discoveryUrl),[...t.values()]}function b9(e,t){if(t){x9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);x9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!xwe.has(e)))x9(e,t,1,`substring`)}catch{}}}function x9(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 wwe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Ewe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)Twe(a,e)&&(r+=e.weight*o)}return r}function Twe(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 Ewe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Dwe=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=w9(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:C9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===C9)throw new lr(`ENOTDIR`,`not a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);return S9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new lr(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=w9(e);if(t.length===1&&t[0]===C9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new lr(`EISDIR`,`is a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new lr(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new lr(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=w9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===C9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new lr(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new lr(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new lr(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new lr(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new lr(`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 lr(`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:E9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:D9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5007
|
+
`}renderProcFile(e,t){if(e===1)return Mwe(t);let n=this.pm.get(e);switch(t){case`status`:return Owe(n);case`cmdline`:return kwe(n);case`cwd`:return Awe(n);case`stat`:return jwe(n)}}};const S9=[`status`,`cmdline`,`cwd`,`stat`],C9=`table`;function w9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function T9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Owe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${E9(e.status)} (${e.status})`,`Owner:\t${D9(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(`
|
|
5008
5008
|
`)+`
|
|
5009
|
-
`}function
|
|
5010
|
-
`}function
|
|
5011
|
-
`}function E9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function D9(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function
|
|
5009
|
+
`}function kwe(e){return e.argv.join(`\0`)+`\0`}function Awe(e){return e.cwd+`
|
|
5010
|
+
`}function jwe(e){return[e.pid,`(${e.kind})`,E9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
5011
|
+
`}function E9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function D9(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function Mwe(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
|
|
5012
5012
|
`)+`
|
|
5013
5013
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5014
5014
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5015
|
-
`}}function
|
|
5016
|
-
`,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 Hwe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-CDToX4F0.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BJU2QL9q.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 Uwe(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 my(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})},{...Wwe(t),isOwnTab:fy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Wwe(e){let t=ge();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:()=>hy()}}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-B9S80wQd.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-BDyGIOIb.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 Kwe(){_ee(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-B0CnEfsD.js`);return e()})}function qwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B0CnEfsD.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 Jwe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-DBtF-C4h.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 Ywe(e){return e===`node-rest`}function Xwe(e,t,n,r){import(`./gelatiere-unit-Dem3bPJm.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!p(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-CcLPnD5F.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function Zwe(e,t){if(!e)return()=>{};import(`./memory-curation-seam-UdyrM1Mx.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return p(`memory-v2`)&&import(`./memory-health-MhSOmzAf.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function Qwe(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Sn(e,t,e.getSessionStore())}async function $we(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Kwe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Lwe(t,n,r,i,e);if(s(`orchestrator-ready`),Qwe(l,f,o),f)try{await f.mountInternal(`/proc`,new Ewe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Rwe(l,e,o);s(`lick-manager-ready`),f&&Bwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),O9().__slicc_lickManager=m,Xwe(l,m,f,o);let h=Zwe(f,o),{wsBridge:g,wsRegistry:_}=await Vwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});O9().__slicc_wsSubscribers=_;let v=Ywe(p.adapter)?await Hwe(m,o,e.localLickWsUrl??null,f):null,y=Uwe(n,m,o,e.appPageUrl);f&&Gwe(f,m,o),a||await zwe(l),s(`cone-bootstrapped`),f&&qwe(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await Jwe(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Mwe({nonce:e.syncFsChannelNonce}).dispose);let C=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){C||(C=!0,await eTe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:b,memoryHealthStop:h,scriptCatalogDispose:x,lickWsBridgeStop:v,navigationWatcherStop:y,syncFsResponderDispose:S,sharedFs:f,wsRegistry:_,wsBridge:g,processManager:c,lickManager:m,browser:n,log:o}))}}}async function eTe(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.memoryHealthStop?.(),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)}tTe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function tTe(e){let t=O9();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[f7]}const k9=`x-bypass-llm-proxy`;function nTe(e,t,n){return t?(r,i)=>{if(!rTe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(k9)||a.set(k9,`1`),e(r,{...i,headers:a})}:e}function rTe(e,t,n){if(aTe(e,t))return!0;let r=n?.()??null;return r?iTe(e,r,t):!1}function iTe(e,t,n){let r=A9(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 aTe(e,t){let n=A9(e);try{return new URL(n,t).origin===t}catch{return!0}}function A9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function oTe(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 sTe=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(!cTe(e)||e.source!==`panel`)return;let t=e.payload;lTe(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=ho(y(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?j9(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,j9(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 cTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function j9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function lTe(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 uTe=class extends A7{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 dTe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new sTe({transport:t,processManager:i,createShell:(a,o)=>new uTe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Nr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function fTe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function pTe(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function mTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function hTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function M9(e){return fTe(e)||pTe(e)||mTe(e)||hTe(e)}function N9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return gTe(e);if(typeof e==`object`)return _Te(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function P9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return L9(e)??R9(e);let t=N9(e);if(t!==void 0)return F9(t)}function F9(e){let t=e.trim();if(!t)return e;let n=I9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=I9(t.slice(r,i+1));if(e)return e}return e}function gTe(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function _Te(e){let t=L9(e),n=R9(e);return n&&t?`${n}: ${t}`:t??n}function I9(e){if(e.startsWith(`{`))try{return L9(JSON.parse(e))}catch{return}}function L9(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function R9(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let z9=null,B9=!1;function vTe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function yTe(e){return vTe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function bTe(e={}){if(!B9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){lSe(xTe),mC(STe),FC(V9);try{let t=yTe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(z9=(await import(`./rum-worker-CwmNSpjO.js`)).default,U9(self)):t===`extension`?(z9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&U9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),ETe(),wTe(),z9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),B9=!0,z9&&z9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function xTe(e){z9?.(`fill`,{source:e})}function V9(e,t){let n=H9(t);n!==null&&z9?.(`error`,{source:e,target:n})}function STe(e,t,n){if(e===`error`){let e=H9(n);if(e===null)return;z9?.(`error`,{source:`scoop:${t}`,target:e});return}z9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function CTe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function H9(e){let t=N9(e);if(t===void 0)return e==null?void 0:null;if(M9(t))return null;let n=P9(e)??F9(t);return M9(n)?null:G9(n)}function U9(e){e.addEventListener(`error`,e=>{let t=e;V9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{V9(`js`,e.reason)})}function W9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function wTe(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0))}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5017
|
-
`).filter(e=>!
|
|
5018
|
-
`).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){let t=typeof e==`string`?e:P9(e)??N9(e);if(typeof t!=`string`)return{kind:`absent`};let n=F9(t);if(n===`[object Object]`)return{kind:`noise`};let r=G9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function TTe(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||n.kind===`noise`&&e.source===`undefined error`)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 ETe(){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=TTe(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 DTe(e){let t=new OTe(e);return t.start(),{stop:()=>t.dispose()}}var OTe=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(!kTe(e)||e.source!==`panel`)return;let t=e.payload;if(ATe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(jTe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(MTe(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{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new lr(`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 readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new lr(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new lr(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}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(NTe(e.type),e.requestId,new lr(`EACCES`,`vfs-rpc-host has no writable backend wired`),PTe(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 lr(`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 lr(`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 lr(`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 kTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ATe(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 jTe(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 MTe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function NTe(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 PTe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof lr?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function FTe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=nTe(e.bind(globalThis),t,ITe)}function ITe(){let e=we();if(!e)return null;try{return new URL(e).origin}catch{return null}}function LTe(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 RTe=oTe(e=>VTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&RTe.handle(e.data)});function zTe(e){let t=Ps(e.pageBuildId,`6.154.5-mu2j1goz`);return()=>{t&&V9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.154.5-mu2j1goz`)}}function BTe(e){FTe(),P(e.localApiBaseUrl??null),N(e.bridgeToken??null),$q(e.syncFsBridgeEnabled??!1),Qee(e.pageLoadedAt??null),M(e.extensionDelegateId??null),LTe(e.localStorageSeed??{}),e.flagFloat&&xs(e.flagFloat)}async function VTe(e){js(e.instanceId);let t=zTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{BTe(e),bTe().then(t).catch(()=>{}),await g(),n(`providers-registered`);let r=Yc(e.kernelPort),i=new Zv(r),a=Zv.createCallbacks(i),o=new Xc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new hs(o);Y9=await $we({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-Bur-XBNy.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 ete)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(vs(u));let p=await UTe({host:Y9,transport:r,browser:s,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){HTe(e.kernelPort,t)}}function HTe(e,t){Ns(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 UTe(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=dTe({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=DTe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await WTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function WTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DOu9EHnU.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DEK8DT-z.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())});
|
|
5015
|
+
`}}function Nwe(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(FU(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(!AU(n.token))return;let a=i.get(n.id);if(a){r({type:IU,id:n.id}),a.result&&r({type:LU,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:IU,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:LU,id:n.id,...e})};(VU(n)?WU(n):PU(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 O9(){return globalThis}function Pwe(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 Fwe(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 Iwe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Lwe(e,t)}async function Lwe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Dn(r),a=e.type===`discovery`&&!e.targetScoop?Swe(e,i.filter(Cy),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?Zc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Cy(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}if(e.type===`navigate`){try{let{shouldSkipNavigateUpskill:r}=await import(`./upskill-lick-skip-Coa1zDvD.js`);if(await r(e,typeof t.getDefaultConeFs==`function`?()=>t.getDefaultConeFs():()=>null)){n.debug?.(`dropping navigate·upskill lick; advertised skill already installed at that commit`);return}}catch(e){n.warn(`navigate·upskill skip check failed; raising card`,e)}e.lickId=t.registerNavigateLick(e)}else 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=hv(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=Pwe(e),l=Fwe(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 Rwe(e,t,n,r,i){let a=new Ta,o=new dwe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=rn(),c=i.capabilityBroker??Py(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),pr(c),O9().__slicc_pm=a,aJ(sJ()),O9().__slicc_browser=t,await n.bind(o,t);let l=Fr(()=>n.emitTrayRuntimeStatus()),u=Mv(()=>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 zwe(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-BzdZ_evm.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source-CxT001UE.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??Iwe,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Bwe(e){let t=e.getScoops();Dn(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 Vwe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;mwe({sharedFs:i,getStartingRoot:e=>{let n=Dn(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)=>lJ(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p7().slice(10,22),splitResult:(e,t)=>m7(e,t)})}async function Hwe(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))+`
|
|
5016
|
+
`,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 Uwe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-CDToX4F0.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BJU2QL9q.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 Wwe(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 my(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})},{...Gwe(t),isOwnTab:fy(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Gwe(e){let t=ge();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:()=>hy()}}function Kwe(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-Be7iHZMh.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-BDyGIOIb.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 qwe(){_ee(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-Cz-hPWu6.js`);return e()})}function Jwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Cz-hPWu6.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-DBtF-C4h.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 Xwe(e){return e===`node-rest`}function Zwe(e,t,n,r){import(`./gelatiere-unit-Dem3bPJm.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!p(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-CcLPnD5F.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function Qwe(e,t){if(!e)return()=>{};import(`./memory-curation-seam-gS_uRoYt.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return p(`memory-v2`)&&import(`./memory-health-MhSOmzAf.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function $we(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}Sn(e,t,e.getSessionStore())}async function eTe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);qwe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Rwe(t,n,r,i,e);if(s(`orchestrator-ready`),$we(l,f,o),f)try{await f.mountInternal(`/proc`,new Dwe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await zwe(l,e,o);s(`lick-manager-ready`),f&&Vwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),O9().__slicc_lickManager=m,Zwe(l,m,f,o);let h=Qwe(f,o),{wsBridge:g,wsRegistry:_}=await Hwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});O9().__slicc_wsSubscribers=_;let v=Xwe(p.adapter)?await Uwe(m,o,e.localLickWsUrl??null,f):null,y=Wwe(n,m,o,e.appPageUrl);f&&Kwe(f,m,o),a||await Bwe(l),s(`cone-bootstrapped`),f&&Jwe(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await Ywe(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Nwe({nonce:e.syncFsChannelNonce}).dispose);let C=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:m,sharedFs:f??null,processManager:c,capabilityBroker:p,async dispose(){C||(C=!0,await tTe({unsubLeader:u,unsubFollower:d,bshWatchdogStop:b,memoryHealthStop:h,scriptCatalogDispose:x,lickWsBridgeStop:v,navigationWatcherStop:y,syncFsResponderDispose:S,sharedFs:f,wsRegistry:_,wsBridge:g,processManager:c,lickManager:m,browser:n,log:o}))}}}async function tTe(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.memoryHealthStop?.(),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)}nTe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function nTe(e){let t=O9();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[f7]}const k9=`x-bypass-llm-proxy`;function rTe(e,t,n){return t?(r,i)=>{if(!iTe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(k9)||a.set(k9,`1`),e(r,{...i,headers:a})}:e}function iTe(e,t,n){if(oTe(e,t))return!0;let r=n?.()??null;return r?aTe(e,r,t):!1}function aTe(e,t,n){let r=A9(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 oTe(e,t){let n=A9(e);try{return new URL(n,t).origin===t}catch{return!0}}function A9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function sTe(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 cTe=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(!lTe(e)||e.source!==`panel`)return;let t=e.payload;uTe(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=ho(y(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?j9(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,j9(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 lTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function j9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function uTe(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 dTe=class extends A7{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 fTe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new cTe({transport:t,processManager:i,createShell:(a,o)=>new dTe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Nr},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function pTe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function mTe(e){if(typeof e!=`string`||!e)return!1;let t=e.toLowerCase();return t.includes(`the provided model identifier is invalid`)||t.includes(`model not allowed`)}function hTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function gTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function M9(e){return pTe(e)||mTe(e)||hTe(e)||gTe(e)}function N9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return _Te(e);if(typeof e==`object`)return vTe(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function P9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return L9(e)??R9(e);let t=N9(e);if(t!==void 0)return F9(t)}function F9(e){let t=e.trim();if(!t)return e;let n=I9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=I9(t.slice(r,i+1));if(e)return e}return e}function _Te(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function vTe(e){let t=L9(e),n=R9(e);return n&&t?`${n}: ${t}`:t??n}function I9(e){if(e.startsWith(`{`))try{return L9(JSON.parse(e))}catch{return}}function L9(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function R9(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let z9=null,B9=!1;function yTe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function bTe(e){return yTe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function xTe(e={}){if(!B9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){uSe(STe),mC(CTe),FC(V9);try{let t=bTe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(z9=(await import(`./rum-worker-CwmNSpjO.js`)).default,U9(self)):t===`extension`?(z9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&U9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),DTe(),TTe(),z9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),B9=!0,z9&&z9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function STe(e){z9?.(`fill`,{source:e})}function V9(e,t){let n=H9(t);n!==null&&z9?.(`error`,{source:e,target:n})}function CTe(e,t,n){if(e===`error`){let e=H9(n);if(e===null)return;z9?.(`error`,{source:`scoop:${t}`,target:e});return}z9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function wTe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function H9(e){let t=N9(e);if(t===void 0)return e==null?void 0:null;if(M9(t))return null;let n=P9(e)??F9(t);return M9(n)?null:G9(n)}function U9(e){e.addEventListener(`error`,e=>{let t=e;V9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{V9(`js`,e.reason)})}function W9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function TTe(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0))}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5017
|
+
`).filter(e=>!wTe(e)).join(`
|
|
5018
|
+
`).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){let t=typeof e==`string`?e:P9(e)??N9(e);if(typeof t!=`string`)return{kind:`absent`};let n=F9(t);if(n===`[object Object]`)return{kind:`noise`};let r=G9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function ETe(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||n.kind===`noise`&&e.source===`undefined error`)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 DTe(){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=ETe(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 OTe(e){let t=new kTe(e);return t.start(),{stop:()=>t.dispose()}}var kTe=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(!ATe(e)||e.source!==`panel`)return;let t=e.payload;if(jTe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(MTe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(NTe(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{if(t===`binary`&&Number.isInteger(e.start)){let t=await this.readFileWindow(e.path,e.start,e.end);this.sendBinaryReadResult(e.requestId,e.path,t);return}let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`)this.sendBinaryReadResult(e.requestId,e.path,n);else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new lr(`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 readFileWindow(e,t,n){let r=n??(await this.client.stat(e)).size;if(this.client.readFileRange)return this.client.readFileRange(e,t,r);let i=await this.client.readFile(e,{encoding:`binary`});if(!(i instanceof Uint8Array))throw new lr(`EIO`,`readFile(binary) did not return Uint8Array`,e);return new Uint8Array(i.subarray(t,Math.min(r,i.byteLength)))}sendBinaryReadResult(e,t,n){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e,new lr(`EIO`,`readFile(binary) did not return Uint8Array`),t);return}let r={type:`vfs-read-file-result`,requestId:e,ok:!0,encoding:`binary`,data:n},i=n.buffer,a=typeof ArrayBuffer<`u`&&i instanceof ArrayBuffer?[i]:void 0;this.transport.send(r,a)}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(PTe(e.type),e.requestId,new lr(`EACCES`,`vfs-rpc-host has no writable backend wired`),FTe(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 lr(`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 lr(`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 lr(`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 ATe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function jTe(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 MTe(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 NTe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function PTe(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 FTe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof lr?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function ITe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=rTe(e.bind(globalThis),t,LTe)}function LTe(){let e=we();if(!e)return null;try{return new URL(e).origin}catch{return null}}function RTe(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 zTe=sTe(e=>HTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&zTe.handle(e.data)});function BTe(e){let t=Ps(e.pageBuildId,`6.154.6-mu2lvg3m`);return()=>{t&&V9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.154.6-mu2lvg3m`)}}function VTe(e){ITe(),P(e.localApiBaseUrl??null),N(e.bridgeToken??null),$q(e.syncFsBridgeEnabled??!1),Qee(e.pageLoadedAt??null),M(e.extensionDelegateId??null),RTe(e.localStorageSeed??{}),e.flagFloat&&xs(e.flagFloat)}async function HTe(e){js(e.instanceId);let t=BTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{VTe(e),xTe().then(t).catch(()=>{}),await g(),n(`providers-registered`);let r=Yc(e.kernelPort),i=new Zv(r),a=Zv.createCallbacks(i),o=new Xc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new hs(o);Y9=await eTe({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-Bur-XBNy.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 ete)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(vs(u));let p=await WTe({host:Y9,transport:r,browser:s,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){UTe(e.kernelPort,t)}}function UTe(e,t){Ns(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 WTe(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=fTe({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=OTe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await GTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function GTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DOu9EHnU.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-DEK8DT-z.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())});
|