sliccy 6.158.0 → 6.158.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/.vite/manifest.json +167 -167
- package/dist/ui/assets/{account-store-M2UwsoRK.js → account-store-D7eN4OXk.js} +1 -1
- package/dist/ui/assets/{account-store-5prBUpgd.js → account-store-KxT17gu_.js} +1 -1
- package/dist/ui/assets/{adobe-CVqIgi2n.js → adobe-F_tfp998.js} +1 -1
- package/dist/ui/assets/{adobe-DjjZw4mf.js → adobe-y_m9GLTZ.js} +1 -1
- package/dist/ui/assets/{agent-bridge-CK3k8fpK.js → agent-bridge-BkHuOfQg.js} +1 -1
- package/dist/ui/assets/{agent-panels-BTBIlF8V.js → agent-panels-ZTL0xD08.js} +1 -1
- package/dist/ui/assets/{apply-layout-CsIl1zKW.js → apply-layout-DSd09wMF.js} +1 -1
- package/dist/ui/assets/{apps-BTcdiAg7.js → apps-yo7bohdm.js} +1 -1
- package/dist/ui/assets/{azure-openai-CU7zbhow.js → azure-openai-BmDolwc9.js} +1 -1
- package/dist/ui/assets/{azure-openai-BMWNMNHG.js → azure-openai-CrO9XDqv.js} +1 -1
- package/dist/ui/assets/{backend-hostfs-DUFy5JMq.js → backend-hostfs-B_iS_HNp.js} +1 -1
- package/dist/ui/assets/{budget-usage-source-Cx-X3dby.js → budget-usage-source--zsr_0LN.js} +1 -1
- package/dist/ui/assets/{cdp--mXMJgCZ.js → cdp-DVzfiM9e.js} +1 -1
- package/dist/ui/assets/{cerebras-CMwQUqY2.js → cerebras-BwCLBghg.js} +1 -1
- package/dist/ui/assets/{cerebras-BZh4NimK.js → cerebras-Dss1K_Le.js} +1 -1
- package/dist/ui/assets/{composer-speech-BwG9nMFA.js → composer-speech-NcfWb8wQ.js} +1 -1
- package/dist/ui/assets/{connect-surface-BL2dDylV.js → connect-surface-Cd0lpgxe.js} +1 -1
- package/dist/ui/assets/{directed-approval-DFoMRwaG.js → directed-approval-DVTvTDeB.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-CxIM0vni.js → ensure-speech-assets-DBH5XTaz.js} +1 -1
- package/dist/ui/assets/{fs-C-VGcymB.js → fs-CKF7L1oq.js} +1 -1
- package/dist/ui/assets/{fs-C5_HauPu.js → fs-wraTgXdT.js} +2 -2
- package/dist/ui/assets/{github-C2auwTfN.js → github-RwjN5lkE.js} +2 -2
- package/dist/ui/assets/{github-auth-CQ0OVCLm.js → github-auth-PgzNFXb7.js} +1 -1
- package/dist/ui/assets/{github-DtjbS44I.js → github-c4Dzmjps.js} +1 -1
- package/dist/ui/assets/{github-copilot-CjMXqAFV.js → github-copilot-BcZ7hCvs.js} +1 -1
- package/dist/ui/assets/{github-copilot-CJW_3ivx.js → github-copilot-Cuvcp5Rx.js} +1 -1
- package/dist/ui/assets/{github-install-Dbz8WLRF.js → github-install-CCiLZQKP.js} +1 -1
- package/dist/ui/assets/{github-zip-BWd2XSNT.js → github-zip-C3GODUL3.js} +1 -1
- package/dist/ui/assets/{hear-BWKP36jm.js → hear-DwTK5tX6.js} +1 -1
- package/dist/ui/assets/{help-CW6zgkXv.js → help-CZ_jut-Q.js} +1 -1
- package/dist/ui/assets/{installer-EvwVnAiv.js → installer-CeDnN_9I.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-CjRTKYQi.js → js-realm-worker-BfqOZWvd.js} +1 -1
- package/dist/ui/assets/{kernel-worker-Bxh2W6Eg.js → kernel-worker-DF3tsip4.js} +33 -33
- package/dist/ui/assets/{local-llm-B5PHgroX.js → local-llm-Cw7-Quw-.js} +1 -1
- package/dist/ui/assets/{local-llm-BFEopou-.js → local-llm-DkZRyZIp.js} +1 -1
- package/dist/ui/assets/{main-BKm__arh.js → main-ONTk0ouk.js} +3 -3
- package/dist/ui/assets/{main-cherry-mTSDofpE.js → main-cherry-pPieUceA.js} +1 -1
- package/dist/ui/assets/{memory-curation-seam-BjsquXL_.js → memory-curation-seam-BysRStGd.js} +1 -1
- package/dist/ui/assets/{mount-vtaT3M8u.js → mount-BvqonRdx.js} +3 -3
- package/dist/ui/assets/{mount-YLXOTtO9.js → mount-DSkdtHPr.js} +1 -1
- package/dist/ui/assets/{mount-recovery-CB_vvrUl.js → mount-recovery-B41gr65n.js} +1 -1
- package/dist/ui/assets/{new-session-B2WIcSWw.js → new-session-CXa1CFW4.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DEpAPtSs.js → oauth-bootstrap-DJTSVccz.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-WbBdV53F.js → onboarding-orchestrator-CAOZ5FNB.js} +1 -1
- package/dist/ui/assets/{openai-codex-CEI5zU7f.js → openai-codex-Cf_vJHJ6.js} +1 -1
- package/dist/ui/assets/{openai-codex-C_VkBkYe.js → openai-codex-D2RiGTxw.js} +1 -1
- package/dist/ui/assets/{openrouter-CmhZr0Cx.js → openrouter-BEXCQv3t.js} +1 -1
- package/dist/ui/assets/{openrouter-B-jGPyZA.js → openrouter-CWQfZQKE.js} +1 -1
- package/dist/ui/assets/{openrouter-free-Da87rNN-.js → openrouter-free-BNMjowpG.js} +1 -1
- package/dist/ui/assets/{openrouter-free-C8Q34WKV.js → openrouter-free-EPf0YafV.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-xVmgHioX.js → openrouter-oauth-CcOSnDNi.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-CqZuO3jx.js → openrouter-oauth-DyHwOlwL.js} +1 -1
- package/dist/ui/assets/{opfs-mount-DSbuqvnM.js → opfs-mount-8-wz4ji1.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-C9hl9MX6.js → panel-rpc-handlers-DHoRbEwU.js} +2 -2
- package/dist/ui/assets/{panelize-shell-DTKYQ5t2.js → panelize-shell-D9tDs-AV.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-DMZFZsub.js → pi-edit-execution-BzX4faZ8.js} +1 -1
- package/dist/ui/assets/{provider-mwdQ508x.js → provider-BJ3CneJK.js} +2 -2
- package/dist/ui/assets/{provider-bbDpf9nd.js → provider-JhY8VUoS.js} +1 -1
- package/dist/ui/assets/provider-settings-dOfr4Jis.js +1 -0
- package/dist/ui/assets/provider-store-access-BSmbWmyl.js +1 -0
- package/dist/ui/assets/provider-store-access-BbOEpFKm.js +1 -0
- package/dist/ui/assets/{providers-u1uymOJS.js → providers-CFMeCih2.js} +2 -2
- package/dist/ui/assets/{providers-DtFJa9_W.js → providers-DG3GRO0g.js} +1 -1
- package/dist/ui/assets/{quick-llm-H465QKpV.js → quick-llm--hJWl7Jr.js} +1 -1
- package/dist/ui/assets/{recovery-screen-CVY6s2RJ.js → recovery-screen-DA7RUpNw.js} +1 -1
- package/dist/ui/assets/{run-DypsPxOj.js → run-BMeDofYZ.js} +1 -1
- package/dist/ui/assets/{run-D15RdZhl.js → run-Cs70ONoW.js} +1 -1
- package/dist/ui/assets/{run-CH658S49.js → run-DePgFtOr.js} +2 -2
- package/dist/ui/assets/{session-jsonl-BIskVnhX.js → session-jsonl-BVeHlpsk.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-PX1BkYi_.js → setup-feature-flags-remote-Be_G1aKz.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-Bbwuw7D-.js → silent-renew-backoff-D5iqxWam.js} +1 -1
- package/dist/ui/assets/{skills-RIkRI7nY.js → skills-C058JDJA.js} +1 -1
- package/dist/ui/assets/slicc-version-DFbfAxmg.js +1 -0
- package/dist/ui/assets/{snapshot-Dcq6pk1-.js → snapshot-C0jMXzwY.js} +1 -1
- package/dist/ui/assets/{snapshot-features-B6PVya4J.js → snapshot-features-BrjTvoVG.js} +1 -1
- package/dist/ui/assets/{soundscape-JLvhv6J7.js → soundscape-Bwf0RsVL.js} +1 -1
- package/dist/ui/assets/{speak-DCcJ3RQV.js → speak-BEZMIDR3.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-C1vO3oW3.js → sprinkle-manager-dx8JwFUg.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-BjAbXlKm.js → sprinkle-renderer-bOeNIrR0.js} +1 -1
- package/dist/ui/assets/{state-DUXkItYp.js → state-B0LE2MQY.js} +1 -1
- package/dist/ui/assets/{store-BV-ot8zB.js → store-Ckv7LyPo.js} +1 -1
- package/dist/ui/assets/{store-CyvdDoXd.js → store-sD4MH5HN.js} +1 -1
- package/dist/ui/assets/{sudo-Bt2gvB1F.js → sudo-DnHIhPQc.js} +1 -1
- package/dist/ui/assets/{sync-dialog-CCGFI9ga.js → sync-dialog-CZWYu4ww.js} +1 -1
- package/dist/ui/assets/{transformers-env-Q-Up6Nqm.js → transformers-env-BmiJwlBu.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-BSXy-_bR.js → tray-sidecar-CzeMGM61.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-BEqd3zwB.js → upgrade-detection-egIJU9Tj.js} +1 -1
- package/dist/ui/assets/{upskill-lick-skip-awi-Htq_.js → upskill-lick-skip-DBBqtrXa.js} +1 -1
- package/dist/ui/assets/{voice-reply-DTvy0SLg.js → voice-reply-wkpyBnBq.js} +1 -1
- package/dist/ui/assets/{wc-attach-zIsuaQp0.js → wc-attach-CJ_1LM59.js} +2 -2
- package/dist/ui/assets/{wc-extension-zeTUZgwk.js → wc-extension-D-NpYYTA.js} +2 -2
- package/dist/ui/assets/{wc-follower-teeoShBo.js → wc-follower-Bazf_uJP.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-DtyHM2F8.js → wc-follower-oauth-DdJI_wlo.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-BTRF1iEE.js → wc-gelatiere-gQcttN2b.js} +1 -1
- package/dist/ui/assets/{wc-live-0eTZEuFT.js → wc-live-DV35XuXH.js} +5 -5
- package/dist/ui/assets/{wc-nav-BxbafbwT.js → wc-nav-CncYSiKZ.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-DMkJf4xP.js → wc-onboarding-DbBSQGPn.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-cF2zg9og.js → wc-placeholder-CFy9WBEV.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-DfEthIMs.js → wc-secret-request-Cc8DepP_.js} +1 -1
- package/dist/ui/assets/{wc-settings-CKKSzA6l.js → wc-settings-B3-9zu54.js} +3 -3
- package/dist/ui/assets/{wc-shell-0H_44OJQ.js → wc-shell-Cy_9M5oX.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-DYZiWcru.js → wc-shortcut-config-CK8CTDCw.js} +1 -1
- package/dist/ui/assets/{wc-shortcuts-BCK8BR2m.js → wc-shortcuts-D6QU__Zr.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-CRkk-gCD.js → wc-sprinkles-C7YifBIt.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-N7gvzjxZ.js → wc-transcript-export-DbKzb44U.js} +2 -2
- package/dist/ui/assets/{wc-tray-DIvYkZVn.js → wc-tray-Chhjrppk.js} +4 -4
- package/dist/ui/assets/welcome-detection-BNAVpTRM.js +1 -0
- package/dist/ui/assets/{whisper-session-CAQ3-gd2.js → whisper-session-CxBK9wBI.js} +2 -2
- package/dist/ui/assets/{xai-grok-DPwplgue.js → xai-grok-BW4eVIlM.js} +1 -1
- package/dist/ui/assets/{xai-grok-C-NsOhNx.js → xai-grok-COvcgYJc.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-B4m0TBa3.js +0 -1
- package/dist/ui/assets/provider-store-access-B7Bi-NTa.js +0 -1
- package/dist/ui/assets/provider-store-access-Du2v7_2b.js +0 -1
- package/dist/ui/assets/slicc-version-D6PCo87w.js +0 -1
- package/dist/ui/assets/welcome-detection-Bc82v6WL.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{t as n}from"./logger-LESFN7Hj.js";import{a as r,i,n as a,o,r as s,t as c}from"./snapshot-Dcq6pk1-.js";import{n as l,r as u,t as d}from"./panel-rpc-BPwAqRch.js";import{n as f,r as p,t as m}from"./feature-flags-BIRXJe0o.js";import{a as h,t as g}from"./providers-DtFJa9_W.js";import{r as _,t as v}from"./base64-DzRgusa4.js";import{n as y}from"./bridge-protocol-DdqxTTSu.js";import{t as b}from"./content-type-_QKWY0B2.js";import{a as x,c as S,i as C,l as w,o as T,r as E,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as ie,d as eee,f as ae,g as oe,h as tee,i as se,m as ce,p as le,u as ue,v as de,x as fe,y as pe}from"./account-store-5prBUpgd.js";import{a as me,l as he,n as ge,o as nee}from"./proxied-fetch-DEK8DT-z.js";import{t as _e}from"./runtime-env-DadgceZk.js";import{t as ve}from"./slugify-BYJ6QVAt.js";import{i as ye}from"./archive-redaction-ByV7X5fs.js";import{r as be}from"./binary-cache-bSOhqXB1.js";import{i as xe,n as Se,r as Ce,t as we}from"./fetch-body-CuwTaJC_.js";import{a as ree,l as iee,o as Te,s as aee,t as Ee,u as oee}from"./api-endpoint-3qEcn7BY.js";import{$ as De,A as Oe,At as ke,B as Ae,C as je,Ct as Me,D as Ne,Dt as Pe,E as Fe,Et as Ie,F as see,H as Le,I as Re,J as ze,K as cee,L as lee,M as Be,Mt as D,N as Ve,Nt as He,O as uee,Ot as Ue,P as We,Q as Ge,R as Ke,St as qe,T as Je,Tt as Ye,U as Xe,V as Ze,W as Qe,X as $e,Y as et,Z as tt,_ as nt,_t as rt,a as it,at,b as ot,bt as dee,c as st,ct as O,d as ct,dt as fee,et as lt,f as ut,ft as dt,g as ft,gt as pt,h as pee,ht as mt,i as mee,it as ht,j as gt,jt as _t,k as vt,kt as yt,l as bt,lt as xt,m as St,mt as Ct,n as wt,nt as Tt,o as Et,ot as Dt,p as Ot,pt as k,q as kt,r as At,rt as jt,s as Mt,st as A,t as Nt,tt as Pt,u as Ft,ut as It,v as Lt,vt as Rt,w as zt,wt as Bt,x as Vt,xt as hee,y as Ht,yt as Ut,z as Wt}from"./build-BRNa03GH.js";import{a as gee}from"./models-4WTk3EBD.js";import{o as Gt,t as _ee}from"./compat-uEPf6-XW.js";import{a as vee,c as Kt,i as qt,l as yee,o as Jt,s as Yt,t as Xt,u as Zt}from"./core-DP-MJcag.js";import{t as bee}from"./__vite-browser-external-5eBdwsFd.js";import{n as xee,r as See}from"./attachments-u2K0aIPI.js";import{i as Qt,n as Cee,r as wee,t as Tee}from"./context-compaction-DRymamfD.js";import{n as Eee,t as Dee}from"./mime-types-D7IV6i7k.js";import{t as $t}from"./secrets-bridge-client-ZpBL1Zhl.js";import{t as en}from"./image-markers-DuyWsic3.js";import{i as tn,r as nn}from"./budget-usage-source-Cx-X3dby.js";import{a as rn,i as an,n as j,t as on}from"./path-utils-DNJG-zQf.js";import{a as sn,i as cn,o as ln,r as un,t as dn}from"./agent-bridge-CK3k8fpK.js";import{A as fn,C as pn,D as mn,E as hn,S as gn,T as _n,_ as vn,a as yn,c as bn,d as xn,f as Sn,g as Cn,h as wn,k as Tn,l as En,m as Dn,n as On,o as kn,p as Oee,r as kee,s as An,t as Aee,u as jn,v as jee,w as Mee,y as Nee}from"./record-YqlVEfh_.js";import{c as Pee,d as Mn,i as Nn,l as Pn,n as Fee,o as Fn,r as In,s as Iee,u as Ln}from"./descriptor-D-6Koktu.js";import{a as Lee,c as Ree,i as zee,l as Rn,o as Bee,r as Vee,s as Hee,u as Uee}from"./agent-message-to-chat-w7n13QEN.js";import{n as zn,t as Bn}from"./thinking-level-5x0UAu9N.js";import{n as Vn,t as M}from"./types-D8gIX-W-.js";import{i as Hn}from"./mount-index-CQfmUPuZ.js";import{a as Wee,c as Un,i as Gee,l as Kee,n as qee,o as Jee,r as Yee,s as Wn,u as Xee}from"./mount-YLXOTtO9.js";import{o as Gn}from"./mount-table-store-DrF_Ifaz.js";import{t as Kn}from"./remote-cache-BE5T1-53.js";import{i as Zee,n as qn,r as Jn}from"./fs-C-VGcymB.js";import{r as Yn,t as Qee}from"./mount-recovery-CB_vvrUl.js";import{r as Xn,t as Zn}from"./key-DExP84Xm.js";import{n as $ee,t as ete}from"./manager-CstXzWYQ.js";import{a as tte,c as nte,i as Qn,n as rte,o as ite,r as ate,s as ote}from"./lick-urls-BZVq_P3x.js";import{C as $n,D as ste,E as er,S as tr,_ as nr,a as rr,b as ir,d as ar,g as or,h as sr,m as cr,n as lr,o as ur,r as dr,s as fr,t as pr,u as mr,w as hr,y as gr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-CRZxBChd.js";import{n as _r,r as vr,t as yr}from"./slicc-version-D6PCo87w.js";import{a as br,i as xr,n as N,r as Sr,t as Cr}from"./browser-fOe3v0iv.js";import{t as P}from"./subcommand-flags-BZi7j78Q.js";import{n as wr,r as Tr,t as F}from"./subcommand-help-CgO7wRS5.js";import{a as Er,i as Dr,n as Or,r as kr}from"./cost-command-DlIH8zCh.js";import{_ as Ar,a as jr,c as Mr,d as Nr,f as Pr,g as Fr,h as Ir,i as Lr,l as Rr,m as zr,n as Br,o as Vr,p as Hr,r as Ur,s as Wr,t as Gr,u as Kr,v as qr}from"./sudoers-BdBYQPUn.js";import{a as Jr,i as Yr,n as Xr,o as Zr,r as Qr,s as $r}from"./skills-RIkRI7nY.js";import{a as ei,c as ti,i as ni,l as ri,n as ii,o as ai,r as oi,t as si}from"./types-BfwydWt7.js";import{n as ci,t as li}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as ui}from"./html-B_Hg2WOy.js";import{n as di,t as fi}from"./llm-session-id-BZyXP_j2.js";import{a as pi}from"./frozen-archive-format-B4efpvB9.js";import{n as mi,r as hi}from"./derive-BqbmiIL9.js";import{n as gi,t as _i}from"./cone-memory-budget-ieIsscyt.js";import{i as vi,r as yi}from"./browser-2rCVqcqy.js";import{a as bi}from"./gelatiere-constants-BYJlhm8R.js";import{n as xi}from"./safe-buffer-OLJ0qaLt.js";import{A as Si,B as Ci,C as wi,D as Ti,E as Ei,F as Di,G as Oi,H as ki,I as Ai,J as ji,K as Mi,L as Ni,M as cte,N as lte,O as Pi,P as ute,R as Fi,S as Ii,T as dte,U as fte,V as Li,W as pte,Y as mte,_ as hte,a as Ri,b as zi,c as Bi,d as gte,f as Vi,g as _te,h as vte,i as Hi,j as Ui,k as yte,l as Wi,m as Gi,n as Ki,o as qi,p as Ji,q as Yi,r as Xi,s as bte,t as Zi,u as Qi,v as xte,w as Ste,x as $i,y as Cte,z as ea}from"./isomorphic-git-DRUhmZ5u.js";import"./global-db-DJXlpNui.js";import{S as ta,_ as na,a as ra,b as ia,c as aa,d as wte,f as Tte,g as Ete,h as Dte,i as oa,l as Ote,n as sa,o as ca,p as kte,r as la,s as ua,t as Ate,u as da,v as I,x as fa,y as pa}from"./state-DUXkItYp.js";import{a as jte,i as ma,r as ha,t as ga}from"./git-config-Bdgu8kD2.js";import{a as Mte,c as _a,i as Nte,o as Pte,r as Fte,s as Ite,t as Lte}from"./script-catalog-Bt94D0RP.js";import{t as va}from"./process-manager-BkhAohXT.js";import{A as ya,C as ba,F as xa,I as Sa,N as Ca,P as Rte,_ as zte,a as wa,b as Ta,c as Ea,d as Da,f as Oa,g as Bte,h as ka,i as Aa,j as Vte,l as Hte,m as Ute,n as Wte,o as ja,p as Ma,r as Na,s as Pa,t as Fa,u as Ia,v as La,x as Ra,y as za}from"./shared-C_68vn79.js";import{t as Ba}from"./tmpdir-env-ate4iNcK.js";import{t as Va}from"./realm-browser-fetch-V3uggGbM.js";import{n as Ha,t as Ua}from"./esbuild-wasm-DS_YG2EY.js";import{n as Wa,t as Ga}from"./wasm-compiler-Ct7QZURL.js";import{a as Ka,i as qa,n as Ja,o as Ya,s as Xa,t as Za}from"./usb-device-registry-DFzxaOky.js";import{n as Qa,r as $a,t as eo}from"./just-bash-compat-_TMo8UnL.js";import{a as to,c as no,o as ro,s as io,t as ao}from"./types-Dzr0qYl3.js";import{a as oo,c as so,d as co,f as lo,n as uo,r as fo,u as po}from"./github-zip-BWd2XSNT.js";import{i as mo,t as ho}from"./github-auth-CQ0OVCLm.js";import{a as go,i as _o,o as vo,r as yo,t as bo}from"./provenance-DdmsQ3Nr.js";import{a as xo,c as So,i as Co,n as wo,o as To,r as Eo,s as Do}from"./github-install-Dbz8WLRF.js";import{n as Oo,t as ko}from"./magick-wasm-DCNZhAyd.js";import{i as Ao,n as jo,r as Mo,t as No}from"./pdf-raster-BWk6ezTX.js";import{n as Po,t as Fo}from"./lick-target-env-8JxfVcIV.js";import{a as Io,c as Lo,d as Ro,f as zo,i as Bo,l as Vo,n as Ho,o as Uo,p as Wo,r as Go,s as Ko,t as qo,u as Jo}from"./installer-EvwVnAiv.js";import{n as Yo,r as Xo,t as Zo}from"./extension-media-capture-CRjN0St9.js";import{t as Qo}from"./local-llm-B5PHgroX.js";import{t as $o}from"./client-B6iKb_ye.js";import{t as es}from"./redirect-uri-CgKdq7-K.js";import{t as ts}from"./write-verification-BOaZdtyk.js";let ns=null;function rs(e){ns=e!==null&&Number.isFinite(e)&&e>0?e:null}function is(){if(ns!==null)return ns;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const as=[`/workspace`,`/shared`,`/scoops`,`/home`];var os=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 ss(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 cs=n(`cdp`);function ls(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 us=class{ws=null;nextId=1;_superseded=!1;pending=new os;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,cs.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(cs.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(),cs.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),cs.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 ss(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;cs.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(cs.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;cs.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,cs.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?cs.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):cs.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(ls(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{}}}},ds=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 fs(e,t){if(e?.aborted)throw new ds(t)}function ps(e,t){return e?{signal:e,error:()=>new ds(t)}:void 0}function ms(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new ds(n));return}let a=()=>{clearTimeout(o),i(new ds(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function hs(e,t,n){return t?t.aborted?Promise.reject(new ds(n)):new Promise((r,i)=>{let a=()=>i(new ds(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 gs=n(`har-recorder`);var _s=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)}`;fs(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),fs(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),fs(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}`),gs.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=>{gs.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=>{gs.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 vs(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return gs.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 gs.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)),gs.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 gs.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 vs(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){gs.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return gs.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ys=`(function() {
|
|
1
|
+
import{n as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{t as n}from"./logger-LESFN7Hj.js";import{a as r,i,n as a,o,r as s,t as c}from"./snapshot-C0jMXzwY.js";import{n as l,r as u,t as d}from"./panel-rpc-BPwAqRch.js";import{n as f,r as p,t as m}from"./feature-flags-BIRXJe0o.js";import{a as h,t as g}from"./providers-DG3GRO0g.js";import{r as _,t as v}from"./base64-DzRgusa4.js";import{n as y}from"./bridge-protocol-DdqxTTSu.js";import{t as b}from"./content-type-_QKWY0B2.js";import{a as x,c as S,i as C,l as w,o as T,r as E,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as ie,d as eee,f as ae,g as oe,h as tee,i as se,m as ce,p as le,u as ue,v as de,x as fe,y as pe}from"./account-store-KxT17gu_.js";import{a as me,l as he,n as ge,o as nee}from"./proxied-fetch-DEK8DT-z.js";import{t as _e}from"./runtime-env-DadgceZk.js";import{t as ve}from"./slugify-BYJ6QVAt.js";import{i as ye}from"./archive-redaction-ByV7X5fs.js";import{r as be}from"./binary-cache-bSOhqXB1.js";import{i as xe,n as Se,r as Ce,t as we}from"./fetch-body-CuwTaJC_.js";import{a as ree,l as iee,o as Te,s as aee,t as Ee,u as oee}from"./api-endpoint-3qEcn7BY.js";import{$ as De,A as Oe,At as ke,B as Ae,C as je,Ct as Me,D as Ne,Dt as Pe,E as Fe,Et as Ie,F as see,H as Le,I as Re,J as ze,K as cee,L as lee,M as Be,Mt as D,N as Ve,Nt as He,O as uee,Ot as Ue,P as We,Q as Ge,R as Ke,St as qe,T as Je,Tt as Ye,U as Xe,V as Ze,W as Qe,X as $e,Y as et,Z as tt,_ as nt,_t as rt,a as it,at,b as ot,bt as dee,c as st,ct as O,d as ct,dt as fee,et as lt,f as ut,ft as dt,g as ft,gt as pt,h as pee,ht as mt,i as mee,it as ht,j as gt,jt as _t,k as vt,kt as yt,l as bt,lt as xt,m as St,mt as Ct,n as wt,nt as Tt,o as Et,ot as Dt,p as Ot,pt as k,q as kt,r as At,rt as jt,s as Mt,st as A,t as Nt,tt as Pt,u as Ft,ut as It,v as Lt,vt as Rt,w as zt,wt as Bt,x as Vt,xt as hee,y as Ht,yt as Ut,z as Wt}from"./build-BRNa03GH.js";import{a as gee}from"./models-4WTk3EBD.js";import{o as Gt,t as _ee}from"./compat-uEPf6-XW.js";import{a as vee,c as Kt,i as qt,l as yee,o as Jt,s as Yt,t as Xt,u as Zt}from"./core-DP-MJcag.js";import{t as bee}from"./__vite-browser-external-5eBdwsFd.js";import{n as xee,r as See}from"./attachments-u2K0aIPI.js";import{i as Qt,n as Cee,r as wee,t as Tee}from"./context-compaction-DRymamfD.js";import{n as Eee,t as Dee}from"./mime-types-D7IV6i7k.js";import{t as $t}from"./secrets-bridge-client-ZpBL1Zhl.js";import{t as en}from"./image-markers-DuyWsic3.js";import{i as tn,r as nn}from"./budget-usage-source--zsr_0LN.js";import{a as rn,i as an,n as j,t as on}from"./path-utils-DNJG-zQf.js";import{a as sn,i as cn,o as ln,r as un,t as dn}from"./agent-bridge-BkHuOfQg.js";import{A as fn,C as pn,D as mn,E as hn,S as gn,T as _n,_ as vn,a as yn,c as bn,d as xn,f as Sn,g as Cn,h as wn,k as Tn,l as En,m as Dn,n as On,o as kn,p as Oee,r as kee,s as An,t as Aee,u as jn,v as jee,w as Mee,y as Nee}from"./record-YqlVEfh_.js";import{c as Pee,d as Mn,i as Nn,l as Pn,n as Fee,o as Fn,r as In,s as Iee,u as Ln}from"./descriptor-D-6Koktu.js";import{a as Lee,c as Ree,i as zee,l as Rn,o as Bee,r as Vee,s as Hee,u as Uee}from"./agent-message-to-chat-w7n13QEN.js";import{n as zn,t as Bn}from"./thinking-level-5x0UAu9N.js";import{n as Vn,t as M}from"./types-D8gIX-W-.js";import{i as Hn}from"./mount-index-CQfmUPuZ.js";import{a as Wee,c as Un,i as Gee,l as Kee,n as qee,o as Jee,r as Yee,s as Wn,u as Xee}from"./mount-DSkdtHPr.js";import{o as Gn}from"./mount-table-store-DrF_Ifaz.js";import{t as Kn}from"./remote-cache-BE5T1-53.js";import{i as Zee,n as qn,r as Jn}from"./fs-CKF7L1oq.js";import{r as Yn,t as Qee}from"./mount-recovery-B41gr65n.js";import{r as Xn,t as Zn}from"./key-DExP84Xm.js";import{n as $ee,t as ete}from"./manager-CstXzWYQ.js";import{a as tte,c as nte,i as Qn,n as rte,o as ite,r as ate,s as ote}from"./lick-urls-BZVq_P3x.js";import{C as $n,D as ste,E as er,S as tr,_ as nr,a as rr,b as ir,d as ar,g as or,h as sr,m as cr,n as lr,o as ur,r as dr,s as fr,t as pr,u as mr,w as hr,y as gr}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config-CRZxBChd.js";import{n as _r,r as vr,t as yr}from"./slicc-version-DFbfAxmg.js";import{a as br,i as xr,n as N,r as Sr,t as Cr}from"./browser-fOe3v0iv.js";import{t as P}from"./subcommand-flags-BZi7j78Q.js";import{n as wr,r as Tr,t as F}from"./subcommand-help-CgO7wRS5.js";import{a as Er,i as Dr,n as Or,r as kr}from"./cost-command-DlIH8zCh.js";import{_ as Ar,a as jr,c as Mr,d as Nr,f as Pr,g as Fr,h as Ir,i as Lr,l as Rr,m as zr,n as Br,o as Vr,p as Hr,r as Ur,s as Wr,t as Gr,u as Kr,v as qr}from"./sudoers-BdBYQPUn.js";import{a as Jr,i as Yr,n as Xr,o as Zr,r as Qr,s as $r}from"./skills-C058JDJA.js";import{a as ei,c as ti,i as ni,l as ri,n as ii,o as ai,r as oi,t as si}from"./types-BfwydWt7.js";import{n as ci,t as li}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as ui}from"./html-B_Hg2WOy.js";import{n as di,t as fi}from"./llm-session-id-BZyXP_j2.js";import{a as pi}from"./frozen-archive-format-B4efpvB9.js";import{n as mi,r as hi}from"./derive-BqbmiIL9.js";import{n as gi,t as _i}from"./cone-memory-budget-ieIsscyt.js";import{i as vi,r as yi}from"./browser-2rCVqcqy.js";import{a as bi}from"./gelatiere-constants-BYJlhm8R.js";import{n as xi}from"./safe-buffer-OLJ0qaLt.js";import{A as Si,B as Ci,C as wi,D as Ti,E as Ei,F as Di,G as Oi,H as ki,I as Ai,J as ji,K as Mi,L as Ni,M as cte,N as lte,O as Pi,P as ute,R as Fi,S as Ii,T as dte,U as fte,V as Li,W as pte,Y as mte,_ as hte,a as Ri,b as zi,c as Bi,d as gte,f as Vi,g as _te,h as vte,i as Hi,j as Ui,k as yte,l as Wi,m as Gi,n as Ki,o as qi,p as Ji,q as Yi,r as Xi,s as bte,t as Zi,u as Qi,v as xte,w as Ste,x as $i,y as Cte,z as ea}from"./isomorphic-git-DRUhmZ5u.js";import"./global-db-DJXlpNui.js";import{S as ta,_ as na,a as ra,b as ia,c as aa,d as wte,f as Tte,g as Ete,h as Dte,i as oa,l as Ote,n as sa,o as ca,p as kte,r as la,s as ua,t as Ate,u as da,v as I,x as fa,y as pa}from"./state-B0LE2MQY.js";import{a as jte,i as ma,r as ha,t as ga}from"./git-config-Bdgu8kD2.js";import{a as Mte,c as _a,i as Nte,o as Pte,r as Fte,s as Ite,t as Lte}from"./script-catalog-Bt94D0RP.js";import{t as va}from"./process-manager-BkhAohXT.js";import{A as ya,C as ba,F as xa,I as Sa,N as Ca,P as Rte,_ as zte,a as wa,b as Ta,c as Ea,d as Da,f as Oa,g as Bte,h as ka,i as Aa,j as Vte,l as Hte,m as Ute,n as Wte,o as ja,p as Ma,r as Na,s as Pa,t as Fa,u as Ia,v as La,x as Ra,y as za}from"./shared-C_68vn79.js";import{t as Ba}from"./tmpdir-env-ate4iNcK.js";import{t as Va}from"./realm-browser-fetch-V3uggGbM.js";import{n as Ha,t as Ua}from"./esbuild-wasm-DS_YG2EY.js";import{n as Wa,t as Ga}from"./wasm-compiler-Ct7QZURL.js";import{a as Ka,i as qa,n as Ja,o as Ya,s as Xa,t as Za}from"./usb-device-registry-DFzxaOky.js";import{n as Qa,r as $a,t as eo}from"./just-bash-compat-_TMo8UnL.js";import{a as to,c as no,o as ro,s as io,t as ao}from"./types-Dzr0qYl3.js";import{a as oo,c as so,d as co,f as lo,n as uo,r as fo,u as po}from"./github-zip-C3GODUL3.js";import{i as mo,t as ho}from"./github-auth-PgzNFXb7.js";import{a as go,i as _o,o as vo,r as yo,t as bo}from"./provenance-DdmsQ3Nr.js";import{a as xo,c as So,i as Co,n as wo,o as To,r as Eo,s as Do}from"./github-install-CCiLZQKP.js";import{n as Oo,t as ko}from"./magick-wasm-DCNZhAyd.js";import{i as Ao,n as jo,r as Mo,t as No}from"./pdf-raster-BWk6ezTX.js";import{n as Po,t as Fo}from"./lick-target-env-8JxfVcIV.js";import{a as Io,c as Lo,d as Ro,f as zo,i as Bo,l as Vo,n as Ho,o as Uo,p as Wo,r as Go,s as Ko,t as qo,u as Jo}from"./installer-CeDnN_9I.js";import{n as Yo,r as Xo,t as Zo}from"./extension-media-capture-CRjN0St9.js";import{t as Qo}from"./local-llm-Cw7-Quw-.js";import{t as $o}from"./client-B6iKb_ye.js";import{t as es}from"./redirect-uri-CgKdq7-K.js";import{t as ts}from"./write-verification-BOaZdtyk.js";let ns=null;function rs(e){ns=e!==null&&Number.isFinite(e)&&e>0?e:null}function is(){if(ns!==null)return ns;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const as=[`/workspace`,`/shared`,`/scoops`,`/home`];var os=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 ss(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 cs=n(`cdp`);function ls(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 us=class{ws=null;nextId=1;_superseded=!1;pending=new os;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,cs.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(cs.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(),cs.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),cs.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 ss(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;cs.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(cs.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;cs.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,cs.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?cs.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):cs.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(ls(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{}}}},ds=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 fs(e,t){if(e?.aborted)throw new ds(t)}function ps(e,t){return e?{signal:e,error:()=>new ds(t)}:void 0}function ms(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new ds(n));return}let a=()=>{clearTimeout(o),i(new ds(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function hs(e,t,n){return t?t.aborted?Promise.reject(new ds(n)):new Promise((r,i)=>{let a=()=>i(new ds(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 gs=n(`har-recorder`);var _s=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)}`;fs(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),fs(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),fs(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}`),gs.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=>{gs.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=>{gs.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 vs(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return gs.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 gs.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)),gs.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 gs.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 vs(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){gs.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return gs.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ys=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -1559,7 +1559,7 @@ except BaseException:
|
|
|
1559
1559
|
`)?a:`${a}\n`;t(n>0?`${` `.repeat(n)}${o}`:o)}function PL(e,t,n){let r=OL(n);if(e.has(r)){t(`Label '${r}' already exists for console.time()`);return}e.set(r,kL())}function FL(e,t,n,r){let i=OL(r),a=e.get(i);if(a===void 0){t(`No such label '${i}' for console.timeEnd()`);return}e.delete(i),n(`${i}: ${AL(kL()-a)}`)}function IL(e,t,n,r,i){let a=OL(r),o=e.get(a);if(o===void 0){t(`No such label '${a}' for console.timeLog()`);return}let s=`${a}: ${AL(kL()-o)}`;i.length===0?n(s):n(s,...i)}function LL(e,t,n){let r=OL(n),i=(e.get(r)??0)+1;e.set(r,i),t(`${r}: ${i}`)}function RL(e,t,n){let r=OL(n);if(!e.has(r)){t(`Count for '${r}' does not exist`);return}e.set(r,0)}function zL(e,t,n){n.length>0&&t(...n),e.depth+=1}function BL(e){e.depth>0&&--e.depth}function VL(e,t){let n=new Map,r=new Map,i={depth:0},a=(...t)=>jL(e,i.depth,t),o=(...e)=>jL(t,i.depth,e),s=(...e)=>zL(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:()=>BL(i),assert:(e,...t)=>ML(o,e,t),trace:(...e)=>NL(o,t,i.depth,e),time:e=>PL(r,o,e),timeEnd:e=>FL(r,o,a,e),timeLog:(e,...t)=>IL(r,o,a,e,t),count:e=>LL(n,a,e),countReset:e=>RL(n,o,e)}}function HL(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=WL(e.stdin??``,o),c=vL(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:xa},version:`v${xa}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new TL(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var UL=class extends vM.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 TL){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 WL(e,t){return new UL(e,t)}function GL(e){if(e===``)return[];let t=e.split(`
|
|
1560
1560
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function KL(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function qL(e){return new TextDecoder(`utf-8`).decode(bj(e))}function JL(e){if(e&&typeof e.write==`function`)return e}var YL=class extends fM{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=GL(qL(KL(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 TL&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function XL(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=JL(e.output)}else r=t,i=JL(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new YL(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:YL,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var ZL=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`?`: ${QL(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 QL(e){try{return JSON.stringify(e)}catch{return String(e)}}function $L(e){return new Promise(t=>setTimeout(t,e))}function eR(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 tR(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?eR(r,n):r}function nR(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 rR(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function iR(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 aR(e){if(rR(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 oR(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 sR(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function cR(e,t,n){let r=await t(n);r&&!sR(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function lR(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 uR(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function dR(e,t){let n=await aR(e);return t?uR(e,n):n}async function fR(e,t){let n=await aR(e).catch(()=>null);throw new ZL(e.status,e.statusText,t,n)}function pR(e,t){let n=iR(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function mR(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=lR(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 dR(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return fR(l,t);await e.sleep(pR(l,a))}if(i)return fR(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function hR(e){let t=e.sleep??$L;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=tR(n.baseUrl,o,s.params),l=nR(n.headers,s.headers);n.token&&await cR(l,n.token,{method:a,path:o,url:c});let u=oR(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),mR({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 gR(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 _R(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`,gR(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 vR(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(_R(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 yR(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 bR(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=yR(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 xR(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 SR(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 SR(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(Un(e)){let t=await Wn(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 CR(e){return{findTab:t=>e.call(`browser`,`findTab`,[TR(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,ER(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[yR(t),wR(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[yR(t),wR(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[yR(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[yR(t),n]),fetch:(t,n,r={})=>Va(n,r).then(n=>e.call(`browser`,`evalAsync`,[yR(t),n])),websocket:bR(e)}}function wR(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 TR(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 ER(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function DR(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function OR(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:DR(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}const kR=new Set([204,205,304]),AR=new Set([`content-encoding`,`transfer-encoding`,`content-length`]);function jR(e,t){let n=MR(e.body),r=NR(e.headers),i=kR.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 PR(a,n),a}function MR(e){return e.byteLength===0?new Uint8Array:e.slice()}function NR(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(!AR.has(n.toLowerCase()))try{t.set(n,r)}catch{}return t}function PR(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 FR(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 IR(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function LR(e){return e==null?[]:Array.isArray(e)?e:[e]}function RR(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:IR(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,FR(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,FR(r)]),receiveFeatureReport:async t=>IR((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 zR(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>RR(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[LR(t)]))[0];if(!n)throw Error(`No device selected.`);return RR(e,n)}}}function BR(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 VR=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 };`)}},HR=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=BR(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 VR(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 VR(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?.())}},UR=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 HR(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()}},WR=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 HR(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 UR(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 GR(e){let t=async t=>new WR(e),n=async(t,n)=>new WR(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const KR=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`]),qR={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 JR(e,t){let n=qR[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function YR(e){return{...e,time:CL,fmt:Qj,pool:yL}}function XR(e,t){return e?.startsWith(`/`)?wL(e):t}function ZR(e){return e.includes(`require`)||e.includes(`import`)||/(?:^|[;\n}])\s*export\b/.test(e)}async function QR(e,t,n,r){return ZR(t)?e.call(`module`,`buildGraph`,[t,XR(r,n),r]):{files:[],entryMap:{},edges:{},edgeErrors:{},errors:{}}}function $R(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 ez(e){return{playwright:GR(e)}}function tz(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=LN,nodeUtilModule:u=IM}=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=MN({requireFrom:(e,t)=>x(e,t),resolveFrom:(e,t)=>b(e,t)}),h=yN(()=>{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:iz(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=nz(t,{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:l,nodeUtilModule:u,nodePathModule:h,nodeReadline:c,nodeModule:m});if(a.hit)return a;if(KR.has(t))throw JR(e,t);if(Rte.has(t))throw oz(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):rz(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=wL(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`&&$R(o.exports),o.exports}function y(e){return d.has(e)}function b(e,n){if(Sa(n))return n;let r=t.edges[e]?.[n];if(r)return r;let i=wL(e);if(jN(n)){let e=kN(i,n,y);if(e)return e}else{let e=AN(i,n,y);if(e)return e}let a=t.edgeErrors?.[e]?.[n];throw a?Error(a):rz(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 nz(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:sN}: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:uM}:e===`assert/strict`?{hit:!0,value:lM}:e===`util`?{hit:!0,value:o}:e===`events`?{hit:!0,value:pM}:e===`os`?{hit:!0,value:a}:e===`tty`?{hit:!0,value:RN}:e===`stream`?{hit:!0,value:vM}:e===`url`?{hit:!0,value:CN}:e===`zlib`?{hit:!0,value:gL}: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 rz(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 iz(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 az={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function oz(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${az[t]||``}`)}async function sz(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";
|
|
1561
1561
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof TL?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function cz(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?FR(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,FR(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function lz(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>cz(e,t)),request:async t=>cz(e,await e.call(`serial`,`request`,[LR(t)]))}}function uz(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 dz(e,t){let n=t.handle,r=e=>({status:e.status,data:IR(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,FR(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,FR(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 fz(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>dz(e,t)),request:async t=>dz(e,await e.call(`usb`,`request`,[LR(t)]))}}function pz(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function mz(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 hz(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function gz(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function _z(e){let t=pz(e.argv[1]??``),n=mz(t),r=gz(n,`references`),i=gz(n,`assets`),a=gz(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)+`
|
|
1562
|
-
`),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 ${hz(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 vz=new Map,yz=new Map;function bz(e){let t=crypto.randomUUID();return vz.set(t,e),t}function xz(e){return vz.get(e)??null}function Sz(e,t){if(!vz.has(e))return t.abort(),()=>{};let n=yz.get(e);return n||(n=new Set,yz.set(e,n)),n.add(t),()=>{let n=yz.get(e);n&&(n.delete(t),n.size===0&&yz.delete(e))}}function Cz(e){vz.delete(e);let t=yz.get(e);if(t){yz.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function wz(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 Tz(e){let t=xz(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??``),{renameViaFs:a}=await import(`./rename-via-fs-ckVY1Ljv.js`);return await a(n,t,i),{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return wz(e)}}function Ez(e){return`slicc-sync-fs-`+e}const Dz=`sync-fs-ack`,Oz=`sync-fs-res`,kz=6e5,Az=5e3,jz=`exec`;function Mz(e){return e.channel===jz}function Nz(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 Pz(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,kz)}async function Fz(e){let t=xz(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=Nz(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()},Pz(e.timeoutMs,kz)),o=Sz(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`}:wz(e)}finally{clearTimeout(a),o()}}function Iz(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function Lz(e){let t=zz(e);if(Bz(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw Iz(`EIO`,e.label);Vz(t,e.label)}function Rz(e){let t=Lz(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw Iz(`EIO`,e.label)}}function zz(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 Iz(`EIO`,e.label)}return t}function Bz(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function Vz(e,t){throw Iz(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function Hz(e){return(t,n,r)=>{let i=Rz({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:jz})),timeoutMs:n+Az,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw Iz(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function Uz(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 Wz(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??Hz(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&Uz(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=Pz(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 Gz(e,t){return Iz(e,`sync-fs bridge, '${t}'`)}function Kz(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function qz(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:Kz(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return Lz(r(`GET`,e))},writeFile(e,t){Lz(r(`POST`,e,t))},stat(e){let t=Rz(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw Gz(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=Rz(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw Gz(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=Rz(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw Gz(`EIO`,e);return t},exists(e){let t=Rz(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw Gz(`EIO`,e);return t},mkdir(e){Lz(r(`POST`,e,void 0,`mkdir`))},rm(e){Lz(r(`POST`,e,void 0,`rm`))}}}const Jz=new TextEncoder,Yz=new TextDecoder;function Xz(e){if(!e.ok)return{status:4,payload:Jz.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:Jz.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function Zz(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(Yz.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(Yz.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 Qz(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 $z(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function eB(e,t,n={}){let{header:r,window:i}=Qz(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 Iz(`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 Iz(`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 Iz(`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 Iz(`EIO`,a)}}finally{Atomics.store(r,0,0)}return Zz(f,d)}}}function tB(e,t){return Iz(e,`sync-sab bridge, '${t}'`)}function nB(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function rB(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 tB(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw tB(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw tB(`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(!nB(t))throw tB(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!nB(t))throw tB(`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 tB(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw tB(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function iB(e){return(t,n,r)=>{let i=e.call({...t,channel:jz},n+Az,r);if(!i.ok)throw Iz(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 Iz(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function aB(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 vj(r)}function oB(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function sB(e,t){return t?rB(t):e.syncFsToken?qz(e.syncFsToken):void 0}function cB(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return eB(e.syncSab,t)}function lB(e,t,n,r,i){let a=cB(e,t),o=sB(e,a);if(Object.assign(r,zj(n,e.cwd,o,i,{write:(e,n)=>{t.postMessage({type:`realm-fs-write`,path:e,bytes:n})},delete:e=>{t.postMessage({type:`realm-fs-delete`,path:e})}})),e.syncFsToken)return Wz(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:iB(a)}:{}})}function uB(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:_r().version,writable:!1,enumerable:!1,configurable:!1})}function dB(e,t,n){let r=Hj({isTTY:!e,noColor:e});return{colorApi:r,cliApi:Bj({writeStdout:t,writeStderr:n,exit:e=>{throw new TL(e)},color:r})}}function fB(e,t,n){return{readStdinBytes:()=>bj(e.stdin??``),writeStdout:t,writeStderr:n}}function pB(e){return{usbBridge:fz(e),serialBridge:lz(e),hidBridge:zR(e)}}async function mB(e,t){let n=[],r=[],i=(e,n,r)=>{let i=typeof r==`string`?r:String(r);n.push(i),t.postMessage({type:`realm-output`,stream:e,chunk:i})},a=e=>{i(`stdout`,n,e)},o=e=>{i(`stderr`,r,e)},s=VL(a,o),c=HL(e,a,o),{colorApi:l,cliApi:u}=dB(!!e.env?.NO_COLOR,a,o),d=new kA(t),f=fB(e,a,o),p=Mj(d,w,f),m=await aB(d,e.cwd,oB(e,o)),h=lB(e,t,m,p,f),g=OR(d,m,e.cwd,o),_=vR(g,{cwd:e.cwd}),v=_z({argv:e.argv,fs:p,exec:g}),y=CR(d),{usbBridge:b,serialBridge:x,hidBridge:S}=pB(d),C=hR({fetch:w});async function w(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return jR(await d.call(`fetch`,`request`,[n,await xR(t,e)]),n)}let T=YR({exec:g,agent:_,skill:v,http:C,browser:y,usb:b,serial:x,hid:S,cli:u,color:l}),E=e.filename,ee=wL(E),te=await QR(d,e.code,e.cwd,E),ne=tz({graph:te,fsBridge:p,processShim:c.processShim,childProcess:GM(g,h),nodeConsole:s,sliccyModules:T,shimmedPackages:ez(d),nodeReadline:XL({output:{write:a},onExit:c.recordExit}),nodeOsModule:IN(e.env),nodeUtilModule:FM(e=>o(`${e}\n`))}).require,re={exports:{},filename:e.filename},ie=te.entrySource!==void 0;await hB({entryCode:te.entrySource??e.code,isEsmEntry:ie,filename:E,dirname:ee,proc:c,nodeConsole:s,requireShim:ne,moduleShim:re,realmFetch:w,writeStderr:o,rpc:d,syncFs:m,stdoutChunks:n,stderrChunks:r,port:t})}async function hB(e){let t=globalThis;uB(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=uz(globalThis,{onCallbackError(e){if(!(e instanceof TL))throw e}});n.install();try{let r=await gB({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 gB(e){let t=await sz(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await _B(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await vB(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await _B(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function _B(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 vB(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 yB(){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 bB(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=yB(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&mB(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 xB(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=yB(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&BA(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 SB=bB(),CB=xB();function wB(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?EB():CB({kind:e,ctx:t}):typeof Worker<`u`?TB():SB({kind:e,ctx:t})}function TB(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return DB(new Worker(new URL(`/assets/js-realm-worker-CjRTKYQi.js`,``+import.meta.url),{type:`module`}))}function EB(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return DB(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function DB(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 OB(){if(Ma())return decodeURIComponent(Bte(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function kB(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function AB(e){return e instanceof Error?e.message:String(e)}function jB(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function MB(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:jB(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function NB(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:jB(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const PB=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,FB=/\bimport\s*\.\s*meta\b/g;function IB(e,t){let n=JSON.stringify(t);return e.replace(PB,n).replace(FB,`({ url: ${n} })`)}async function LB(e,t,n,r){let i=await e();return i.transpileModule(IB(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function RB(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Ha(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Da(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ta(e))return e;let a=kB(t),o;try{return await MB(n,e,t,a)}catch(e){o=e}try{return await LB(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${AB(o)}; typescript fallback: ${AB(e)}`)}}}function zB(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Ha(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Da(t));return async({source:e,filename:t})=>{if(!Ta(e)&&!za(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?kB(t):void 0,o=i?t:`[eval].js`,s;try{return await NB(n,e,t,a)}catch(e){s=e}try{return await LB(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${AB(s)}; typescript fallback: ${AB(e)}`)}}}function BB(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1562
|
+
`),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 ${hz(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 vz=new Map,yz=new Map;function bz(e){let t=crypto.randomUUID();return vz.set(t,e),t}function xz(e){return vz.get(e)??null}function Sz(e,t){if(!vz.has(e))return t.abort(),()=>{};let n=yz.get(e);return n||(n=new Set,yz.set(e,n)),n.add(t),()=>{let n=yz.get(e);n&&(n.delete(t),n.size===0&&yz.delete(e))}}function Cz(e){vz.delete(e);let t=yz.get(e);if(t){yz.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function wz(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 Tz(e){let t=xz(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??``),{renameViaFs:a}=await import(`./rename-via-fs-ckVY1Ljv.js`);return await a(n,t,i),{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return wz(e)}}function Ez(e){return`slicc-sync-fs-`+e}const Dz=`sync-fs-ack`,Oz=`sync-fs-res`,kz=6e5,Az=5e3,jz=`exec`;function Mz(e){return e.channel===jz}function Nz(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 Pz(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,kz)}async function Fz(e){let t=xz(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=Nz(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()},Pz(e.timeoutMs,kz)),o=Sz(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`}:wz(e)}finally{clearTimeout(a),o()}}function Iz(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function Lz(e){let t=zz(e);if(Bz(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw Iz(`EIO`,e.label);Vz(t,e.label)}function Rz(e){let t=Lz(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw Iz(`EIO`,e.label)}}function zz(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 Iz(`EIO`,e.label)}return t}function Bz(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function Vz(e,t){throw Iz(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function Hz(e){return(t,n,r)=>{let i=Rz({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:jz})),timeoutMs:n+Az,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw Iz(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function Uz(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 Wz(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??Hz(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&Uz(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=Pz(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 Gz(e,t){return Iz(e,`sync-fs bridge, '${t}'`)}function Kz(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function qz(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:Kz(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return Lz(r(`GET`,e))},writeFile(e,t){Lz(r(`POST`,e,t))},stat(e){let t=Rz(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw Gz(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=Rz(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw Gz(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=Rz(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw Gz(`EIO`,e);return t},exists(e){let t=Rz(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw Gz(`EIO`,e);return t},mkdir(e){Lz(r(`POST`,e,void 0,`mkdir`))},rm(e){Lz(r(`POST`,e,void 0,`rm`))}}}const Jz=new TextEncoder,Yz=new TextDecoder;function Xz(e){if(!e.ok)return{status:4,payload:Jz.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:Jz.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function Zz(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(Yz.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(Yz.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 Qz(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 $z(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function eB(e,t,n={}){let{header:r,window:i}=Qz(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 Iz(`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 Iz(`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 Iz(`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 Iz(`EIO`,a)}}finally{Atomics.store(r,0,0)}return Zz(f,d)}}}function tB(e,t){return Iz(e,`sync-sab bridge, '${t}'`)}function nB(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function rB(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 tB(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw tB(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw tB(`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(!nB(t))throw tB(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!nB(t))throw tB(`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 tB(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw tB(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function iB(e){return(t,n,r)=>{let i=e.call({...t,channel:jz},n+Az,r);if(!i.ok)throw Iz(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 Iz(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function aB(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 vj(r)}function oB(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function sB(e,t){return t?rB(t):e.syncFsToken?qz(e.syncFsToken):void 0}function cB(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return eB(e.syncSab,t)}function lB(e,t,n,r,i){let a=cB(e,t),o=sB(e,a);if(Object.assign(r,zj(n,e.cwd,o,i,{write:(e,n)=>{t.postMessage({type:`realm-fs-write`,path:e,bytes:n})},delete:e=>{t.postMessage({type:`realm-fs-delete`,path:e})}})),e.syncFsToken)return Wz(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:iB(a)}:{}})}function uB(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:_r().version,writable:!1,enumerable:!1,configurable:!1})}function dB(e,t,n){let r=Hj({isTTY:!e,noColor:e});return{colorApi:r,cliApi:Bj({writeStdout:t,writeStderr:n,exit:e=>{throw new TL(e)},color:r})}}function fB(e,t,n){return{readStdinBytes:()=>bj(e.stdin??``),writeStdout:t,writeStderr:n}}function pB(e){return{usbBridge:fz(e),serialBridge:lz(e),hidBridge:zR(e)}}async function mB(e,t){let n=[],r=[],i=(e,n,r)=>{let i=typeof r==`string`?r:String(r);n.push(i),t.postMessage({type:`realm-output`,stream:e,chunk:i})},a=e=>{i(`stdout`,n,e)},o=e=>{i(`stderr`,r,e)},s=VL(a,o),c=HL(e,a,o),{colorApi:l,cliApi:u}=dB(!!e.env?.NO_COLOR,a,o),d=new kA(t),f=fB(e,a,o),p=Mj(d,w,f),m=await aB(d,e.cwd,oB(e,o)),h=lB(e,t,m,p,f),g=OR(d,m,e.cwd,o),_=vR(g,{cwd:e.cwd}),v=_z({argv:e.argv,fs:p,exec:g}),y=CR(d),{usbBridge:b,serialBridge:x,hidBridge:S}=pB(d),C=hR({fetch:w});async function w(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return jR(await d.call(`fetch`,`request`,[n,await xR(t,e)]),n)}let T=YR({exec:g,agent:_,skill:v,http:C,browser:y,usb:b,serial:x,hid:S,cli:u,color:l}),E=e.filename,ee=wL(E),te=await QR(d,e.code,e.cwd,E),ne=tz({graph:te,fsBridge:p,processShim:c.processShim,childProcess:GM(g,h),nodeConsole:s,sliccyModules:T,shimmedPackages:ez(d),nodeReadline:XL({output:{write:a},onExit:c.recordExit}),nodeOsModule:IN(e.env),nodeUtilModule:FM(e=>o(`${e}\n`))}).require,re={exports:{},filename:e.filename},ie=te.entrySource!==void 0;await hB({entryCode:te.entrySource??e.code,isEsmEntry:ie,filename:E,dirname:ee,proc:c,nodeConsole:s,requireShim:ne,moduleShim:re,realmFetch:w,writeStderr:o,rpc:d,syncFs:m,stdoutChunks:n,stderrChunks:r,port:t})}async function hB(e){let t=globalThis;uB(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=uz(globalThis,{onCallbackError(e){if(!(e instanceof TL))throw e}});n.install();try{let r=await gB({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 gB(e){let t=await sz(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await _B(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await vB(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await _B(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function _B(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 vB(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 yB(){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 bB(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=yB(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&mB(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 xB(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=yB(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&BA(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 SB=bB(),CB=xB();function wB(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?EB():CB({kind:e,ctx:t}):typeof Worker<`u`?TB():SB({kind:e,ctx:t})}function TB(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return DB(new Worker(new URL(`/assets/js-realm-worker-BfqOZWvd.js`,``+import.meta.url),{type:`module`}))}function EB(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return DB(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function DB(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 OB(){if(Ma())return decodeURIComponent(Bte(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function kB(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function AB(e){return e instanceof Error?e.message:String(e)}function jB(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function MB(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:jB(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function NB(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:jB(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const PB=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,FB=/\bimport\s*\.\s*meta\b/g;function IB(e,t){let n=JSON.stringify(t);return e.replace(PB,n).replace(FB,`({ url: ${n} })`)}async function LB(e,t,n,r){let i=await e();return i.transpileModule(IB(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function RB(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Ha(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Da(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ta(e))return e;let a=kB(t),o;try{return await MB(n,e,t,a)}catch(e){o=e}try{return await LB(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${AB(o)}; typescript fallback: ${AB(e)}`)}}}function zB(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Ha(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Da(t));return async({source:e,filename:t})=>{if(!Ta(e)&&!za(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?kB(t):void 0,o=i?t:`[eval].js`,s;try{return await NB(n,e,t,a)}catch(e){s=e}try{return await LB(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${AB(s)}; typescript fallback: ${AB(e)}`)}}}function BB(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1563
1563
|
`);return t===-1?``:e.slice(t+1)}function VB(e){return rn(e).dir}const HB=[`node`,`require`,`default`],UB=[`node`,`import`,`default`],WB=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,GB=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,KB=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,qB=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,JB=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function YB(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function XB(e){let t=Ra(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!YB(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(WB,`require`,`require`),r(GB,`import`,`import`),r(KB,`import`,`import`),r(qB,`import`,`export`),r(JB,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function ZB(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=BB(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${Fa} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function QB(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??HB,s=e.importConditions??UB,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 ZB(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=VB(e),m={},h={};for(let{specifier:e,kind:t}of XB(n)){let n;try{n=await ba(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 ba(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 $B(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Ca.has(e)||KR.has(e))}function eV(e,t){for(let[n,r]of Object.entries(t))e[n]={...e[n]??{},...r}}async function tV(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 XB(t))if($B(e))try{let t=await QB({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?UB:HB,requireConditions:HB,importConditions:UB});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap),eV(u,t.edges),eV(d,t.edgeErrors)}catch(t){f[e]=t instanceof Error?t.message:String(t)}let p;o&&(Ta(t)||za(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 nV(){return globalThis.navigator?.hid??null}function rV(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function iV(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&rV(e)===rV(t)&&!!e.productName}var aV=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(iV(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 oV=null;function sV(){return oV||=new aV,oV}const cV=4194304;function lV(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 uV(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function dV(e){e.opened||await e.open()}function fV(e,t){if(e>4194304)throw Error(`${t} exceeds the ${cV}-byte (4 MiB) v1 limit`)}function pV(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function mV(e,t){return(await t.getDevices()).map(t=>lV(e.register(t),t))}async function hV(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>lV(e.register(t),t))}function gV(e,t){return lV(t,uV(e,t))}async function _V(e,t){await uV(e,t).open()}async function vV(e,t){await uV(e,t).close()}async function yV(e,t,n,r){fV(r.byteLength,`send report payload`);let i=uV(e,t);await dV(i),await i.sendReport(n,r)}async function bV(e,t,n,r){fV(r.byteLength,`send feature report payload`);let i=uV(e,t);await dV(i),await i.sendFeatureReport(n,r)}async function xV(e,t,n){let r=uV(e,t);return await dV(r),{reportId:n,bytes:pV(await r.receiveFeatureReport(n))}}async function SV(e,t,n){let r=uV(e,t);await dV(r);let i=e=>{n({reportId:e.reportId,bytes:pV(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const CV=6e4;function wV(){return tT()}function TV(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),CV);nT(`hid-device`,e??[],void 0,{timeoutMs:CV}).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 EV(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var DV=class{registry;constructor(e){this.registry=e}hid(){let e=nV();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return mV(this.registry,this.hid())}async request(e){if(wV()){let t=await TV(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=>lV(this.registry.register(e),e))}return hV(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(gV(this.registry,e))}open(e){return _V(this.registry,e)}close(e){return vV(this.registry,e)}sendReport(e,t,n){return yV(this.registry,e,t,EV(n))}sendFeatureReport(e,t,n){return bV(this.registry,e,t,EV(n))}async receiveFeatureReport(e,t){let n=await xV(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return SV(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},OV=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:EV(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:EV(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 kV(e,t){return e&&nV()?new DV(sV()):t?new OV(t):null}function AV(e){return async function(t,n){let r=t instanceof Request?t:null,i=jV(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=NV(r?.headers,n?.headers),s=await IV(n,r,a,o);s.defaultContentType&&!PV(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 jV(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function MV(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 NV(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=MV(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function PV(e,t){return FV(e,t)!==void 0}function FV(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function IV(e,t,n,r){if(e&&`body`in e&&e.body!==void 0)return LV(e.body,n);if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=FV(r,`content-type`)??``,a=e&&(!i||!b(i));return{body:n.byteLength===0?void 0:a?we(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function LV(e,t){if(Un(e)){if(t===`GET`||t===`HEAD`)return{};let n=await Wn(e);return{body:n.bytes,defaultContentType:n.contentType}}return{body:await RV(e,t),defaultContentType:BV(e,t)}}async function RV(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 we(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 zV(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function BV(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!zV(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function VV(){return globalThis.navigator?.serial??null}var HV=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 UV=null;function WV(){return UV||=new HV,UV}const GV=4194304;function KV(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 qV(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function JV(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function YV(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 XV(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 ZV(e){if(await XV(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function QV(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await ZV(t);return n.map(t=>{let n=e.register(t);return KV(n,e.get(n))})}async function $V(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return KV(i,e.get(i))}function eH(e,t){return KV(t,qV(e,t))}async function tH(e,t,n){let r=qV(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 nH(e,t){let n=qV(e,t);await XV(n);try{await n.port.close()}catch(e){if(!rH(e))throw e}n.opened=!1}function rH(e){let t=e instanceof Error?e.message:String(e);return/already closed|not open/i.test(t)}function iH(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 aH(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 oH(e,t,n){let r=qV(e,t),i=Math.min(n.maxBytes??4194304,GV),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=YV(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=iH(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=JV(c,a.value);let e=u();if(e)return e}}return c}async function sH(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${GV}-byte (4 MiB) v1 limit`);return await aH(qV(e,t)).write(n),n.length}async function cH(e,t){return qV(e,t).port.getSignals()}async function lH(e,t,n){await qV(e,t).port.setSignals(n)}const uH=6e4;function dH(){return tT()}function fH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),uH);nT(`serial-port`,e??[],void 0,{timeoutMs:uH}).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 pH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var mH=class{registry;constructor(e){this.registry=e}serial(){let e=VV();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return QV(this.registry,this.serial())}async request(e){if(dH()){let t=await fH(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 KV(r,this.registry.get(r))}return $V(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(eH(this.registry,e))}open(e,t){return tH(this.registry,e,t)}close(e){return nH(this.registry,e)}read(e,t){return oH(this.registry,e,t)}write(e,t){return sH(this.registry,e,t)}getSignals(e){return cH(this.registry,e)}setSignals(e,t){return lH(this.registry,e,t)}},hH=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?pH(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:pH(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 gH(e,t){return e&&VV()?new mH(WV()):t?new hH(t):null}const _H=n(`usb`);async function vH(){return import(`./usb-claim-broker-C5dFP5bv.js`)}function yH(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function bH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${Za}-byte (4 MiB) v1 limit`)}function xH(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function SH(e,t){return(await t.getDevices()).map(t=>Ka(e.register(t),t))}async function CH(e,t,n){let r=await t.requestDevice({filters:n});return Ka(e.register(r),r)}function wH(e,t){return Ka(t,yH(e,t))}async function TH(e,t){await yH(e,t).open()}async function EH(e,t,n){await IH(e,t,`close`,n)}async function DH(e,t,n){await yH(e,t).selectConfiguration(n)}async function OH(e,t,n,r){let i=r?.owner??`usb`,a=yH(e,t),o=await vH(),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 kH(e,t){let n=await vH(),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 AH(e,t,n,r){let i=r?.owner??`usb`,a=yH(e,t),o=await vH(),s=o.claimOwner(e,t,n);if(s&&s!==i)throw new qa({handle:t,holder:s,op:`release`,interfaceNumber:n});await a.releaseInterface(n),o.releaseInterfaceClaim(e,t,n,i)}async function jH(e,t,n,r){bH(r,`control-in length`);let i=await yH(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?xH(i.data):new ArrayBuffer(0)}}async function MH(e,t,n,r){bH(r.byteLength,`control-out payload`);let i=await yH(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function NH(e,t,n,r){bH(r,`transfer-in length`);let i=await yH(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?xH(i.data):new ArrayBuffer(0)}}async function PH(e,t,n,r){bH(r.byteLength,`transfer-out payload`);let i=await yH(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function FH(e,t,n){await IH(e,t,`reset`,n)}async function IH(e,t,n,r){let i=r?.owner??`usb`,a=r?.force??!1,o=yH(e,t),s=await vH(),c=s.listClaims(e,t);if(c.length>0){let e=c.map(e=>`${e.interfaceNumber}=${e.owner}`).join(`, `);_H.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 LH(e,t,n,r){await yH(e,t).clearHalt(n,r)}const RH=6e4;function zH(){return tT()}function BH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),RH);nT(`usb-device`,e??[],void 0,{timeoutMs:RH}).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 VH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var HH=class{registry;constructor(e){this.registry=e}usb(){let e=Ya();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return SH(this.registry,this.usb())}async request(e){if(zH()){let t=await BH(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 Ka(this.registry.register(n),n)}return CH(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(wH(this.registry,e))}open(e){return TH(this.registry,e)}close(e,t){return EH(this.registry,e,UH(t))}selectConfig(e,t){return DH(this.registry,e,t)}claim(e,t,n){return OH(this.registry,e,t,UH(n))}release(e,t,n){return AH(this.registry,e,t,UH(n))}async controlIn(e,t,n){let r=await jH(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return MH(this.registry,e,t,VH(n))}async transferIn(e,t,n){let r=await NH(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return PH(this.registry,e,t,VH(n))}clearHalt(e,t,n){return LH(this.registry,e,t,n)}reset(e,t){return FH(this.registry,e,UH(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 kH(this.registry,e)}};function UH(e){return{...e,owner:e?.owner??`shell`}}var WH=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:VH(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:VH(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 GH(e,t){return e&&Ya()?new HH(Xa()):t?new WH(t):null}function KH(e,t,n,r={}){let{header:i,window:a}=Qz(t),o=new Map,s=!1,c=r.dispatch??(e=>Mz(e)?Fz(e):Tz(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}=Xz(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 qH=n(`realm-host`);let JH=0;function YH(e,t,n={}){let r=new Map,i=new Map,a=`${Ja}:${++JH}`,o=n.syncFsBridgeEnabled?bz({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;XH(e,i,t,n,l,u,f)};e.addEventListener(`message`,p);let m=o&&n.syncSab?KH(e,n.syncSab,o):void 0;return e.start?.(),{syncFsToken:o,dispose:()=>{if(!s){s=!0,m?.dispose(),o&&Cz(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??eU(n)).dropOwner?.(a)?.catch(()=>{})}catch{}}}}}async function XH(e,t,n,r,i,a,o){try{let s=await ZH(t,n,r,i,a,o),c={type:`realm-rpc-res`,id:t.id,result:s},l=VU(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 ZH(e,t,n,r,i,a){switch(e.channel){case`vfs`:return iU(e.op,e.args,t,n.onHostFsMutation);case`exec`:return _U(e.op,e.args,t,a);case`fetch`:return xU(e.op,e.args,t);case`browser`:return TU(e.op,e.args,QH(n),n);case`usb`:return RU(e.op,e.args,eU(n),i);case`serial`:return zU(e.op,e.args,tU(n));case`hid`:return BU(e.op,e.args,nU(n),r);case`module`:return CU(e.op,e.args,t);case`wasm`:return wU(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function QH(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 $H(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 eU(e){if(e.usbBackend)return e.usbBackend;let t=GH(u(),l());if(!t)throw Error(`usb is not available in this runtime`);return t}function tU(e){if(e.serialBackend)return e.serialBackend;let t=gH(u(),l());if(!t)throw Error(`serial is not available in this runtime`);return t}function nU(e){if(e.hidBackend)return e.hidBackend;let t=kV(u(),l());if(!t)throw Error(`hid is not available in this runtime`);return t}function rU(e){return[...e.deleted,...e.created.map(e=>e.path),...e.modified.map(e=>e.path)]}async function iU(e,t,n,r){let i=typeof t[0]==`string`?t[0]:null,a=i===null?null:n.fs.resolvePath(n.cwd,i);switch(e){case`readFile`:return n.fs.readFile(a);case`readFileBinary`:return n.fs.readFileBuffer(a);case`writeFile`:return await n.fs.writeFile(a,t[1]),a&&r?.([a]),!0;case`writeFileBinary`:return await n.fs.writeFile(a,t[1]),a&&r?.([a]),!0;case`readDir`:return n.fs.readdir(a);case`exists`:return n.fs.exists(a);case`stat`:{let e=await n.fs.stat(a);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(a,{recursive:!0}),!0;case`rm`:return await n.fs.rm(a,{recursive:!0}),a&&r?.([a]),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),{renameViaFs:i}=await import(`./rename-via-fs-ckVY1Ljv.js`);return await i(n.fs,a,e),r?.(a?[a,e]:[e]),!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 pU(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await mU(n,e),r?.(rU(e)),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const aU=10485760;function oU(e){return e.fileCount>=500||e.totalBytes>=aU}function sU(e){return e.entries.length>=2e4}async function cU(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 lU(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 uU(e,t,n,r,i){if(n>1048576||oU(r)||r.totalBytes+n>aU){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 dU(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function dU(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await cU(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function fU(e,t,n){if(sU(n))return;let r=[t];for(;r.length>0;){if(sU(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await lU(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await cU(e,t,r,n):a.isFile&&await uU(e,t,a.size,n,r)}}async function pU(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await fU(e,t,n),t!==`/tmp`&&await fU(e,`/tmp`,n),{entries:n.entries}}async function mU(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 hU=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),gU=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function _U(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 yU(t,n,r);if(e===`kill`)return bU(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function vU(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 yU(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??{};vU(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 bU(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&hU.has(r)?r:`SIGTERM`;gU.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 xU(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?AV(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 SU(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 CU(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=SU(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return tV({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:RB({ipk:s}),transpileEntry:zB({ipk:s})})}async function wU(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 Ga(e=>n.fs.readFileBuffer(e),i)}async function TU(e,t,n,r){switch(e){case`findTab`:return OU(n,t[0]??{});case`ensureTab`:{let e=t[0];return kU(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return AU(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return AU(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return PU(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return FU(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await $H(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return $H(r).update(e,n)}case`wsClose`:{let e=t[0];return $H(r).close(e)}case`wsList`:return $H(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 NU(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function EU(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function DU(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=EU()?l():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){qH.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function OU(e,t){let n=await DU(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=IU(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 kU(e,t,n){let r=await DU(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=LU(t);if(e){let t=r.find(t=>LU(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function AU(e,t,n,r){return e.withTab(t,async e=>jU(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function jU(e){if(typeof e!=`string`)return e;let t=MU(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=MU(t);if(typeof e==`object`&&e)return e}return t}return e}function MU(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 NU(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(){
|
|
1564
1564
|
try {
|
|
1565
1565
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1576,7 +1576,7 @@ except BaseException:
|
|
|
1576
1576
|
})()`,{returnByValue:!0}))return})}async function PU(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 FU(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 IU(e){try{return new URL(e).hostname}catch{return null}}function LU(e){try{return new URL(e).origin}catch{return null}}async function RU(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 zU(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 BU(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 VU(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[]}const HU={SIGKILL:137,SIGINT:130,SIGTERM:143};function UU(e,t){let n=Math.max(0,e)/1e3;return`--- killed after ${n<10?n.toFixed(2).replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``):String(Math.round(n))}s (exit ${t}) ---\n`}function WU(e,t){for(let n of t)e.pendingByPath.delete(n)}function GU(e,t){if(e.type===`realm-output`){let n=e;return n.stream===`stdout`?t.stdout+=n.chunk:t.stderr+=n.chunk,`live`}if(e.type===`realm-fs-write`){let n=e;return t.pendingByPath.set(n.path,{op:`write`,path:n.path,bytes:n.bytes}),`live`}if(e.type===`realm-fs-delete`){let n=e;return t.pendingByPath.set(n.path,{op:`delete`,path:n.path}),`live`}return e.type===`realm-done`?`done`:e.type===`realm-error`?`error`:`live`}async function KU(e,t,n){try{if(t.op===`write`){let n=e.fs?.writeFile?.bind(e.fs);n&&await n(t.path,t.bytes)}else{let n=e.fs?.rm?.bind(e.fs);n&&await n(t.path,{recursive:!0})}}catch(e){let r=e instanceof Error?e.message:String(e),i=t.op===`write`?`write`:`delete`;n.stderr+=`[sync-fs] ERROR: ${i} of ${t.path} was NOT persisted: ${r}\n`}}async function qU(e,t,n){for(let r of e)await KU(t,r,n)}function JU(e,t,n){return{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,...t.syncFsToken===void 0?{}:{syncFsToken:t.syncFsToken},...n?{syncSab:n}:{}}}async function YU(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?XU(e.syncSabBytes):void 0,a={stdout:``,stderr:``,pendingByPath:new Map},o=YH(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}:{},onHostFsMutation:e=>WU(a,e)});return new Promise(t=>{let s=!1,c=!1,l=null,u=null,d=null,f=null,p=()=>{if(!c){c=!0,u&&r.controlPort.removeEventListener(`message`,u),r.removeEventListener&&(d&&r.removeEventListener(`error`,d),f&&r.removeEventListener(`messageerror`,f)),l?.();try{r.terminate()}catch{}}},m=(r,i)=>{p(),o.dispose(),e.pm.exit(n.pid,i),t(r)},h=(e,t)=>{s||(s=!0,Promise.resolve().then(()=>m(e,t)))},g=t=>{s||(s=!0,Promise.resolve().then(()=>{let r=[...a.pendingByPath.values()];a.pendingByPath.clear(),p(),qU(r,e.ctx,a).finally(()=>{let e=UU(Date.now()-n.startedAt,t);m({stdout:a.stdout,stderr:a.stderr+e,exitCode:t},t)})}))};u=e=>{let t=e.data,n=GU(t,a);if(n===`done`){let t=e.data;h({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(n===`error`){let t=e.data;h({stdout:a.stdout,stderr:a.stderr+t.message+`
|
|
1577
1577
|
`,exitCode:1},1)}},d=e=>{let t=e.message??`realm error`;h({stdout:a.stdout,stderr:a.stderr+t+`
|
|
1578
1578
|
`,exitCode:1},1)},f=()=>{h({stdout:a.stdout,stderr:a.stderr+`realm-runner: worker message could not be deserialized
|
|
1579
|
-
`,exitCode:1},1)},l=e.pm.onSignal((e,t)=>{if(e.pid!==n.pid)return;let r=HU[t];r!==void 0&&g(r)}),r.controlPort.addEventListener(`message`,u),r.addEventListener&&(r.addEventListener(`error`,d),r.addEventListener(`messageerror`,f)),r.controlPort.postMessage(JU(e,o,i))})}function XU(e){if($z())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let ZU=!1;function QU(e){ZU=e}function $U(){return ZU}const eW=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 tW(e){return eW[e]??null}function nW(e,t){let n=tW(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let rW=null;function iW(e){let t=rW;return rW=e,t}async function aW(){if(!rW)return{};try{return await rW()??{}}catch{return{}}}function oW(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1579
|
+
`,exitCode:1},1)},l=e.pm.onSignal((e,t)=>{if(e.pid!==n.pid)return;let r=HU[t];r!==void 0&&g(r)}),r.controlPort.addEventListener(`message`,u),r.addEventListener&&(r.addEventListener(`error`,d),r.addEventListener(`messageerror`,f)),r.controlPort.postMessage(JU(e,o,i))})}function XU(e){if($z())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let ZU=!1;function QU(e){ZU=e}function $U(){return ZU}const eW=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 tW(e){return eW[e]??null}function nW(e,t){let n=tW(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let rW=null;function iW(e){let t=rW;return rW=e,t}async function aW(){if(!rW)return{};try{return await rW()??{}}catch{return{}}}function oW(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-KxT17gu_.js`).then(e=>e.t);return nW(t(),e())}}async function sW(e,t,n,r,i={}){return await n.fs.exists(e)?cW(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 cW(e,t,n,r,i={}){let a=i.realmFactory??lW(),o=r?.processManager??fW()??dW(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await YU({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await aW(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:Qa(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:$U()})}function lW(){return typeof Worker<`u`||typeof document<`u`?wB():bB()}let uW=null;function dW(){return uW||=new va,uW}function fW(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function pW(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 mW=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=Yt();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?hW(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=gW(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:gW(i)})})}};async function hW(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function gW(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function _W(e,t){return t.length?`${e} ${t.join(` `)}`:e}function vW(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function yW(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:vW(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 bW={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}},xW=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function SW(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 CW(e,t){switch(e.type){case`CommandSubstitution`:return PW(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=CW(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function wW(e,t){let n=0;for(let r of e.parts){let e=CW(r,t);if(e===null)return null;n+=e}return n}function TW(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=wW(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=wW(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=SW(e.name);if(r===null||xW.has(r))return null;if(!t.has(r))return n;n+=1;let i=bW[r];if(i){let r=e.args.map(SW);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(xW.has(a))return null;t.has(a)&&(n+=1)}return n}function EW(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 DW(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||SW(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=SW(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 OW(e){let t=0;for(let n of e){let e=n.type===`Word`?kW(n.word):EW(n);if(e===null)return null;t+=e}return t}function kW(e){let t=DW(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=OW(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function AW(e){let t=0;for(let n of e){let e=kW(n);if(e===null)return null;t+=e}return t}function jW(e,t){let n=0;for(let r of e){let e=NW(r,t);if(e===null)return null;n+=e}return n}function MW(e,t){switch(e.type){case`SimpleCommand`:return TW(e,t);case`For`:{if(!e.words)return null;let n=AW(e.words),r=jW(e.body,t);return n===null||r===null?null:e.words.filter(e=>DW(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return jW(e.body,t);case`FunctionDef`:return 0;default:return null}}function NW(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=MW(e,t);if(r===null)return null;n+=r}return n}function PW(e,t){return jW(e.statements,t)}function FW(e,t){let n=PW(e,t);return{totalSteps:n!==null&&n>0?n:null}}function IW(e){return e.split(`
|
|
1580
1580
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var LW=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 RW=globalThis.setTimeout.bind(globalThis);function zW(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function BW(e,t={}){let n=t.now??Date.now,r=t.setTimeout??RW,i=t.isAborted??(()=>!1),a=t.label??zW,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 VW=globalThis.setTimeout.bind(globalThis);function HW(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 UW(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 WW(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??VW;return{...e,async execute(n,a){let o=UW(n),s=o>=0?HW(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=_W(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 GW=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 KW(e,t,n={}){if((n.skip??GW).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=_W(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 qW=new Map([[`jsh`,`node`]]);function JW(e,t){return`${qW.get(e)??e} ${t.join(` `)}`.trim()}function YW(e){return Jr(`sudo`,e)}async function XW(e,t){let n=e.trim();if(!n||Lr(Nr(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n,...t.reason?{reason:t.reason}:{}});if(r.decision===`deny`)return{allowed:!1,message:YW(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}function ZW(e){let t=e.replace(/\s+/g,` `).trim();if(t.length<=300)return t;let n=Array.from(t);return n.length<=300?t:`${n.slice(0,299).join(``).trimEnd()}…`}const QW=`__SLICC_SUDO_REASON`,$W=/^#!/;function eG(e){let t=[];for(let n of e.split(`
|
|
1581
1581
|
`)){let e=n.trim();if(e.length===0){if(t.length>0)break;continue}if(!e.startsWith(`#`))break;if($W.test(e))continue;let r=e.replace(/^#+/,``).trim();r&&t.push(r)}return ZW(t.join(` `))}const tG={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 nG(e,t=[],n){let r=tG[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${ui(n)}</div>`:``;return`
|
|
1582
1582
|
<div class="sprinkle-action-card">
|
|
@@ -1700,7 +1700,7 @@ Examples:
|
|
|
1700
1700
|
skill list
|
|
1701
1701
|
skill info bluebubbles
|
|
1702
1702
|
skill read bluebubbles
|
|
1703
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1703
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-C058JDJA.js`).then(e=>e.t);try{switch(r){case`list`:return GG(t,e,i);case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1704
1704
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:UG(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
|
|
1705
1705
|
`,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+`
|
|
1706
1706
|
`,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 qG=[{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=>Co(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=>S(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 JG(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=qG.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 YG(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function XG(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 ZG(e,t,n,r){let i=await XG(e,t);return co(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?YG(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function QG(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await ZG(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 lo(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 $G(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 ho(t),d=await _o(s,c,o.ref,u,!0,l||void 0);if(d&&r.sha===d&&await eK(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await tK(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 QG(e,`${to}/${n}`,p,r),v=g.length>0||_.length>0;if(a)return{...o,outcome:v?`updated`:`current`,changes:h};let y=d??r.sha;return v&&await oK(e,{changes:h,writes:g,removals:_}),await vo(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 eK(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 tK(e,t,n,r,i,a,o){let s=await fo(e,t,a,i??`main`);if(s.status===`ok`){let i=oo(s.files),a=n||nK(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:aK(i,a),path:a}}try{return{files:iK(rK(await uo(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 nK(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 rK(e){return new Map([...e].filter(([e])=>so(e)))}function iK(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function aK(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 iK(r)}async function oK(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 sK(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 RG(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${to}/${n}/SKILL.md`,u=await XG(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&IG(new TextDecoder().decode(u))===IG(c.content);if(YG(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${to}/${n}`,{recursive:!0}),await e.writeFile(l,d),await vo(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function cK(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 lK(e,t,n,r){let i=Co(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 uK(e,t,n){if(t.length===0){let t=await go(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await yo(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?lK(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 dK(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1711,7 +1711,7 @@ Examples:
|
|
|
1711
1711
|
`}function mK(e,t,n,r,i){let a=t?`Skill update (dry run — nothing written):
|
|
1712
1712
|
`:`Skill update:
|
|
1713
1713
|
`;for(let n of e)a+=cK(n,t);if(i.length>0&&(a+=pK(i)),!n&&r&&e.length>0){let n=i.length>0?`all ${fK(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 hK(e,t,n){let{targets:r,missing:i,skipped:a}=await uK(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 sK(e,t,i.name,i.provenance,n.dryRun):await $G(e,t,i.name,i.provenance,n.branch,n.dryRun));return{results:o,skipped:a,missing:i}}async function gK(e,t,n){let r=JG(e);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{results:i,missing:a,skipped:o}=await hK(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`:mK([],r.dryRun,!1,!0,o),stderr:``,exitCode:0}:{stdout:``,stderr:a.length?a.map(dK).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 So();let l=a.map(dK).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:mK(i,r.dryRun,c,u,o),stderr:l,exitCode:+!u}}function _K(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 vK(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 yK(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}${vK(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(`
|
|
1714
|
-
`)}\n`}async function bK(e,t){let n=await(await import(`./skills-
|
|
1714
|
+
`)}\n`}async function bK(e,t){let n=await(await import(`./skills-C058JDJA.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${BG()}`,stderr:``,exitCode:0}:{stdout:HG(n,`Discoverable local skills`),stderr:``,exitCode:0}}async function xK(e,t,n){let{results:r,skipped:i}=await hK(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:yK(r,i),stderr:c,exitCode:+!s}}async function SK(e,t,n){let r=_K(e);return r.error?{stdout:``,stderr:`${r.error}\n`,exitCode:1}:r.outdated?xK(t,n,r.json):bK(t,r.json)}async function CK(e,t){let n=`${no}/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(mo(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=xe(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=xo(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 wK(e,t){let n=`${no}/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: ${mo(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=xe(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=xo(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 TK=[{label:`Tessl`,host:new URL(no).host,fetch:CK},{label:`browse.sh`,host:new URL(ao).host,fetch:AG}];function EK(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 DK(e,t,n=1){let r=await Promise.allSettled(TK.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=EK(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=TK[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+=`
|
|
1715
1715
|
`}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:
|
|
1716
1716
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
1717
1717
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
@@ -1734,7 +1734,7 @@ Examples:
|
|
|
1734
1734
|
`,{stdout:s,stderr:``,exitCode:0}}function PK(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1735
1735
|
`,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
|
|
1736
1736
|
`,exitCode:1}}function FK(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`||!S(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
|
|
1737
|
-
`,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=PK(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 IK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-
|
|
1737
|
+
`,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=PK(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 IK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-C058JDJA.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 yo(n,t),a=i?bo(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:UG(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+`
|
|
1738
1738
|
`,stderr:``,exitCode:0}}async function LK(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 To(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 RK(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 wo(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 zK(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await wo(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 BK(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 VK(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await ho(r),l=await Eo(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:BK(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:BK(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 fo(i,a,r,o);if(e.status===`ok`){let r=await _o(i,a,o,c,!0,s),l=await LK(u,i,a,oo(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 RK(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await zK(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 So()),{stdout:p,stderr:m,exitCode:+!!m}}async function HK(e,t,n,r){switch(e[0]){case`tabs`:return MK(t,n,r,e.includes(`--json`));case`recommendations`:return NK(t,n,e.includes(`--install`));case`update`:case`upgrade`:return gK(e.slice(1),t,n);case`list`:return SK(e.slice(1),t,n);case`info`:case`read`:return IK(e[0],e[1],t);case`search`:return WK(e,n);default:return null}}function UK(e,t,n){return N(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return WG();let a=await HK(r,e,t,n);if(a)return a;let o=FK(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return WG();if(o.sourceRef.startsWith(`tessl:`))return GK(o.sourceRef,o.force,e,t);let s=NG(o.sourceRef);if(s)return zG(s.hostname,s.task,e,t,o.force);let c=Co(o.sourceRef);return c?VK(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 WK(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?DK(a,t,i):WG()}async function GK(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1739
1739
|
`,exitCode:1};let a=await wK(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await ho(r);return wo(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function KK(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1740
1740
|
|
|
@@ -2155,7 +2155,7 @@ Examples:
|
|
|
2155
2155
|
`;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+=`
|
|
2156
2156
|
`;return t}async function TX(e,t){let n=P(e.slice(1),{});if(`error`in n)return SX(n.error);if(!t()){let e=await hX();if(!e)return vX(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2157
2157
|
`,stderr:``,exitCode:0}:{stdout:wX(t),stderr:``,exitCode:0}}let{ok:r,data:i}=await bX(`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
|
|
2158
|
-
`,stderr:``,exitCode:0}:{stdout:wX(a),stderr:``,exitCode:0}}async function EX(e,t){let n=e[0],r=P(e.slice(1),{});if(`error`in r)return SX(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 hX();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}:vX(`delete`)}let{ok:a,status:o,data:s}=await bX(`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 DX(e={}){let t=e.hasLocalNodeServer??(()=>!1);return N(`crontask`,async(e,n)=>{let r=e[0];if(!r||F(e,{valueFlags:xX}))return yX();try{switch(r){case`create`:return await CX(e,n.env,t);case`list`:return await TX(e,t);case`delete`:case`kill`:return await EX(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 OX(e){return N(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2158
|
+
`,stderr:``,exitCode:0}:{stdout:wX(a),stderr:``,exitCode:0}}async function EX(e,t){let n=e[0],r=P(e.slice(1),{});if(`error`in r)return SX(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 hX();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}:vX(`delete`)}let{ok:a,status:o,data:s}=await bX(`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 DX(e={}){let t=e.hasLocalNodeServer??(()=>!1);return N(`crontask`,async(e,n)=>{let r=e[0];if(!r||F(e,{valueFlags:xX}))return yX();try{switch(r){case`create`:return await CX(e,n.env,t);case`list`:return await TX(e,t);case`delete`:case`kill`:return await EX(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 OX(e){return N(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-BMeDofYZ.js`);return r(e,t,n)})}const kX=`slicc-fs`;async function AX(){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===kX)}catch{return!0}}async function jX(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(kX)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function MX(){if(!await AX())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await jX();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 NX(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2159
2159
|
|
|
2160
2160
|
Usage:
|
|
2161
2161
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -2647,7 +2647,7 @@ Options:
|
|
|
2647
2647
|
`,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 c2(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!Tte(e))throw e}t.sessionDirsCreated=!0}}async function l2(e,t,n,r){try{return await e.withTab(n,async e=>{let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:l,refToFrameId:u}=await c(e),d={url:i,title:a,refToSelector:s,refToBackendNodeId:l,refToFrameId:u,content:o,timestamp:Date.now()};r.snapshots.set(n,d);let f=[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
2648
2648
|
`),p=`/.playwright/snapshots/page-${aa(new Date)}.yml`;return await t.writeFile(p,f),p})}catch{return null}}async function u2(e,t,n){await c2(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(`
|
|
2649
2649
|
`)+`
|
|
2650
|
-
`,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 d2(){return import(`./snapshot-features-
|
|
2650
|
+
`,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 d2(){return import(`./snapshot-features-BrjTvoVG.js`)}async function f2(e,t,n,r){let i=await e.getAccessibilityTreeForFrame(r.frameId),a=new Map,o=new Map,c=new Map,l=s(i,a,o,{value:0},``,`f1`);for(let e of a.keys())c.set(e,r.frameId);let u=l.join(`
|
|
2651
2651
|
`);return t.snapshots.set(n,{url:r.url,title:r.name,refToSelector:a,refToBackendNodeId:o,refToFrameId:c,content:u,timestamp:Date.now()}),u}async function p2(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() {
|
|
2652
2652
|
this.scrollIntoView({ block: 'center' });
|
|
2653
2653
|
const r = this.getBoundingClientRect();
|
|
@@ -2725,7 +2725,7 @@ Options:
|
|
|
2725
2725
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2726
2726
|
return el.files.length;
|
|
2727
2727
|
})()`,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`,w2],[`state-load`,T2],[`console`,a1],[`requests`,K0],[`request`,q0],[`request-headers`,J0],[`request-body`,Y0],[`response-headers`,X0],[`response-body`,Z0],[`mousemove`,Z1],[`mousedown`,Q1],[`mouseup`,$1],[`mousewheel`,e0],[`drop`,t0],[`route`,a2],[`route-list`,o2],[`unroute`,s2],[`generate-locator`,h1],[`highlight`,g1]]);function J2(){let e=(oa.string??[]).map(e=>`--${e}`),t=new Set(oa.boolean??[]);for(let[e,n]of Object.entries(oa.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 Y2(e){return e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e)}function X2(e){return{...e,bool:[...e.bool??[],`--_noiframes`],value:[...e.value??[],`--_noiframes`]}}const Z2=2e3;function Q2(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 $2(e,t,n,r){if(!t||typeof e.getTabLockStats!=`function`)return r;let i=e.getTabLockStats(),a=i.totalWaitMs-t.totalWaitMs;if(a<Z2)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>=Z2?`${(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.
|
|
2728
|
-
`;return{...r,stderr:r.stderr+c}}async function e4(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Ote(e,t.tab,n):null)??r}\n`,exitCode:1}}function t4(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 n4(e,t,n){let r=q2.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?t4(e,t,void 0):a}catch(r){return i?.aborted?t4(e,t,r):await e4(n.browser,n.flags,r)}}async function r4(e,t,n,r){let i=P(Y2(n),X2(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Dte(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-
|
|
2728
|
+
`;return{...r,stderr:r.stderr+c}}async function e4(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Ote(e,t.tab,n):null)??r}\n`,exitCode:1}}function t4(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 n4(e,t,n){let r=q2.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?t4(e,t,void 0):a}catch(r){return i?.aborted?t4(e,t,r):await e4(n.browser,n.flags,r)}}async function r4(e,t,n,r){let i=P(Y2(n),X2(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Dte(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-CZ_jut-Q.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 i4(e,t,n){let r=t?wte(t,n):null,i=J2();return N(e,async(a,o)=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`){let{formatHelp:t}=await import(`./help-CZ_jut-Q.js`);return{stdout:t(e)+`
|
|
2729
2729
|
`,stderr:``,exitCode:0}}let s=a[0],c=a.slice(1),l=await r4(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=Q2(t,f),m=await n4(e,s,{browser:t,fs:n,state:r,positional:u,flags:d,scratchDir:Ba(o.env),onTab:(e,n)=>t.withTab(e,n,{signal:o.signal}),signal:o.signal}),h=d.tab??null,g=null;Ate.has(s)&&m.exitCode===0&&h&&(g=await l2(t,n,h,r));try{await u2(n,r,{command:s,args:c,result:m,snapshotPath:g,targetId:h})}catch{}return $2(t,p,f,m)})}const a4=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`,`tst`,`esbuild`,`biome`]],[`Packages`,[`ipk`,`hf`,`npm`,`i`,`ipx`,`npx`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...la,`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)`,[...jq]]]);function o4(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:
|
|
2730
2730
|
`);let a=[];for(let[e,t]of a4){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(`
|
|
2731
2731
|
`)+`
|
|
@@ -2983,7 +2983,7 @@ Common base URLs:
|
|
|
2983
2983
|
`)+`
|
|
2984
2984
|
`,stderr:``,exitCode:0}}function Cse(e,t){let n=t.models.length;return{stdout:[`✓ ${e} (${X3(t.runtime,!1)})`,` Saved ${n} model${n===1?``:`s`} to Settings:`,...Z3(t.models)].join(`
|
|
2985
2985
|
`)+`
|
|
2986
|
-
`,stderr:``,exitCode:0}}function wse(){return N(Y3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:bse(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
2986
|
+
`,stderr:``,exitCode:0}}function wse(){return N(Y3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:bse(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-KxT17gu_.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-Cw7-Quw-.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(Y3);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
2987
2987
|
`,exitCode:1};let c=await a(s,t(Y3)??void 0);if(!c.ok)return xse(s,c);if(o===`discover`){let e=n(Y3)??``;return i(Y3,e,s,c.models.join(`, `)),Cse(s,c)}return Sse(s,c)})}function Tse(){return{stdout:`usage: man <topic>
|
|
2988
2988
|
|
|
2989
2989
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3021,20 +3021,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3021
3021
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3022
3022
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3023
3023
|
short name resolves on the PATH.
|
|
3024
|
-
`);let n=P(e,{});if(`error`in n)return t6(n.error);if(n.positionals.length<2)return X(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return X(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return X(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3024
|
+
`);let n=P(e,{});if(`error`in n)return t6(n.error);if(n.positionals.length<2)return X(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return X(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return X(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-sD4MH5HN.js`).then(e=>e.r);if(await a(i,t.fs))return X(`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 Mse(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>o6(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 Zse(i,t);let m=await l6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-JhY8VUoS.js`);e({name:i,serverUrl:r,auth:u})}return e6([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${$3}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3025
3025
|
`)+`
|
|
3026
|
-
`)}async function Mse(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3027
|
-
`);let n=P(e,{});if(`error`in n)return t6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3026
|
+
`)}async function Mse(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-KxT17gu_.js`).then(e=>e.t),c=await Yse(r.oauthFetchImpl),l=r.oauthLauncher??await s6(),u=await i(e,n,c);Q3.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await es(Zt()),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt,scopes:m.scope}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,redirectUri:d,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function Nse(e,t){if(F(e))return e6(`usage: mcp list
|
|
3027
|
+
`);let n=P(e,{});if(`error`in n)return t6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-JhY8VUoS.js`);await r();let{listServers:i}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),a=await i(t.fs),o=Object.keys(a).sort();if(o.length===0)return e6("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 e6(n6(s))}function n6(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(`
|
|
3028
3028
|
`)+`
|
|
3029
3029
|
`}async function Pse(e,t){if(F(e))return e6(`usage: mcp search <query>
|
|
3030
3030
|
|
|
3031
3031
|
Case-insensitive substring search across the cached tools of every
|
|
3032
3032
|
registered MCP server. Matches tool name OR description and prints a
|
|
3033
3033
|
table of (server, tool, description, match-field) rows.
|
|
3034
|
-
`);let n=P(e,{});if(`error`in n)return t6(n.error);if(n.positionals.length===0)return X(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-
|
|
3035
|
-
`);let n=P(e,{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-
|
|
3034
|
+
`);let n=P(e,{});if(`error`in n)return t6(n.error);if(n.positionals.length===0)return X(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-JhY8VUoS.js`);await a();let{listServers:o}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),s=await o(t.fs),c=Object.keys(s).sort();if(c.length===0)return e6("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 e6(`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,Fse(e.description),e.match]);return e6(n6(u))}function Fse(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Ise(e,t){if(e.length===0||F(e))return e.length===0?X(`mcp delete: expected <name>`):e6(`usage: mcp delete <name>
|
|
3035
|
+
`);let n=P(e,{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-JhY8VUoS.js`);await i(r);let{deleteServer:o}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),s=await o(r,t.fs);await Qse(r,t),await $se(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-KxT17gu_.js`).then(e=>e.t);t().some(e=>e.providerId===c)&&(await e(c),l=!0)}catch(e){Q3.warn(`mcp delete: OAuth removal failed`,{providerId:c,error:e instanceof Error?e.message:String(e)})}let u=a(r);return!s&&!l&&!u?X(`mcp delete: no server, alias, or account found for "${r}"`):e6([`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(`
|
|
3036
3036
|
`)+`
|
|
3037
|
-
`)}async function Lse(e,t){if(e.length===0)return X(`mcp invoke: expected <name>`);if(F(e.slice(0,1)))return e6(zse());let n=P([e[0]],{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-
|
|
3037
|
+
`)}async function Lse(e,t){if(e.length===0)return X(`mcp invoke: expected <name>`);if(F(e.slice(0,1)))return e6(zse());let n=P([e[0]],{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-JhY8VUoS.js`);await a(r);let{getServer:o}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),s=await o(r,t.fs);if(!s)return X(`mcp invoke: unknown server "${r}" (run \`mcp add <url> ${r}\` first)`);let c=s.tools??[];if(i.length===0||F(i.slice(0,1)))return e6(Bse(r,s,c));let l=P([i[0]],{});if(`error`in l)return t6(l.error);let u=l.positionals[0];if(!u)return X(`mcp invoke: expected <tool>`);let d=c.find(e=>e.name===u);if(!d)return X(`mcp invoke: unknown tool "${u}" on "${r}" (run \`${r}\` to list tools)`);let{timeoutMs:f,remaining:p,warnings:m}=Rse(i.slice(1));if(F(p))return e6(Vse(r,d));let h=Hse(p,d.inputSchema);if(!h.ok)return X(`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?()=>o6(r):void 0,...f===void 0?{}:{timeoutMs:f}});await _.initialize();let v=Kse(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function Rse(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=r6(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=r6(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 r6(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 zse(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3038
3038
|
|
|
3039
3039
|
mcp invoke <name> List tools on <name>.
|
|
3040
3040
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3064,7 +3064,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3064
3064
|
|
|
3065
3065
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3066
3066
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3067
|
-
`);let n=P(e,{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3067
|
+
`);let n=P(e,{});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-JhY8VUoS.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),s=await a(r,t.fs);if(!s)return X(`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?()=>o6(r):void 0});try{await u.initialize()}catch(e){if(e instanceof l)return X(`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 l6(r,f,t);return e6(`Refreshed "${r}" — tools: ${d.length}, apps: ${f.length} (${p} sprinkle${p===1?``:`s`})\n`)}async function Jse(e,t){if(F(e))return e6(`usage: mcp auth <name> [--silent | --interactive]
|
|
3068
3068
|
|
|
3069
3069
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3070
3070
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3076,7 +3076,7 @@ Options:
|
|
|
3076
3076
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3077
3077
|
directly. Use after revoking a refresh token or
|
|
3078
3078
|
when the AS no longer accepts the cached one.
|
|
3079
|
-
`);let n=P(e,{bool:Ose});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`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 X(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3079
|
+
`);let n=P(e,{bool:Ose});if(`error`in n)return t6(n.error);let r=n.positionals[0];if(!r)return X(`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 X(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-JhY8VUoS.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-sD4MH5HN.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return X(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return X(`mcp auth: server "${r}" does not use OAuth`);if(!s)return X(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-DG3GRO0g.js`).then(e=>e.r),f=d(u);if(!f)return X(`mcp auth: provider "${u}" is not registered`);if(a)return await a6(r,f,t);if(!f.onSilentRenew)return i?X(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await a6(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 X(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);Q3.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?e6(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?X(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await a6(r,f,t)}async function a6(e,t,n){if(!t.onOAuthLogin)return X(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await s6(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?e6(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):X(`mcp auth: interactive login for "${e}" did not complete`)}async function o6(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-KxT17gu_.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DG3GRO0g.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){Q3.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function s6(){let{createOAuthLauncher:e}=await import(`./oauth-service-IlBYPvwr.js`);return e()}async function Yse(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 c6(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-CKF7L1oq.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 Xse(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3080
3080
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3081
3081
|
const { promisify } = require('util');
|
|
3082
3082
|
const { exec } = require('child_process');
|
|
@@ -3105,7 +3105,7 @@ try {
|
|
|
3105
3105
|
if (stdout) process.stdout.write(stdout);
|
|
3106
3106
|
if (stderr) process.stderr.write(stderr);
|
|
3107
3107
|
process.exit(exitCode);
|
|
3108
|
-
`}async function Zse(e,t){let n=await c6(t.fs);await n.mkdir($3,{recursive:!0}),await n.writeFile(`${$3}/${e}.jsh`,Xse(e)),t.scriptCatalog?.invalidateJsh()}async function Qse(e,t){let n=await c6(t.fs),r=`${$3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Q3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function $se(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3108
|
+
`}async function Zse(e,t){let n=await c6(t.fs);await n.mkdir($3,{recursive:!0}),await n.writeFile(`${$3}/${e}.jsh`,Xse(e)),t.scriptCatalog?.invalidateJsh()}async function Qse(e,t){let n=await c6(t.fs),r=`${$3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Q3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function $se(e,t){let{removeAppSprinkles:n}=await import(`./apps-yo7bohdm.js`);await n(e,t.fs)}async function l6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-yo7bohdm.js`);return(await r(e,t,n.fs)).length}catch(t){return Q3.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function u6(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function d6(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 ece(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 tce(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function nce(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 rce(e){let t=[`total: ${d6(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(`${d6(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${ece(e)}`)}return`${t.join(`
|
|
3109
3109
|
`)}\n`}function ice(e={}){return N(`meminfo`,async t=>{let n=nce(t);if(`error`in n)return u6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3110
3110
|
|
|
3111
3111
|
Usage:
|
|
@@ -3132,7 +3132,7 @@ Options:
|
|
|
3132
3132
|
-h, --help Show this help message
|
|
3133
3133
|
`}function hce(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function g6(e){return`$${e.toFixed(2)}`}const gce=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function _ce(e){let t=`${e.id} ${e.name??``}`;return!gce.test(t)}function vce(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 yce(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),vce(t)??t.replace(/-[\d.]+$/,``)}function bce(e){let t=new Map;for(let n of e){let e=yce(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function xce(e,t,n,r,i){let a=i?pce(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 Sce(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=`${g6(e.cost.input)} / ${g6(e.cost.output)}`,a=`${hce(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(`
|
|
3134
3134
|
`)+`
|
|
3135
|
-
`}function Cce(e){let t=P(e,{bool:sce,value:p6});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 wce(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 Tce(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(_ce);if(o.length===0)return[];let s=o.map(e=>xce(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=bce(s)),s}function Ece(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 Dce(e,t){if(F(e,{valueFlags:p6}))return{stdout:mce(),stderr:``,exitCode:0};let n=Cce(e);if(`error`in n)return m6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3135
|
+
`}function Cce(e){let t=P(e,{bool:sce,value:p6});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 wce(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 Tce(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(_ce);if(o.length===0)return[];let s=o.map(e=>xce(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=bce(s)),s}function Ece(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 Dce(e,t){if(F(e,{valueFlags:p6}))return{stdout:mce(),stderr:``,exitCode:0};let n=Cce(e);if(`error`in n)return m6(`models: ${n.error}`);let r=await import(`./account-store-KxT17gu_.js`).then(e=>e.t);if(r.getAccounts().length===0)return m6(`No provider accounts configured. Run the provider settings to add one.
|
|
3136
3136
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await fce(t,n.forceRefresh);e.length>0&&(l=e)}let u=wce(r,n,s);if(`error`in u)return m6(u.error);let d=[],f=[];for(let e of u){let t=Tce(r,e,a,o,l,n.allVersions);if(t.length===0){if(!n.allMode)return m6(`No models available for provider ${e}.\n`);continue}if(d.push(...t),!n.jsonMode){let n=r.getProviderConfig(e);f.push(Sce(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3137
3137
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3138
3138
|
`),f.push(Ece(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3190,7 +3190,7 @@ Examples:
|
|
|
3190
3190
|
`)}\n`,stderr:``,exitCode:0}}async function Kce(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3191
3191
|
`,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 qce(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3192
3192
|
`,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 Jce(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>
|
|
3193
|
-
`,exitCode:1}}async function Yce(e,t,n,r){switch(t){case`list`:return Gce(e,n);case`add`:return Kce(e,n,r);case`remove`:return qce(e,n,r);case`clear`:return Jce(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${x6()}`,exitCode:1}}}function Xce(){return N(`oauth-domain`,async e=>{if(e.length===0||F(e))return{stdout:x6(),stderr:``,exitCode:0};let t=P(e);if(`error`in t)return S6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3193
|
+
`,exitCode:1}}async function Yce(e,t,n,r){switch(t){case`list`:return Gce(e,n);case`add`:return Kce(e,n,r);case`remove`:return qce(e,n,r);case`clear`:return Jce(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${x6()}`,exitCode:1}}}function Xce(){return N(`oauth-domain`,async e=>{if(e.length===0||F(e))return{stdout:x6(),stderr:``,exitCode:0};let t=P(e);if(`error`in t)return S6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-KxT17gu_.js`).then(e=>e.t);try{return await Yce(a,n,r,i)}catch(e){return S6(e instanceof Error?e.message:String(e))}})}function Zce(){return N(`oauth-token`,async(e,t)=>{let{runOAuthToken:n}=await import(`./run-DePgFtOr.js`);return n(e,t)})}const Qce=[`--download`,`-d`,`--view`,`-v`],C6=[`--size`],w6={low:256,medium:768,high:1536};function T6(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
3194
3194
|
|
|
3195
3195
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
3196
3196
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -3216,7 +3216,7 @@ Examples:
|
|
|
3216
3216
|
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=xk(e,await Ea(t.fs,i?e:ja(e))),o;try{o=await r(a)}catch(e){return O6(`${e instanceof Error?e.message:String(e)}\n`)}return D6(`opened ${e} → ${a}${k6(o)}`)}async function fle(e,t,n,r){if(!Oa(e)&&e.endsWith(`.shtml`)&&t.fs)return sle(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return O6(`open: browser APIs are unavailable in this environment
|
|
3217
3217
|
`);if(Oa(e))return cle(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?lle(e,i,t,n.sizeSpec):n.download?ule(e,i,t,r.hasDom):dle(i,t,r.canOpenWindow,r.openExternal)}function ple(e){return N(`open`,async(t,n)=>{if(t.length===0||F(t,{valueFlags:C6}))return T6();let r=ale(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 T6();let c=globalThis.__slicc_sprinkleManager,u=typeof window<`u`&&typeof document<`u`,d=u?null:l(),f={canOpenWindow:!!e||u||!!d,hasDom:u,sprinkleManager:c,openExternal:ole(e,u,d)},p=[];for(let e of s){let t=await fle(e,n,{view:a,download:i,sizeSpec:o},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
3218
3218
|
`)+`
|
|
3219
|
-
`,stderr:``,exitCode:0}})}function mle(){return N(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-
|
|
3219
|
+
`,stderr:``,exitCode:0}})}function mle(){return N(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-Cs70ONoW.js`);return n(e,t)})}function A6(e=`pdftk`){return N(e,async(t,n)=>{let{runPdftk:r}=await import(`./run-B-t7kWH3.js`);return r(e,t,n)})}function hle(){return{stdout:`usage: pdftoppm [options] <input.pdf> [output-prefix]
|
|
3220
3220
|
|
|
3221
3221
|
Rasterize PDF pages to images. Writes <prefix>-<n>.<ext> per page, where <n>
|
|
3222
3222
|
is zero-padded to the digit width of the last page (out-1.png for a 9-page
|
|
@@ -3276,7 +3276,7 @@ Examples:
|
|
|
3276
3276
|
plugin list
|
|
3277
3277
|
plugin info my-plugin
|
|
3278
3278
|
plugin remove my-plugin
|
|
3279
|
-
`}function Dle(e={}){return N(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return P6(Ele());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await kle(i,a,e);case`list`:case`ls`:return await Nle(i,e);case`info`:return await Ple(i,e);case`validate`:return await Fle(i,a,e,Ba(n?.env));case`remove`:case`rm`:case`delete`:return await Ile(i,e);default:return F6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return F6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function L6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3279
|
+
`}function Dle(e={}){return N(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return P6(Ele());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await kle(i,a,e);case`list`:case`ls`:return await Nle(i,e);case`info`:return await Ple(i,e);case`validate`:return await Fle(i,a,e,Ba(n?.env));case`remove`:case`rm`:case`delete`:return await Ile(i,e);default:return F6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return F6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function L6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-CKF7L1oq.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 R6(e,t,n){let r=Lle(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-CCiLZQKP.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 Ole(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function z6(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${N6}/${t.map(Ole).join(`--`)}`}async function B6(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-C3GODUL3.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 V6(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function kle(e,t,n){if(F(e))return P6(`usage: plugin install <path|repo>
|
|
3280
3280
|
|
|
3281
3281
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3282
3282
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3287,19 +3287,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3287
3287
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3288
3288
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3289
3289
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3290
|
-
`);let r=I6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return F6(`plugin install: expected <path|repo>`);let i=await L6(n),a=await R6(r.positionals[0],t,i);if(a.kind===`error`)return F6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return F6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=z6(a.ref),s=a.ref.display;let e=await B6(a.ref,o,i,n.fetch);if(e)return F6(`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 V6(i,o),F6(`plugin install: plugin at ${s??o} was rejected:\n${H6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3290
|
+
`);let r=I6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return F6(`plugin install: expected <path|repo>`);let i=await L6(n),a=await R6(r.positionals[0],t,i);if(a.kind===`error`)return F6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return F6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=z6(a.ref),s=a.ref.display;let e=await B6(a.ref,o,i,n.fetch);if(e)return F6(`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 V6(i,o),F6(`plugin install: plugin at ${s??o} was rejected:\n${H6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-Ckv7LyPo.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await V6(i,o),F6(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await Mle(u,n),g=await jle(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),P6(Ale(u,h,g,s??o,l.diagnostics))}function Ale(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:`,H6(i)),c.join(`
|
|
3291
3291
|
`)+`
|
|
3292
|
-
`}async function jle(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-
|
|
3293
|
-
`);let n=I6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3292
|
+
`}async function jle(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-sD4MH5HN.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 Mle(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-sD4MH5HN.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 Nle(e,t){if(F(e))return P6(`usage: plugin list
|
|
3293
|
+
`);let n=I6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-Ckv7LyPo.js`),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return P6("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 P6(o.map(e=>e.map((e,t)=>e.padEnd(s[t])).join(` `)).join(`
|
|
3294
3294
|
`)+`
|
|
3295
3295
|
`)}async function Ple(e,t){if(F(e))return P6(`usage: plugin info <name>
|
|
3296
|
-
`);let n=I6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return F6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-
|
|
3296
|
+
`);let n=I6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return F6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-Ckv7LyPo.js`),a=await i(r,t.fs);if(!a)return F6(`plugin info: no installed plugin named "${r}"`);let o=await L6(t),{loadPluginFromDirectory:s}=await import(`./loader-Dw-TPPKt.js`),c=await s(o,a.root);if(!c.ok)return F6(`plugin info: plugin at ${a.root} no longer loads:\n${H6(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:`,H6(c.diagnostics)),P6(d.join(`
|
|
3297
3297
|
`)+`
|
|
3298
3298
|
`)}async function Fle(e,t,n,r){if(F(e))return P6(`usage: plugin validate <path|repo>
|
|
3299
3299
|
`);let i=I6(`validate`,e);if(!(`ok`in i))return i;if(i.positionals.length<1)return F6(`plugin validate: expected <path|repo>`);let a=await L6(n),o=await R6(i.positionals[0],t,a);if(o.kind===`error`)return F6(`plugin validate: ${o.message}`);let s,c=null;if(o.kind===`github`){if(!n.fetch)return F6(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);c=`${r}/.plugin-validate/${z6(o.ref).split(`/`).pop()}`;let e=await B6(o.ref,c,a,n.fetch);if(e)return F6(`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 V6(a,c)}if(!u.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${H6(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:`,H6(u.diagnostics)),P6(p.join(`
|
|
3300
3300
|
`)+`
|
|
3301
3301
|
`)}async function Ile(e,t){if(F(e))return P6(`usage: plugin remove <name>
|
|
3302
|
-
`);let n=I6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return F6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-
|
|
3302
|
+
`);let n=I6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return F6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-Ckv7LyPo.js`),o=await i(r,t.fs);if(!o)return F6(`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-sD4MH5HN.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(`${N6}/`);return c&&await V6(await L6(t),o.root),P6([`Removed agent plugin "${r}"`,` registry: removed`,` mcp servers: ${s} removed`,c?` files: removed (${o.root})`:` files: left in place (${o.root})`].join(`
|
|
3303
3303
|
`)+`
|
|
3304
3304
|
`)}function Lle(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 H6(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3305
3305
|
`)}const U6=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Rle=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],zle={running:`R`,pending:`S`,exited:`Z`,killed:`K`},Ble=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],W6=[`-o`,`--columns`];function Vle(e={}){return N(`ps`,async t=>{if(F(t,{valueFlags:W6}))return $le();let n=e.processManager??Hle();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -4926,7 +4926,7 @@ pass --wait to block and print the full result.`,Whe=new Set([`list`,`status`,`s
|
|
|
4926
4926
|
`),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 I7(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=P7(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=Lge(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(`
|
|
4927
4927
|
`),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 Lge(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 L7=n(`tool:bash`),R7=40960,z7=1048576,B7=`\0slicc-img:`;function Rge(e){let t=en(e).filter(e=>e.kind===`image`);if(t.length===0)return{text:e,markers:new Map};let n=new Set,r=z7;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=`${B7}${r}`;i.set(e,t.marker),a+=e}else a+=`[image dropped: a newer image in this command used up the ${z7/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 zge(e){let t=en(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 Bge(e){return e.replaceAll(RegExp(`${B7}\\d+`,`g`),`[image]`)}function V7(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 Vge(e,t,n,r){let{text:i,markers:a}=Rge(e),o=I7(i,{maxBytes:R7});if(!o.truncated)return V7(i,a);let s=`showing the last ${F7(o.outputBytes)} of ${F7(o.totalBytes)} (${o.totalLines} lines)`,c=`${n}/bash-output-${r()}.txt`;try{return await t.writeFile(c,Bge(i)),V7(`${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 L7.warn(`Failed to persist full bash output`,{error:e instanceof Error?e.message:String(e)}),V7(`${o.content}\n\n[Output truncated: ${s}. Re-run piping through \`head\`/\`tail\`/\`grep\`/\`sed -n\` to narrow the output.]`,a)}}const Hge=new Set([`grep`,`egrep`,`fgrep`,`rg`]);function H7(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 Uge(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=H7(r.name);if(i!==`command`)return i;let a=r.args[0];return a?H7(a):null}function Wge(e,t,n,r){if(n!==1||r.trim())return!1;let i;try{i=Uge(e.getBash().transform(t).ast)}catch{return!1}return i!==null&&Hge.has(i)}function U7(e){if(!(typeof e!=`number`||!Number.isFinite(e)||e<0))return e}function Gge(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 ${R7/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 ${z7/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 Kge(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 qge(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 Jge(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 K7(e,n,r);await e.fs.writeFile(t,i)}).catch(e=>L7.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 W7(e,t){t===`timeout`&&(e.killedByTimeout=!0),e.job?.kill(),e.controller.abort(),e.job?.exit(null)}function G7(e,t){e.job?.exit(e.job.signal.aborted?null:t)}function Yge(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 Xge(e,t,n,r={}){let i=0,a=0,o={shell:e,fs:t,tempDir:n,options:r,defaultBackgroundAfter:U7(r.defaultBackgroundAfterSeconds)??600,nextOutputSeq:()=>i+=1,nextJobId:()=>`bg-${a+=1}`};return{name:`bash`,description:Gge(o.defaultBackgroundAfter),inputSchema:Kge(o.defaultBackgroundAfter),execute:(e,t)=>n_e(o,e,t)}}async function K7(e,t,n){let r=e.options.scrubOutput;if(!r||!n)return n;try{return await r(n)}catch(e){return L7.warn(`Background bash output scrub failed; withholding output`,{jobId:t,error:e instanceof Error?e.message:String(e)}),`[output withheld: secret scrub unavailable]`}}function Zge(e){return e.ok?e.result.exitCode===124&&/execution aborted/i.test(e.result.stderr):/execution aborted/i.test(e.error)}function Qge(e,t){return e===void 0?`--- killed (exit ${t}) ---\n`:`--- killed after ${e}s (exit ${t}) ---\n`}async function $ge(e,t,n,r,i,a,o,s){await o.flushPersist();let c=o.killedByTimeout||Zge(a),l,u;if(c){let e=o.getTeedOutput();u=124,l=`${e.endsWith(`
|
|
4928
4928
|
`)||e.length===0?e:`${e}\n`}${Qge(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(`
|
|
4929
|
-
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await K7(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){L7.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){L7.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=I7(zge(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 e_e(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(()=>W7(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),G7(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),$ge(e,o,s,n,c,r,t,i))).catch(e=>L7.error(`Background bash delivery failed`,{jobId:o,error:e})),L7.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),Yge(o,s,r,c,i)}async function t_e(e,t,n){L7.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 Vge(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!Wge(e.shell,t,n.exitCode,n.stderr)}}async function n_e(e,t,n){let r=t.command,i=U7(t.timeout),a=U7(t.background_after)??e.defaultBackgroundAfter;L7.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=Jge(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?(W7(o,`timeout`),L7.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),qge(c)):t===`elapsed`?e_e(e,o,r,c,i,a):(G7(o,t.ok?t.result.exitCode:1),t.ok?await t_e(e,r,t.result):(L7.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const r_e={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 q7(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function i_e(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:q7(e)&&(t.edits=[e])}catch{}else q7(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 a_e(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:r_e,prepareArguments:i_e,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-
|
|
4929
|
+
`)?e:`${e}\n`}Shell error: ${a.error}`:`Shell error: ${a.error}`}let d=await K7(e,t,l),f;try{await e.fs.writeFile(i,d),f=i}catch(e){L7.warn(`Failed to persist background bash output`,{jobId:t,outputPath:i,error:e instanceof Error?e.message:String(e)})}if(!e.options.fireLick){L7.warn(`Background bash job finished with no lick sink`,{jobId:t,exitCode:u});return}let p=I7(zge(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 e_e(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(()=>W7(t,`timeout`),l*1e3);return t.settled.then(r=>(u!==void 0&&clearTimeout(u),G7(t,t.killedByTimeout?124:r.ok?r.result.exitCode:1),$ge(e,o,s,n,c,r,t,i))).catch(e=>L7.error(`Background bash delivery failed`,{jobId:o,error:e})),L7.info(`Bash command detached to background`,{command:n,jobId:o,pid:s,killAfter:l}),Yge(o,s,r,c,i)}async function t_e(e,t,n){L7.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 Vge(r,e.fs,e.tempDir,e.nextOutputSeq),isError:n.exitCode!==0&&!Wge(e.shell,t,n.exitCode,n.stderr)}}async function n_e(e,t,n){let r=t.command,i=U7(t.timeout),a=U7(t.background_after)??e.defaultBackgroundAfter;L7.debug(`Execute`,{command:r,timeoutSeconds:i,backgroundAfter:a});let o=Jge(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?(W7(o,`timeout`),L7.warn(`Bash command timed out`,{command:r,timeoutSeconds:c,pid:o.job?.pid}),qge(c)):t===`elapsed`?e_e(e,o,r,c,i,a):(G7(o,t.ok?t.result.exitCode:1),t.ok?await t_e(e,r,t.result):(L7.error(`Error`,{command:r,error:t.error}),{content:`Shell error: ${t.error}`,isError:!0}))}finally{l!==void 0&&clearTimeout(l),o.releaseTurnSignal()}}const r_e={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 q7(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.oldText==`string`&&typeof t.newText==`string`}function i_e(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:q7(e)&&(t.edits=[e])}catch{}else q7(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 a_e(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:r_e,prepareArguments:i_e,async execute(n,r){let{executePiEdit:i}=await import(`./pi-edit-execution-BzX4faZ8.js`);return i(e,t,n,r)}}}const J7=n(`tool:fs`);function o_e(e,t=`/workspace`){return[s_e(e),c_e(e),a_e(e,t)]}function s_e(e){return{name:`read_file`,description:`Read a file's contents. Output is capped at 2000 lines or ${N7/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;J7.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
4930
4930
|
`),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=Ige(c.join(`
|
|
4931
4931
|
`));if(u.firstLineExceedsLimit)return{content:`[Line ${s} is ${F7(new TextEncoder().encode(t[o]??``).length)}, exceeds ${F7(N7)} limit. Use bash: sed -n '${s}p' ${n} | head -c ${N7}]`};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} (${F7(N7)} 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 J7.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function c_e(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;J7.debug(`Write`,{path:n,contentLength:r.length});try{await e.writeFile(n,r);let t=await ts(e,n,r);return t?(J7.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 J7.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function l_e(){return null}const Y7=n(`tool:request-secret`);async function u_e(e,t){let n=l_e();if(n)return n(e);let r=t.callPanelRpc??await d_e();return r?r(e):{stored:!1,reason:`unavailable`}}async function d_e(){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 f_e(e){try{return e.getProvider?.()||void 0}catch(e){Y7.warn(`could not resolve this unit’s provider for the secret prompt`,{error:e instanceof Error?e.message:String(e)});return}}function p_e(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 m_e(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(`
|
|
4932
4932
|
`)}function h_e(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 g_e(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:p_e(t.domains),persist:t.persist===!0,requester:e.requester,provider:f_e(e)},a;try{a=await u_e(i,e)}catch(e){let t=e instanceof Error?e.message:String(e);return Y7.error(`secret request failed`,{name:n,error:t}),{content:`The secret prompt failed: ${t}`,isError:!0}}if(!a.stored)return{content:h_e(a),isError:!0};let o=__e(a.name,a.maskedValue,e);return Y7.info(`secret stored via request_secret`,{name:a.name,persisted:a.persisted}),{content:m_e(a,o)}}}}function __e(e,t,n){if(!n.setEnv||!t||!$w(e))return!1;try{return n.setEnv(e,t),!0}catch(t){return Y7.warn(`could not inject the masked value into the shell env`,{name:e,error:t instanceof Error?t.message:String(t)}),!1}}const X7=n(`scoop-management-tools`),Z7=`cross_cone`;function Q7(e){return mn(e.getScoops(),e.scoop.jid)}function v_e(e){let t=new Set;for(let n of Q7(e))n.jid!==e.scoop.jid&&n.parentJid!==null&&t.add(n.jid);return t}function y_e(e){let t=yn(e.getScoops());return t!==void 0&&t.jid===e.scoop.jid}function $7(e){let t=e.getScoops(),n=v_e(e),r=y_e(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=Mee(t,e);a.kind!==`cycle`&&i.push({scoop:e,relation:a.kind===`root`?`foreign`:`inherited`})}return i}function e9(e){return t=>t.folder===e||t.name===e}function t9(e,t){let n=$7(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 n9(e,t){let n=[],r=[];for(let i of e){let e=t9(i,t);e?n.push(e):r.push(i)}return{resolved:n,unknown:r}}function r9(e,t){return _n(e.getScoops(),t.scoop)?.folder??`unknown`}function b_e(e,t){return t.relation===`inherited`?`inherited (its owning cone is gone)`:`owned by cone "${r9(e,t)}"`}function i9(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 ${b_e(r,e)}`).join(`; `)}. Pass ${Z7}: true to act on it anyway.`,isError:!0}}function a9(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 o9=[`command`,`read`,`write`,`secret`];function x_e(e){return`${ve(e,{maxLen:50})}-scoop`}function S_e(e){return e===void 0?{ok:!0}:zn(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${Bn.join(`, `)}.`,isError:!0}}function C_e(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 w_e(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 s9(e,t){let n=$7(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 T_e(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 E_e(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),X7.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function D_e(e){let{kind:t,detail:n,suggested_pattern:r,reason:i}=e;if(!o9.includes(t))return{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${o9.join(`, `)}.`,isError:!0}};if(typeof n!=`string`||n.trim().length===0)return{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}};let a=typeof i==`string`?ZW(i):``;return{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{},...a?{reason:a}:{}}}}function O_e(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.note&&t.push(`Approver's reason: ${e.note}`),e.decision===`deny`&&t.push(e.note?`Not approved. Address the reason above before asking again; do not retry as-is and do not route around it.`:`Not approved, and no reason was given. Do not retry as-is; ask the cone what would make it acceptable, or move on.`),t.join(`
|
|
@@ -4934,7 +4934,7 @@ pass --wait to block and print the full result.`,Whe=new Set([`list`,`status`,`s
|
|
|
4934
4934
|
`)}`}}function N_e({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}:{},...P_e(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 P_e(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function F_e(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return X7.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 I_e(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=fn(s);if(!f.ok)return{content:f.error,isError:!0};let p=S_e(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=C_e(u);if(!m.ok)return{content:m.content,isError:!0};let h=w_e(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=x_e(n),_=Q7(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=Cn(g,t.getScoops().map(e=>e.folder));try{let e=N_e({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:Fn(Ln(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return X7.info(`Scoop created`,{name:n,folder:v}),i&&t.onFeedScoop?F_e(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 L_e(e,t){let{scoop_name:n,cross_cone:r}=e;if(e9(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=t9(n,t);if(!i)return s9([n],t);let a=i9([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),X7.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 c9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function R_e(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return c9();let{resolved:i,unknown:a}=n9(n,t);return i.length===0?s9(a,t):i9(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),X7.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 z_e(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 B_e(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return c9();let{resolved:i,unknown:a}=n9(n,t);if(i.length===0)return s9(a,t);let o=i9(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);X7.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(...z_e(l,c)),{content:u.join(`
|
|
4935
4935
|
`)}}function V_e(e,t){return!Array.isArray(e)||e.length===0?c9():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 H_e(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 U_e(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=V_e(n,r);if(a)return a;let{resolved:o,unknown:s}=n9(n,t);if(o.length===0)return s9(s,t);let c=i9(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 X7.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:H_e(f,s,p,r)}}function W_e(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /etc/sudoers.d/scoop-${e.scoopFolder??`<unknown>`}.`: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 G_e(e,t){let{lick_id:n,always:r,pattern:i,reason:a}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let o=typeof a==`string`?ZW(a):``,s={...r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`},...o?{note:o}:{}};try{let e=await t.onSudoResolve(n,s);return e.settled?(X7.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:W_e(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 K_e(e,t){let{lick_id:n,reason:r}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let i=typeof r==`string`?ZW(r):``;try{let e=await t.onSudoResolve(n,{decision:`deny`,...i?{note:i}:{}});return e.settled?(X7.info(`Lick dismissed`,{id:n,hasReason:!!i}),e.message?{content:e.message}:{content:i?`Denied, and the scoop was told why: "${i}"`:"Denied with NO reason, so the scoop cannot tell refusal from misunderstanding. Pass `reason` next time."}):{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 q_e(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})`:``,i=t.request.reason?`\n reason: ${t.request.reason}`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}${i}`}).join(`
|
|
4936
4936
|
`)}`}}async function J_e(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),X7.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 Y_e(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=>E_e(t,e)}}function X_e(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 the cone-owned /etc/sudoers.d/scoop-<folder> drop-in (you cannot write it yourself). 'deny' (or a timeout / dropped cone) resolves fail-closed. Always pass 'reason': the approver sees only what you ask for, never why.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...o9],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.`},reason:{type:`string`,description:`Why you need this, in one sentence. Name the goal it unblocks, not the action restated: "the build writes its output there", not "I need to write there". Truncated at 300 characters.`}},required:[`kind`,`detail`]},execute:t=>k_e(t,e)}}function Z_e(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.`},[Z7]:a9(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>A_e(t,e)}}function Q_e(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:()=>M_e(e)}}function $_e(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:[...Bn],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=>I_e(t,e)}}function eve(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.`},[Z7]:a9(`drop`)},required:[`scoop_name`]},execute:t=>L_e(t,e)}}function tve(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"]).`},[Z7]:a9(`mute`)},required:[`scoop_names`]},execute:t=>R_e(t,e)}}function nve(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"]).`},[Z7]:a9(`unmute`)},required:[`scoop_names`]},execute:t=>B_e(t,e)}}function rve(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."},[Z7]:a9(`wait on`)},required:[`scoop_names`]},execute:t=>U_e(t,e)}}function ive(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 /etc/sudoers.d/scoop-<folder> drop-in 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.`},reason:{type:`string`,description:`Optional note for the requester — a caveat on the approval. Only reaches a scoop that asked via sudo_request; an implicit filesystem gate has no channel to report it on success. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>G_e(t,e)}}function ave(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action — pass a reason, or the scoop just retries. 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).`},reason:{type:`string`,description:`Why you are refusing, in one sentence; the scoop sees it verbatim. Always give one for a sudo denial — without it the scoop cannot tell refusal from misunderstanding, and retries or works around it. Truncated at 300 characters.`}},required:[`lick_id`]},execute:t=>K_e(t,e)}}function ove(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:()=>q_e(e)}}function sve(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=>J_e(t,e)}}function cve(e){let t=[],n=gn(e.scoop);return pn(e.scoop)||(t.push(Y_e(e)),e.onSudoRequest&&t.push(X_e(e))),n.canCreateChildren&&e.onScoopScoop&&t.push($_e(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(Z_e(e)),t.push(Q_e(e)),e.onDropScoop&&t.push(eve(e)),e.onMuteScoops&&t.push(tve(e)),e.onUnmuteScoops&&t.push(nve(e)),e.onScheduleScoopWait&&t.push(rve(e)),e.onSudoResolve&&(t.push(ive(e)),t.push(ave(e))),e.onListSudoRequests&&t.push(ove(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(sve(e))),t}const lve=n(`scoop-context`);function uve(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 dve(e){let{scoop:t,unit:n,callbacks:r}=e,i=cve({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=[...o_e(e.gatedFs,n.workspace.root),Xge(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:Kt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){lve.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,g_e({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>Fge(qw(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:Kt()},s=uve(e);return e.processManager?Xt(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):Xt(a,void 0,o,s)}const l9=n(`scoop-context`);async function fve(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();l9.info(`Filesystem ready`,{folder:t.folder}),await _ie(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await Nge({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 dve({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 iie(r,n,()=>i.getGlobalMemory());if(!Kw(t))return l9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=oie(t,n),p=Jw(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await yie(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>Kw(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=wn(t);return{kind:`ready`,agent:hie({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:Yw(Xw()??v.level,f),getApiKey:()=>Kw(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 u9=n(`scoop-context`);var pve=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=Qt(e.messages);return this.createdAt=e.createdAt,u9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){u9.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 u9.warn(`Canonical conversation read failed; falling back to the legacy session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),null}let n=mi(t);if(n.length===0)return null;let r=Qt(n);return t&&(this.createdAt=t.createdAt),u9.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=>{u9.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=>{u9.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){u9.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 mve(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 hve(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function d9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const f9=n(`scoop-context`);var gve=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;f9.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)&&(f9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:Hw(r)}),!!(t<3&&(await Uw(p9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return Jre(e)?(f9.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 Qs(e)?(f9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),tc(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(!Hw(e)||t>=3)return!1;let r=p9(t);return f9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await Uw(r,n)&&!this.deps.isDisposed()}fail(e,t){Vw(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function p9(e){return 1e3*2**(e-1)}function _ve(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){f9.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 m9=n(`scoop-context`);var vve=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=Pn(e),this.owner={kind:xn(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 pve({store:r??null,canonical:c?{store:c,identity:{key:Zn(e),workUnitId:e.jid,workspaceId:Xn(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:On(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 mie({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new tie({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new nie({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new pie({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 gve({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 Age(this.unit,this.scoop,hn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Pee(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 fve({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`),m9.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);m9.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(cie(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),hve(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(_ve(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=mve(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(){d9(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 bi(this.scoop)?!0:this.unit.parentId===null&&f(`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:Cee,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&&!f(`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-Dv20JKP2.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-Dv20JKP2.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){m9.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 sie(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=uie(this.agent,this.scoop))}async reloadSkills(){this.agent&&await fie(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?Xw()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,die(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),d9(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||Zre(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||Yre(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 Q=n(`scoop-lifecycle-manager`);var yve=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 Gre(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))??hn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return _n(t.values(),e)??hn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){Q.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 Jn))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`)Q.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{Q.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=Pn(t).policy.filesystem;if(a.kind===`restricted`){let e=fn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new Jn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:Tn(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 vve(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=>{Q.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),Q.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);Q.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),Q.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 Q.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(Q.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){Q.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){Q.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`)),Q.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();if(jn(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=Cn(e.folder,n);r!==e.folder&&(Q.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),Q.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&kw(`spawn`,e.folder)}catch(n){Q.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){Q.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=>{Q.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(bn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?An(t):void 0)??Cw();n&&Sn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of Nee(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&hn(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=>{Q.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Zn(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{Q.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&&Q.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),Q.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){Q.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;Sn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Sn(n,r),this.getContext(e)?.updateModel(),Q.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();Q.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=>{Q.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),Q.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;Oee(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){Q.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}=Pn(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}),kw(`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 vn(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:Ln(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,pn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(pn(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(Q.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),kw(`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`),Pn(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){Q.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{Q.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const $=n(`scoop-message-router`);var bve=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($.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){$.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}`);kw(`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),$.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);$.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){$.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){$.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($.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){$.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{$.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);$.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);$.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,$.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){$.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){$.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){$.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($.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){$.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){$.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=er(pr(ir(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){$.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}: ${xee(e.content,e.attachments)}`).join(`
|
|
4937
|
-
`),l=s.flatMap(e=>See(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=er(pr(ir(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.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=>{$.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=>{$.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),$.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=>{$.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=>{$.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(),$.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 h9=n(`orchestrator`),xve={decision:`deny`};var Sve=class{scoops=new Map;workUnits=new ete(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Are({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Ure({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 Hre({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new zre({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 Fre({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=>cr(e),saveMessage:e=>tr(e)});lickRegistry=new Mre({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 bve({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=>tr(e),deleteMessage:e=>rr(e),clearMessagesForScoop:e=>dr(e),clearAllMessages:()=>lr(),getMessagesSince:(e,t,n)=>sr(e,t,n),setState:(e,t)=>ste(e,t)},isExternalLickChannel:_b});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new yve({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=>$n(e),deleteScoop:e=>ur(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 ww(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new TS({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 Hx(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Sw(e,t),await this.modelPolicyFile.init(),n(),mr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await gr(),this.sharedFs=await ww(e=>qn.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new cb,this.conversationStore=new pre,this.fsWatcher=new Zee,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=>kn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),jn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await or(`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 Pre({onTaskRun:async(e,t)=>{h9.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(),h9.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);h9.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}`)}Er(e=>this.getSessionCostsForCommand(e)),Dr(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-Cx-X3dby.js`).then(e=>e.t);return e()}),this.unregisterExportService=DS(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new db;try{await ure({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){h9.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=kn(e)?null:t??null;try{await $n(e)}catch(t){h9.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=>!bn(e));if(e.length===0)return;let t=Cw(),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?An(n):void 0)??t;if(r){Sn(e,r);try{await $n(e)}catch(t){h9.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=`${Fee.root}/`,r=Fn(Iee(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-DFoMRwaG.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:Ln,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(h9.warn(`Guest approval before SudoManager init — failing closed`),xve)}})}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 $n(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 hn(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 jee(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return _n(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await qn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await vw(this.sharedFs).catch(e=>{h9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new TS({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 Hx(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Sw(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),h9.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 cr(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(kr)]}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&&h9.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,h9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new db,t=this.sharedFs;return new Yne({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:rre(),snapshotStore:{read:e=>Qne(t,e),write:(e,n)=>Zne(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.158.0`})}};const g9=n(`workflow-run-manager`),_9=`/shared/workflow-runs`,v9=1e3;function Cve(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function wve(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){g9.warn(`observeRun handler threw`,e)}},i=(e,n)=>kve(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=Cve(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),Dve(t,n);let f=i(a.ctx,c),p=Ove(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=>g9.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=`${_9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(_9,{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);g9.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`?Eve(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){g9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function Tve(e){let t=wve(e);return globalThis[f7]=t,g9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Eve(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Dve(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 Ove(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 kve(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Ave(n,t,a?.args??[],r):e===`agent`?jve(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Ave(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>v9&&i.logs.splice(0,i.logs.length-v9),r()}return{stdout:``,stderr:``,exitCode:0}}async function jve(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 Mve=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function Nve(e,t,n){let r=Pve(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=Fve(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Pve(e){let t=new Map;return y9(t,e.discoveryOrigin),y9(t,e.discoveryUrl),[...t.values()]}function y9(e,t){if(t){b9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);b9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!Mve.has(e)))b9(e,t,1,`substring`)}catch{}}}function b9(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 Fve(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Lve(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)Ive(a,e)&&(r+=e.weight*o)}return r}function Ive(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 Lve(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Rve=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=C9(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:S9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===S9)throw new M(`ENOTDIR`,`not a directory`,e);let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);return x9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new M(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=C9(e);if(t.length===1&&t[0]===S9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new M(`EISDIR`,`is a directory`,e);let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!x9.includes(r))throw new M(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new M(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=C9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===S9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!x9.includes(r))throw new M(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new M(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new M(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new M(`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 M(`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:T9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:E9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
4937
|
+
`),l=s.flatMap(e=>See(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=er(pr(ir(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);$.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=>{$.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=>{$.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),$.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=>{$.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=>{$.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(),$.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 h9=n(`orchestrator`),xve={decision:`deny`};var Sve=class{scoops=new Map;workUnits=new ete(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Are({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Ure({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 Hre({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new zre({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 Fre({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=>cr(e),saveMessage:e=>tr(e)});lickRegistry=new Mre({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 bve({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=>tr(e),deleteMessage:e=>rr(e),clearMessagesForScoop:e=>dr(e),clearAllMessages:()=>lr(),getMessagesSince:(e,t,n)=>sr(e,t,n),setState:(e,t)=>ste(e,t)},isExternalLickChannel:_b});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new yve({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=>$n(e),deleteScoop:e=>ur(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 ww(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new TS({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 Hx(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Sw(e,t),await this.modelPolicyFile.init(),n(),mr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await gr(),this.sharedFs=await ww(e=>qn.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new cb,this.conversationStore=new pre,this.fsWatcher=new Zee,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=>kn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),jn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await or(`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 Pre({onTaskRun:async(e,t)=>{h9.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(),h9.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);h9.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}`)}Er(e=>this.getSessionCostsForCommand(e)),Dr(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source--zsr_0LN.js`).then(e=>e.t);return e()}),this.unregisterExportService=DS(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new db;try{await ure({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){h9.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=kn(e)?null:t??null;try{await $n(e)}catch(t){h9.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=>!bn(e));if(e.length===0)return;let t=Cw(),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?An(n):void 0)??t;if(r){Sn(e,r);try{await $n(e)}catch(t){h9.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=`${Fee.root}/`,r=Fn(Iee(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-DVTvTDeB.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:Ln,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(h9.warn(`Guest approval before SudoManager init — failing closed`),xve)}})}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 $n(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 hn(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 jee(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return _n(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await qn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await vw(this.sharedFs).catch(e=>{h9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new TS({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 Hx(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Sw(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),h9.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 cr(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(kr)]}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&&h9.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,h9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new db,t=this.sharedFs;return new Yne({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:rre(),snapshotStore:{read:e=>Qne(t,e),write:(e,n)=>Zne(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.158.1`})}};const g9=n(`workflow-run-manager`),_9=`/shared/workflow-runs`,v9=1e3;function Cve(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function wve(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){g9.warn(`observeRun handler threw`,e)}},i=(e,n)=>kve(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=Cve(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),Dve(t,n);let f=i(a.ctx,c),p=Ove(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=>g9.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=`${_9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(_9,{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);g9.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`?Eve(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){g9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function Tve(e){let t=wve(e);return globalThis[f7]=t,g9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Eve(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Dve(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 Ove(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 kve(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Ave(n,t,a?.args??[],r):e===`agent`?jve(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Ave(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>v9&&i.logs.splice(0,i.logs.length-v9),r()}return{stdout:``,stderr:``,exitCode:0}}async function jve(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 Mve=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function Nve(e,t,n){let r=Pve(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=Fve(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Pve(e){let t=new Map;return y9(t,e.discoveryOrigin),y9(t,e.discoveryUrl),[...t.values()]}function y9(e,t){if(t){b9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);b9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!Mve.has(e)))b9(e,t,1,`substring`)}catch{}}}function b9(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 Fve(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Lve(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)Ive(a,e)&&(r+=e.weight*o)}return r}function Ive(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 Lve(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Rve=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=C9(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:S9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===S9)throw new M(`ENOTDIR`,`not a directory`,e);let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);return x9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new M(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=C9(e);if(t.length===1&&t[0]===S9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new M(`EISDIR`,`is a directory`,e);let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!x9.includes(r))throw new M(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new M(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=C9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===S9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=w9(t[0]);if(n===null||!this.pidExists(n))throw new M(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!x9.includes(r))throw new M(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new M(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new M(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new M(`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 M(`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:T9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:E9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
4938
4938
|
`}renderProcFile(e,t){if(e===1)return Uve(t);let n=this.pm.get(e);switch(t){case`status`:return zve(n);case`cmdline`:return Bve(n);case`cwd`:return Vve(n);case`stat`:return Hve(n)}}};const x9=[`status`,`cmdline`,`cwd`,`stat`],S9=`table`;function C9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function w9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function zve(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${T9(e.status)} (${e.status})`,`Owner:\t${E9(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(`
|
|
4939
4939
|
`)+`
|
|
4940
4940
|
`}function Bve(e){return e.argv.join(`\0`)+`\0`}function Vve(e){return e.cwd+`
|
|
@@ -4943,7 +4943,7 @@ pass --wait to block and print the full result.`,Whe=new Set([`list`,`status`,`s
|
|
|
4943
4943
|
`)+`
|
|
4944
4944
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
4945
4945
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
4946
|
-
`}}function Wve(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(Ez(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(!xz(n.token))return;let a=i.get(n.id);if(a){r({type:Dz,id:n.id}),a.result&&r({type:Oz,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:Dz,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:Oz,id:n.id,...e})};(Mz(n)?Fz(n):Tz(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 D9(){return globalThis}function Gve(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 Kve(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 qve(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Jve(e,t)}async function Jve(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=hn(r),a=e.type===`discovery`&&!e.targetScoop?Nve(e,i.filter(zx),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?vl(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!zx(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-
|
|
4947
|
-
`,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 eye(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-CDToX4F0.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CsCDQ3wI.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 tye(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 Ax(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})},{...nye(t),isOwnTab:Ox(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function nye(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:()=>jx()}}function rye(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-CB_vvrUl.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-rytW5wPV.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 iye(){vr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-BEqd3zwB.js`);return e()})}function aye(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BEqd3zwB.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 oye(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 sye(e){return e===`node-rest`}function cye(e,t,n,r){import(`./gelatiere-unit-DnbLwJqw.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!f(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-DA2wk9nw.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function lye(e,t){if(!e)return()=>{};import(`./memory-curation-seam-BjsquXL_.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return f(`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 uye(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}un(e,t,e.getSessionStore())}async function dye(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);iye();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Yve(t,n,r,i,e);if(s(`orchestrator-ready`),uye(l,f,o),f)try{await f.mountInternal(`/proc`,new Rve(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Xve(l,e,o);s(`lick-manager-ready`),f&&Qve({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),D9().__slicc_lickManager=m,cye(l,m,f,o);let h=lye(f,o),{wsBridge:g,wsRegistry:_}=await $ve({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});D9().__slicc_wsSubscribers=_;let v=sye(p.adapter)?await eye(m,o,e.localLickWsUrl??null,f):null,y=tye(n,m,o,e.appPageUrl);f&&rye(f,m,o),a||await Zve(l),s(`cone-bootstrapped`),f&&aye(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await oye(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Wve({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 fye({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 fye(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)}pye({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function pye(e){let t=D9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,iW(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 O9=`x-bypass-llm-proxy`;function mye(e,t,n){return t?(r,i)=>{if(!hye(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(O9)||a.set(O9,`1`),e(r,{...i,headers:a})}:e}function hye(e,t,n){if(_ye(e,t))return!0;let r=n?.()??null;return r?gye(e,r,t):!1}function gye(e,t,n){let r=k9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function _ye(e,t){let n=k9(e);try{return new URL(n,t).origin===t}catch{return!0}}function k9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function vye(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 yye=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(!bye(e)||e.source!==`panel`)return;let t=e.payload;xye(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=eo(v(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?A9(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,A9(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 bye(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function A9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function xye(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 Sye=class extends j7{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 Cye(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new yye({transport:t,processManager:i,createShell:(a,o)=>new Sye(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Qn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function wye(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function Tye(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 Eye(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function Dye(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function j9(e){return wye(e)||Tye(e)||Eye(e)||Dye(e)}function M9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return Oye(e);if(typeof e==`object`)return kye(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function N9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return I9(e)??L9(e);let t=M9(e);if(t!==void 0)return P9(t)}function P9(e){let t=e.trim();if(!t)return e;let n=F9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=F9(t.slice(r,i+1));if(e)return e}return e}function Oye(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function kye(e){let t=I9(e),n=L9(e);return n&&t?`${n}: ${t}`:t??n}function F9(e){if(e.startsWith(`{`))try{return I9(JSON.parse(e))}catch{return}}function I9(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 L9(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 R9=null,z9=!1;function Aye(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function jye(e){return Aye()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Mye(e={}){if(!z9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Sge(Nye),Lre(Pye),Kre(B9);try{let t=jye(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(R9=(await import(`./rum-worker-CwmNSpjO.js`)).default,H9(self)):t===`extension`?(R9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&H9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),Rye(),Iye(),R9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),z9=!0,R9&&R9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Nye(e){R9?.(`fill`,{source:e})}function B9(e,t){let n=V9(t);n!==null&&R9?.(`error`,{source:e,target:n})}function Pye(e,t,n){if(e===`error`){let e=V9(n);if(e===null)return;R9?.(`error`,{source:`scoop:${t}`,target:e});return}R9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function Fye(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function V9(e){let t=M9(e);if(t===void 0)return e==null?void 0:null;if(j9(t))return null;let n=N9(e)??P9(t);return j9(n)?null:W9(n)}function H9(e){e.addEventListener(`error`,e=>{let t=e;B9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{B9(`js`,e.reason)})}function U9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function Iye(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;U9(t)&&(B9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;U9(t)&&(B9(`js`,t),e.stopImmediatePropagation())},!0))}function W9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
4946
|
+
`}}function Wve(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(Ez(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(!xz(n.token))return;let a=i.get(n.id);if(a){r({type:Dz,id:n.id}),a.result&&r({type:Oz,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:Dz,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:Oz,id:n.id,...e})};(Mz(n)?Fz(n):Tz(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 D9(){return globalThis}function Gve(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 Kve(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 qve(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Jve(e,t)}async function Jve(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=hn(r),a=e.type===`discovery`&&!e.targetScoop?Nve(e,i.filter(zx),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?vl(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!zx(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-DBBqtrXa.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=jb(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=Gve(e),l=Kve(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 Yve(e,t,n,r,i){let a=new va,o=new Sve(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=Zt(),c=i.capabilityBroker??Xx(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),Gee(c),D9().__slicc_pm=a,iW(oW()),D9().__slicc_browser=t,await n.bind(o,t);let l=ite(()=>n.emitTrayRuntimeStatus()),u=Jb(()=>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 Xve(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-DlIH8zCh.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source--zsr_0LN.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??qve,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Zve(e){let t=e.getScoops();hn(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 Qve(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Tve({sharedFs:i,getStartingRoot:e=>{let n=hn(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)=>cW(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p7().slice(10,22),splitResult:(e,t)=>m7(e,t)})}async function $ve(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))+`
|
|
4947
|
+
`,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 eye(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-CDToX4F0.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-CsCDQ3wI.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 tye(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 Ax(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})},{...nye(t),isOwnTab:Ox(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function nye(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:()=>jx()}}function rye(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-B41gr65n.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-rytW5wPV.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 iye(){vr(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-egIJU9Tj.js`);return e()})}function aye(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-egIJU9Tj.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 oye(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 sye(e){return e===`node-rest`}function cye(e,t,n,r){import(`./gelatiere-unit-DnbLwJqw.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!f(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-DA2wk9nw.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function lye(e,t){if(!e)return()=>{};import(`./memory-curation-seam-BysRStGd.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return f(`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 uye(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}un(e,t,e.getSessionStore())}async function dye(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);iye();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Yve(t,n,r,i,e);if(s(`orchestrator-ready`),uye(l,f,o),f)try{await f.mountInternal(`/proc`,new Rve(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Xve(l,e,o);s(`lick-manager-ready`),f&&Qve({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),D9().__slicc_lickManager=m,cye(l,m,f,o);let h=lye(f,o),{wsBridge:g,wsRegistry:_}=await $ve({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});D9().__slicc_wsSubscribers=_;let v=sye(p.adapter)?await eye(m,o,e.localLickWsUrl??null,f):null,y=tye(n,m,o,e.appPageUrl);f&&rye(f,m,o),a||await Zve(l),s(`cone-bootstrapped`),f&&aye(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await oye(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Wve({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 fye({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 fye(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)}pye({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function pye(e){let t=D9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,iW(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 O9=`x-bypass-llm-proxy`;function mye(e,t,n){return t?(r,i)=>{if(!hye(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(O9)||a.set(O9,`1`),e(r,{...i,headers:a})}:e}function hye(e,t,n){if(_ye(e,t))return!0;let r=n?.()??null;return r?gye(e,r,t):!1}function gye(e,t,n){let r=k9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function _ye(e,t){let n=k9(e);try{return new URL(n,t).origin===t}catch{return!0}}function k9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function vye(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 yye=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(!bye(e)||e.source!==`panel`)return;let t=e.payload;xye(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=eo(v(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?A9(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,A9(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 bye(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function A9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function xye(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 Sye=class extends j7{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 Cye(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new yye({transport:t,processManager:i,createShell:(a,o)=>new Sye(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Qn},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function wye(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function Tye(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 Eye(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function Dye(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function j9(e){return wye(e)||Tye(e)||Eye(e)||Dye(e)}function M9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return Oye(e);if(typeof e==`object`)return kye(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function N9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return I9(e)??L9(e);let t=M9(e);if(t!==void 0)return P9(t)}function P9(e){let t=e.trim();if(!t)return e;let n=F9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=F9(t.slice(r,i+1));if(e)return e}return e}function Oye(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function kye(e){let t=I9(e),n=L9(e);return n&&t?`${n}: ${t}`:t??n}function F9(e){if(e.startsWith(`{`))try{return I9(JSON.parse(e))}catch{return}}function I9(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 L9(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 R9=null,z9=!1;function Aye(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function jye(e){return Aye()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function Mye(e={}){if(!z9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){Sge(Nye),Lre(Pye),Kre(B9);try{let t=jye(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(R9=(await import(`./rum-worker-CwmNSpjO.js`)).default,H9(self)):t===`extension`?(R9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&H9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),Rye(),Iye(),R9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),z9=!0,R9&&R9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function Nye(e){R9?.(`fill`,{source:e})}function B9(e,t){let n=V9(t);n!==null&&R9?.(`error`,{source:e,target:n})}function Pye(e,t,n){if(e===`error`){let e=V9(n);if(e===null)return;R9?.(`error`,{source:`scoop:${t}`,target:e});return}R9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function Fye(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function V9(e){let t=M9(e);if(t===void 0)return e==null?void 0:null;if(j9(t))return null;let n=N9(e)??P9(t);return j9(n)?null:W9(n)}function H9(e){e.addEventListener(`error`,e=>{let t=e;B9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{B9(`js`,e.reason)})}function U9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function Iye(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;U9(t)&&(B9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;U9(t)&&(B9(`js`,t),e.stopImmediatePropagation())},!0))}function W9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
4948
4948
|
`).filter(e=>!Fye(e)).join(`
|
|
4949
|
-
`).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 G9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function K9(e){let t=typeof e==`string`?e:N9(e)??M9(e);if(typeof t!=`string`)return{kind:`absent`};let n=P9(t);if(n===`[object Object]`)return{kind:`noise`};let r=W9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function Lye(e){let t=K9(e.source),n=K9(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 Rye(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[G9])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=Lye(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[G9]=!0,navigator.sendBeacon=n}function zye(e){let t=new Bye(e);return t.start(),{stop:()=>t.dispose()}}var Bye=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(!Vye(e)||e.source!==`panel`)return;let t=e.payload;if(q9(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Hye(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(Uye(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 M(`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 M(`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 M(`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(Wye(e.type),e.requestId,new M(`EACCES`,`vfs-rpc-host has no writable backend wired`),Gye(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 M(`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 M(`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 M(`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 Vye(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(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 Hye(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 Uye(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Wye(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 Gye(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof M?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Kye(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=mye(e.bind(globalThis),t,qye)}function qye(){let e=ree();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Jye(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 Yye=vye(e=>Qye(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Yye.handle(e.data)});function Xye(e){let t=rc(e.pageBuildId,`6.158.0-mu3h4kjn`);return()=>{t&&B9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.158.0-mu3h4kjn`)}}function Zye(e){Kye(),oee(e.localApiBaseUrl??null),aee(e.bridgeToken??null),QU(e.syncFsBridgeEnabled??!1),rs(e.pageLoadedAt??null),iee(e.extensionDelegateId??null),Jye(e.localStorageSeed??{}),e.flagFloat&&Ws(e.flagFloat)}async function Qye(e){ec(e.instanceId);let t=Xye(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Zye(e),Mye().then(t).catch(()=>{}),await h(),n(`providers-registered`);let r=gl(e.kernelPort),i=new px(r),a=px.createCallbacks(i),o=new _l(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Rs(o);Y9=await dye({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`),u=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of as)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)u.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(l));let p=await ebe({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){$ye(e.kernelPort,t)}}function $ye(e,t){nc(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 ebe(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=Cye({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=zye({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await tbe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function tbe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CxIM0vni.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())});
|
|
4949
|
+
`).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 G9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function K9(e){let t=typeof e==`string`?e:N9(e)??M9(e);if(typeof t!=`string`)return{kind:`absent`};let n=P9(t);if(n===`[object Object]`)return{kind:`noise`};let r=W9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function Lye(e){let t=K9(e.source),n=K9(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 Rye(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[G9])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=Lye(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[G9]=!0,navigator.sendBeacon=n}function zye(e){let t=new Bye(e);return t.start(),{stop:()=>t.dispose()}}var Bye=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(!Vye(e)||e.source!==`panel`)return;let t=e.payload;if(q9(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Hye(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(Uye(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 M(`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 M(`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 M(`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(Wye(e.type),e.requestId,new M(`EACCES`,`vfs-rpc-host has no writable backend wired`),Gye(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 M(`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 M(`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 M(`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 Vye(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(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 Hye(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 Uye(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function Wye(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 Gye(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof M?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Kye(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=mye(e.bind(globalThis),t,qye)}function qye(){let e=ree();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Jye(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 Yye=vye(e=>Qye(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Yye.handle(e.data)});function Xye(e){let t=rc(e.pageBuildId,`6.158.1-mu40eb39`);return()=>{t&&B9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.158.1-mu40eb39`)}}function Zye(e){Kye(),oee(e.localApiBaseUrl??null),aee(e.bridgeToken??null),QU(e.syncFsBridgeEnabled??!1),rs(e.pageLoadedAt??null),iee(e.extensionDelegateId??null),Jye(e.localStorageSeed??{}),e.flagFloat&&Ws(e.flagFloat)}async function Qye(e){ec(e.instanceId);let t=Xye(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Zye(e),Mye().then(t).catch(()=>{}),await h(),n(`providers-registered`);let r=gl(e.kernelPort),i=new px(r),a=px.createCallbacks(i),o=new _l(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Rs(o);Y9=await dye({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`),u=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of as)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)u.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(l));let p=await ebe({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){$ye(e.kernelPort,t)}}function $ye(e,t){nc(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 ebe(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=Cye({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=zye({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await tbe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function tbe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DBH5XTaz.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())});
|