sliccy 6.153.0 → 6.154.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ui/.vite/manifest.json +168 -168
- package/dist/ui/assets/{SKILL-zHRhO4F3.js → SKILL-B0M2f1rt.js} +1 -1
- package/dist/ui/assets/{account-store-DT3VDbvp.js → account-store-B3TDSGgR.js} +1 -1
- package/dist/ui/assets/{account-store-Br-5Tahn.js → account-store-Cbuyot6T.js} +1 -1
- package/dist/ui/assets/{adobe-D-SRO3WV.js → adobe-C1OxVKsW.js} +1 -1
- package/dist/ui/assets/{adobe-s7kqWKTP.js → adobe-D0bVmcsi.js} +1 -1
- package/dist/ui/assets/{agent-bridge-DPAiiTJu.js → agent-bridge-C2T3pN-e.js} +1 -1
- package/dist/ui/assets/{agent-panels-C-vXgmUa.js → agent-panels-BF2KNcL6.js} +1 -1
- package/dist/ui/assets/{apply-layout-aXZfO5zJ.js → apply-layout-Bhjj4nPN.js} +1 -1
- package/dist/ui/assets/{apps-CfzNbgxN.js → apps-C8k6TOsm.js} +1 -1
- package/dist/ui/assets/{azure-openai-Bv0RSahJ.js → azure-openai-BUJ38VHr.js} +1 -1
- package/dist/ui/assets/{azure-openai-CENnbCPD.js → azure-openai-DrtklPbQ.js} +1 -1
- package/dist/ui/assets/{budget-usage-source-CI1VrdHF.js → budget-usage-source-DVW8NROx.js} +1 -1
- package/dist/ui/assets/{cdp-BpGYDjo4.js → cdp-Clmi3S3f.js} +1 -1
- package/dist/ui/assets/{cerebras-DW9t3pME.js → cerebras-B4AeTqby.js} +1 -1
- package/dist/ui/assets/{cerebras-D1qiSEMk.js → cerebras-Dh3T6Yuw.js} +1 -1
- package/dist/ui/assets/{composer-speech-D3-kZTJe.js → composer-speech-Dqgg2NPa.js} +1 -1
- package/dist/ui/assets/{connect-surface-CNxDpOvY.js → connect-surface-BOV2o_6c.js} +1 -1
- package/dist/ui/assets/{directed-approval-ByZDWCge.js → directed-approval-Pzx9_4nE.js} +1 -1
- package/dist/ui/assets/{fs-D_5Hf9-X.js → fs-BjSQWu2g.js} +1 -1
- package/dist/ui/assets/{fs-DqBbpVZo.js → fs-Ci2s9_2x.js} +2 -2
- package/dist/ui/assets/{github-DxToYpZG.js → github-Bh3bUxPz.js} +2 -2
- package/dist/ui/assets/{github-Dbs3fu5D.js → github-DiRnoDll.js} +1 -1
- package/dist/ui/assets/{github-copilot-BtVP3b6q.js → github-copilot-BD0-tQ4L.js} +1 -1
- package/dist/ui/assets/{github-copilot-DDIYDOoo.js → github-copilot-Ny3_Bzue.js} +1 -1
- package/dist/ui/assets/{github-install-CfilaKPL.js → github-install-CB0ldULv.js} +1 -1
- package/dist/ui/assets/{github-zip-CowqpWqM.js → github-zip-DwdgFfY8.js} +1 -1
- package/dist/ui/assets/{hear-Bmw4jv4C.js → hear-BJOAYoZe.js} +1 -1
- package/dist/ui/assets/{help-dis3gVin.js → help-ChVsqTeK.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-BMbF2DPc.js → js-realm-worker-CYo2Tual.js} +1 -1
- package/dist/ui/assets/{kernel-worker-JD5PLtQg.js → kernel-worker-BEtE6IOd.js} +35 -35
- package/dist/ui/assets/{local-llm-3efEmI2R.js → local-llm-BxL33fhK.js} +1 -1
- package/dist/ui/assets/{local-llm-8mNKYUyN.js → local-llm-DorNBm9B.js} +1 -1
- package/dist/ui/assets/{main-DNSx5t9M.js → main-B07t7nYY.js} +3 -3
- package/dist/ui/assets/{main-cherry-BUC0V42i.js → main-cherry-uc6uMkYk.js} +1 -1
- package/dist/ui/assets/{memory-curation-seam-B1zdL89W.js → memory-curation-seam-bWfYQeB0.js} +1 -1
- package/dist/ui/assets/{mount-DQE9qVGW.js → mount-B-Dls9WR.js} +3 -3
- package/dist/ui/assets/{mount-BU0YiStI.js → mount-C_z-hY6d.js} +1 -1
- package/dist/ui/assets/{mount-recovery-szxkUpiN.js → mount-recovery-Wt3z_gJ-.js} +1 -1
- package/dist/ui/assets/{new-session-CVLZettz.js → new-session-BpKQuazZ.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-D4K4RG4i.js → oauth-bootstrap-3rfPAY2v.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-c2j_jTmA.js → onboarding-orchestrator-DaiC0k5A.js} +1 -1
- package/dist/ui/assets/{openai-codex-CK-EVEzJ.js → openai-codex-BvfRwpBB.js} +1 -1
- package/dist/ui/assets/{openai-codex-BB6AGAk4.js → openai-codex-DMTlCy3V.js} +1 -1
- package/dist/ui/assets/{openrouter-D7x3pGdS.js → openrouter-B7CGsX81.js} +1 -1
- package/dist/ui/assets/{openrouter-free-DJ5lPq7S.js → openrouter-free-BVdfCtlF.js} +1 -1
- package/dist/ui/assets/{openrouter-free-CENDt7Ou.js → openrouter-free-DGAFTlu5.js} +1 -1
- package/dist/ui/assets/{openrouter-DIe9K8K3.js → openrouter-mJmUIEt9.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-D32eGAS-.js → openrouter-oauth-BlKX0bbF.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-cIflZeMd.js → openrouter-oauth-D0pKLLyl.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-ChtHTqiQ.js → panel-rpc-handlers-CbqSf72n.js} +2 -2
- package/dist/ui/assets/{panelize-shell-B89wjO8U.js → panelize-shell-D6XcVxaT.js} +1 -1
- package/dist/ui/assets/{provider-C0eIfUUt.js → provider-BZm95oFT.js} +1 -1
- package/dist/ui/assets/{provider-CSA17s1P.js → provider-C1hg69QS.js} +2 -2
- package/dist/ui/assets/provider-settings-NAiB7xVN.js +1 -0
- package/dist/ui/assets/provider-store-access-BQN0Yp9w.js +1 -0
- package/dist/ui/assets/provider-store-access-D_Bfdzd6.js +1 -0
- package/dist/ui/assets/{providers-DdkG0NSO.js → providers-CKUtckcc.js} +1 -1
- package/dist/ui/assets/{providers-CIJO5pfi.js → providers-DGX5ohJc.js} +2 -2
- package/dist/ui/assets/{quick-llm-DzOHzN-I.js → quick-llm-DjQH1IOR.js} +1 -1
- package/dist/ui/assets/{recovery-screen-7YwqCNIg.js → recovery-screen-D3_zoZq2.js} +1 -1
- package/dist/ui/assets/{run-DbnU3wyl.js → run-BGcMWlan.js} +1 -1
- package/dist/ui/assets/{run-CD28vEFB.js → run-BiC8nBGs.js} +1 -1
- package/dist/ui/assets/{run-rqExAVOb.js → run-BoLpdccP.js} +2 -2
- package/dist/ui/assets/{session-jsonl-4dg00tv6.js → session-jsonl-1dH4qbYh.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-DFRtQB19.js → setup-feature-flags-remote-CtLYq8_W.js} +1 -1
- package/dist/ui/assets/sidecar-repair-CUe96gCg.js +1 -0
- package/dist/ui/assets/{silent-renew-backoff-DEAQc8gF.js → silent-renew-backoff-BlXWqqSS.js} +1 -1
- package/dist/ui/assets/{skills-CyAtIBDH.js → skills-MQBhN1sp.js} +1 -1
- package/dist/ui/assets/slicc-version-CveLv8QB.js +1 -0
- package/dist/ui/assets/{snapshot-rQItub8y.js → snapshot-D912sxnM.js} +1 -1
- package/dist/ui/assets/{snapshot-features-CXvFb5kP.js → snapshot-features-DQZYYxXB.js} +1 -1
- package/dist/ui/assets/{soundscape-BfgaSN-Y.js → soundscape-CO_HIUUp.js} +1 -1
- package/dist/ui/assets/{speak-zFtFhgmL.js → speak-Ck274s4Y.js} +1 -1
- package/dist/ui/assets/sprinkle-bridge-channel-Bur-XBNy.js +1 -0
- package/dist/ui/assets/{sprinkle-bridge-channel-Clwu-X1e.js → sprinkle-bridge-channel-DTP5IbJB.js} +1 -1
- package/dist/ui/assets/sprinkle-manager-C3LieoqN.js +1 -0
- package/dist/ui/assets/sprinkle-op-handler-DyRlIvAg.js +1 -0
- package/dist/ui/assets/{sprinkle-renderer-DDP-UxN2.js → sprinkle-renderer-BoyNomH_.js} +17 -17
- package/dist/ui/assets/{state-DVDUDADZ.js → state-BjKxySu5.js} +1 -1
- package/dist/ui/assets/{store-DWLwX9LI.js → store-BXnbNdZV.js} +1 -1
- package/dist/ui/assets/{store-3A-5dTwk.js → store-CCdCzj9v.js} +1 -1
- package/dist/ui/assets/{sudo-Vmn2lmIe.js → sudo-DS92DHjZ.js} +1 -1
- package/dist/ui/assets/{sync-dialog-CS1RAgot.js → sync-dialog-3CGM9fe3.js} +1 -1
- package/dist/ui/assets/{transformers-env-DAziCt21.js → transformers-env-CpAmyrH1.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-Tsj_KlbJ.js → tray-sidecar-BH7UW8Mw.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-BXADtDDx.js → upgrade-detection-dJipOZ6Y.js} +1 -1
- package/dist/ui/assets/{voice-reply-BGwjuDSD.js → voice-reply-BQBf7iL6.js} +1 -1
- package/dist/ui/assets/{wc-attach-lctJI9Cb.js → wc-attach-DR6gOK5A.js} +2 -2
- package/dist/ui/assets/{wc-extension-CJ8-0uuM.js → wc-extension-BgWh03_G.js} +2 -2
- package/dist/ui/assets/{wc-follower-BABTMpUh.js → wc-follower-CCvvo0Xw.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-Dxh3czLI.js → wc-follower-oauth-CltSVU2I.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-BXF8unbT.js → wc-gelatiere-B9FmNfC2.js} +1 -1
- package/dist/ui/assets/{wc-live-CY77nXRu.js → wc-live-C-zLgJHl.js} +5 -5
- package/dist/ui/assets/{wc-nav-D4j-dAFm.js → wc-nav-BKLkTYHx.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Daxory4F.js → wc-onboarding-CFTANPjD.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-R85lT45F.js → wc-placeholder-DkoxYmZF.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-Cq3B_6l5.js → wc-secret-request-C1F8vgx_.js} +1 -1
- package/dist/ui/assets/{wc-settings-D6g62psJ.js → wc-settings-BD0xKwbB.js} +3 -3
- package/dist/ui/assets/{wc-shell-CVnS13Pt.js → wc-shell-PJT-RMat.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-Dq7vpLhS.js → wc-shortcut-config-CDKMKCNS.js} +1 -1
- package/dist/ui/assets/{wc-shortcuts-CQHGJh5j.js → wc-shortcuts-B3zqERjU.js} +1 -1
- package/dist/ui/assets/wc-sprinkles-Cr-ptPKK.js +2 -0
- package/dist/ui/assets/{wc-transcript-export-CqrBcsOg.js → wc-transcript-export-BUtKuj-Y.js} +2 -2
- package/dist/ui/assets/{wc-tray-CBlFR1Md.js → wc-tray-B7y37GAV.js} +4 -4
- package/dist/ui/assets/welcome-detection-CrQU2iTI.js +1 -0
- package/dist/ui/assets/{whisper-session-DzS7Olt2.js → whisper-session-CM5iXItI.js} +2 -2
- package/dist/ui/assets/{xai-grok-B_eBvQy4.js → xai-grok-CGUxsbly.js} +1 -1
- package/dist/ui/assets/{xai-grok-D3bEO2ts.js → xai-grok-dfRTs5-h.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-CK9AxQ6e.js +0 -1
- package/dist/ui/assets/provider-store-access-D0e3HMUh.js +0 -1
- package/dist/ui/assets/provider-store-access-D6D8_V2Z.js +0 -1
- package/dist/ui/assets/sidecar-repair-G397kiLT.js +0 -1
- package/dist/ui/assets/slicc-version-BTzaBTax.js +0 -1
- package/dist/ui/assets/sprinkle-bridge-channel-CftxYQ9D.js +0 -1
- package/dist/ui/assets/sprinkle-manager-CiAkASWE.js +0 -1
- package/dist/ui/assets/sprinkle-op-handler-Cb1pl8Ok.js +0 -1
- package/dist/ui/assets/wc-sprinkles-CnPEFIgm.js +0 -2
- package/dist/ui/assets/welcome-detection-Dv6cuKXV.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"./snapshot-rQItub8y.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{n as p,r as m,t as h}from"./feature-flags-BIRXJe0o.js";import{a as g,t as _}from"./providers-DdkG0NSO.js";import{r as v,t as y}from"./base64-DzRgusa4.js";import{n as b}from"./bridge-protocol-DdqxTTSu.js";import{t as x}from"./content-type-_QKWY0B2.js";import{a as S,c as C,i as w,l as T,o as E,r as D,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as O,d as ie,f as ae,g as oe,h as se,i as ce,m as le,p as ue,u as de,v as fe,x as pe,y as k}from"./account-store-DT3VDbvp.js";import{a as me,l as he,n as ge,o as _e}from"./proxied-fetch-B57RqgUb.js";import{t as ve}from"./runtime-env-DadgceZk.js";import{t as ye}from"./slugify-BYJ6QVAt.js";import{i as be}from"./archive-redaction-ByV7X5fs.js";import{r as xe}from"./binary-cache-bSOhqXB1.js";import{i as Se,n as A,r as j,t as Ce}from"./fetch-body-CuwTaJC_.js";import{a as we,c as M,i as Te,o as N,s as Ee,t as P}from"./api-endpoint-Lx_FU5cP.js";import{$ as F,A as De,At as Oe,B as ke,Bt as Ae,C as I,Ct as je,D as Me,Dt as Ne,E as Pe,Et as Fe,F as Ie,Ft as Le,G as Re,H as ze,I as Be,It as Ve,J as He,K as Ue,L as We,Lt as Ge,M as Ke,Mt as qe,N as Je,Nt as Ye,O as Xe,Ot as Ze,P as Qe,Pt as $e,Q as et,R as tt,Rt as nt,S as rt,St as it,T as at,Tt as ot,U as st,V as ct,Vt as lt,W as eee,X as ut,Y as dt,Z as ft,_ as pt,_t as mt,a as ht,at as gt,b as _t,bt as vt,c as yt,ct as bt,d as xt,dt as St,et as Ct,f as wt,ft as Tt,g as Et,gt as L,h as Dt,ht as R,i as Ot,it as tee,j as kt,jt as At,k as jt,kt as Mt,l as Nt,lt as Pt,m as Ft,mt as It,nt as Lt,o as Rt,ot as zt,p as Bt,pt as Vt,q as Ht,rt as nee,s as Ut,st as Wt,t as Gt,tt as Kt,u as qt,ut as Jt,v as Yt,vt as Xt,w as Zt,wt as Qt,x as $t,xt as z,y as en,yt as tn,z as nn,zt as rn}from"./core-D59qaXEb.js";import{a as an}from"./models-4WTk3EBD.js";import{o as on,t as sn}from"./compat-uEPf6-XW.js";import{t as cn}from"./__vite-browser-external-5eBdwsFd.js";import{n as ln,r as un}from"./attachments-u2K0aIPI.js";import{i as dn,n as ree,r as iee,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as fn}from"./secrets-bridge-client-DBeju3mP.js";import{t as pn}from"./image-markers-DuyWsic3.js";import{i as mn,r as cee}from"./budget-usage-source-CI1VrdHF.js";import{a as hn,i as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{a as yn,i as bn,o as xn,r as lee,t as uee}from"./agent-bridge-DPAiiTJu.js";import{A as Sn,C as Cn,D as wn,E as Tn,S as En,T as Dn,_ as On,a as kn,c as An,d as jn,f as Mn,g as Nn,h as Pn,k as Fn,l as In,m as Ln,n as Rn,o as zn,p as Bn,r as Vn,s as Hn,t as Un,u as Wn,v as Gn,w as Kn,y as qn}from"./record-YqlVEfh_.js";import{c as Jn,d as Yn,i as Xn,l as Zn,n as Qn,o as $n,r as er,s as dee,u as tr}from"./descriptor-D-6Koktu.js";import{a as fee,c as pee,i as mee,l as nr,o as hee,r as gee,s as _ee,u as vee}from"./agent-message-to-chat-w7n13QEN.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{n as ar,t as or}from"./types-Dgm4REV3.js";import{i as sr}from"./mount-index-D9w_zMSm.js";import{a as cr,c as lr,i as ur,l as dr,n as fr,o as pr,r as mr,s as hr,u as gr}from"./mount-BU0YiStI.js";import{o as _r}from"./mount-table-store-DrF_Ifaz.js";import{t as vr}from"./remote-cache-BE5T1-53.js";import{i as yr,n as br,r as xr}from"./fs-D_5Hf9-X.js";import{r as Sr,t as Cr}from"./mount-recovery-szxkUpiN.js";import{r as wr,t as Tr}from"./key-DExP84Xm.js";import{n as Er,t as Dr}from"./manager-CstXzWYQ.js";import{a as Or,c as kr,i as Ar,n as jr,o as Mr,r as Nr,s as Pr}from"./lick-urls-HYeTtmbf.js";import{C as Fr,D as Ir,E as Lr,S as Rr,_ as zr,a as Br,b as Vr,d as Hr,g as Ur,h as Wr,m as Gr,n as Kr,o as qr,r as Jr,s as Yr,t as Xr,u as Zr,w as Qr,y as $r}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config--rtR6Gxd.js";import{n as ei,r as ti,t as ni}from"./slicc-version-BTzaBTax.js";import{r as ri}from"./virtual-device-paths-CS5o4QVz.js";import{a as ii,i as ai,n as B,r as oi,t as si}from"./browser-q8slJ96R.js";import{t as V}from"./subcommand-flags-BZi7j78Q.js";import{n as ci,r as li,t as ui}from"./subcommand-help-CgO7wRS5.js";import{a as di,i as fi,n as pi,r as mi}from"./cost-command-B5aRQX4l.js";import{a as hi,c as gi,d as _i,f as vi,h as yi,i as bi,l as xi,m as Si,n as Ci,o as wi,p as Ti,r as Ei,s as Di,t as Oi,u as ki}from"./sudoers-KgJRnN4b.js";import{a as Ai,i as ji,n as Mi,o as Ni,r as Pi,s as Fi}from"./skills-CyAtIBDH.js";import{a as Ii,c as Li,i as Ri,l as zi,n as Bi,o as Vi,r as yee,t as bee}from"./types-BfwydWt7.js";import{n as Hi,t as Ui}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as xee}from"./html-B_Hg2WOy.js";import{n as See,t as Cee}from"./llm-session-id-BZyXP_j2.js";import{a as wee}from"./frozen-archive-format-B4efpvB9.js";import{n as Tee,r as Eee}from"./derive-BqbmiIL9.js";import{n as Dee,t as Oee}from"./cone-memory-budget-ieIsscyt.js";import{i as kee,r as Aee}from"./browser-2rCVqcqy.js";import{a as jee}from"./gelatiere-constants-BYJlhm8R.js";import{n as Wi,t as Gi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ki,_ as qi,a as Ji,b as Yi,c as Xi,d as Mee,f as Nee,g as Pee,h as Fee,i as Zi,l as Iee,n as Qi,o as $i,p as Lee,r as ea,s as ta,t as na,u as ra,v as H,x as ia,y as aa}from"./state-DVDUDADZ.js";import{a as oa,i as sa,r as ca,t as la}from"./git-config-Bdgu8kD2.js";import{a as ua,c as da,i as fa,o as pa,r as ma,s as ha,t as ga}from"./script-catalog-Bt94D0RP.js";import{t as _a}from"./process-manager-BkhAohXT.js";import{A as va,C as ya,F as ba,I as xa,N as Sa,P as Ree,_ as zee,a as Ca,b as wa,c as Ta,d as Ea,f as Da,g as Bee,h as Oa,i as ka,j as Vee,l as Hee,m as Uee,n as Wee,o as Aa,p as ja,r as Ma,s as Na,t as Pa,u as Fa,v as Ia,x as La,y as Ra}from"./shared-C_68vn79.js";import{t as za}from"./tmpdir-env-ate4iNcK.js";import{t as Ba}from"./realm-browser-fetch-V3uggGbM.js";import{n as Va,t as Ha}from"./esbuild-wasm-DS_YG2EY.js";import{n as Ua,t as Wa}from"./wasm-compiler-Ct7QZURL.js";import{n as Ga,r as Ka,t as qa}from"./just-bash-compat-_TMo8UnL.js";import{_ as Ja,a as Ya,c as Xa,f as Za,g as Qa,h as $a,l as eo,m as to,n as no,p as ro,r as io,u as ao,v as oo,y as so}from"./github-zip-CowqpWqM.js";import{a as co,c as lo,d as uo,f as fo,i as po,l as mo,n as ho,o as go,p as _o,r as vo,s as yo,u as bo}from"./github-install-CfilaKPL.js";import{n as xo,t as So}from"./magick-wasm-DCNZhAyd.js";import{i as Co,n as wo,r as To,t as Eo}from"./pdf-raster-BWk6ezTX.js";import{n as Do,t as Oo}from"./lick-target-env-8JxfVcIV.js";import{a as ko,c as Ao,d as jo,f as Mo,i as No,l as Po,n as Fo,o as Io,p as Lo,r as Ro,s as zo,t as Bo,u as Vo}from"./installer-D4WxHb-C.js";import{n as Ho,r as Uo,t as Wo}from"./extension-media-capture-CRjN0St9.js";import{t as Go}from"./local-llm-3efEmI2R.js";import{t as Ko}from"./client-BOSdqiLb.js";import{t as qo}from"./redirect-uri-C6BjkDE0.js";let Jo=null;function Yo(e){Jo=e!==null&&Number.isFinite(e)&&e>0?e:null}function Xo(){if(Jo!==null)return Jo;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Zo=[`/workspace`,`/shared`,`/scoops`,`/home`];var Qo=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function $o(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 es=r(`cdp`);function ts(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 ns=class{ws=null;nextId=1;_superseded=!1;pending=new Qo;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,es.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(es.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(),es.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),es.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 $o(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;es.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(es.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;es.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,es.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?es.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):es.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(ts(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{}}}},rs=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 is(e,t){if(e?.aborted)throw new rs(t)}function as(e,t){return e?{signal:e,error:()=>new rs(t)}:void 0}function os(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new rs(n));return}let a=()=>{clearTimeout(o),i(new rs(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ss(e,t,n){return t?t.aborted?Promise.reject(new rs(n)):new Promise((r,i)=>{let a=()=>i(new rs(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 cs=r(`har-recorder`);var ls=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)}`;is(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),is(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),is(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}`),cs.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=>{cs.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=>{cs.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 us(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return cs.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 cs.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)),cs.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 cs.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 us(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){cs.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return cs.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ds=`(function() {
|
|
1
|
+
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import{a as i,i as a,n as o,o as s,r as c,t as l}from"./snapshot-D912sxnM.js";import{n as u,r as d,t as f}from"./panel-rpc-BPwAqRch.js";import{n as p,r as m,t as h}from"./feature-flags-BIRXJe0o.js";import{a as g,t as _}from"./providers-CKUtckcc.js";import{r as v,t as y}from"./base64-DzRgusa4.js";import{n as b}from"./bridge-protocol-DdqxTTSu.js";import{t as x}from"./content-type-_QKWY0B2.js";import{a as S,c as C,i as w,l as T,o as E,r as D,s as ee,t as te,u as ne}from"./lick-manager-ULemXDKa.js";import{a as re,b as O,d as ie,f as ae,g as oe,h as se,i as ce,m as le,p as ue,u as de,v as fe,x as pe,y as k}from"./account-store-B3TDSGgR.js";import{a as me,l as he,n as ge,o as _e}from"./proxied-fetch-B57RqgUb.js";import{t as ve}from"./runtime-env-DadgceZk.js";import{t as ye}from"./slugify-BYJ6QVAt.js";import{i as be}from"./archive-redaction-ByV7X5fs.js";import{r as xe}from"./binary-cache-bSOhqXB1.js";import{i as Se,n as A,r as j,t as Ce}from"./fetch-body-CuwTaJC_.js";import{a as we,c as M,i as Te,o as N,s as Ee,t as P}from"./api-endpoint-Lx_FU5cP.js";import{$ as F,A as De,At as Oe,B as ke,Bt as Ae,C as I,Ct as je,D as Me,Dt as Ne,E as Pe,Et as Fe,F as Ie,Ft as Le,G as Re,H as ze,I as Be,It as Ve,J as He,K as Ue,L as We,Lt as Ge,M as Ke,Mt as qe,N as Je,Nt as Ye,O as Xe,Ot as Ze,P as Qe,Pt as $e,Q as et,R as tt,Rt as nt,S as rt,St as it,T as at,Tt as ot,U as st,V as ct,Vt as lt,W as eee,X as ut,Y as dt,Z as ft,_ as pt,_t as mt,a as ht,at as gt,b as _t,bt as vt,c as yt,ct as bt,d as xt,dt as St,et as Ct,f as wt,ft as Tt,g as Et,gt as L,h as Dt,ht as R,i as Ot,it as tee,j as kt,jt as At,k as jt,kt as Mt,l as Nt,lt as Pt,m as Ft,mt as It,nt as Lt,o as Rt,ot as zt,p as Bt,pt as Vt,q as Ht,rt as nee,s as Ut,st as Wt,t as Gt,tt as Kt,u as qt,ut as Jt,v as Yt,vt as Xt,w as Zt,wt as Qt,x as $t,xt as z,y as en,yt as tn,z as nn,zt as rn}from"./core-D59qaXEb.js";import{a as an}from"./models-4WTk3EBD.js";import{o as on,t as sn}from"./compat-uEPf6-XW.js";import{t as cn}from"./__vite-browser-external-5eBdwsFd.js";import{n as ln,r as un}from"./attachments-u2K0aIPI.js";import{i as dn,n as ree,r as iee,t as aee}from"./context-compaction-DRymamfD.js";import{n as oee,t as see}from"./mime-types-D7IV6i7k.js";import{t as fn}from"./secrets-bridge-client-DBeju3mP.js";import{t as pn}from"./image-markers-DuyWsic3.js";import{i as mn,r as cee}from"./budget-usage-source-DVW8NROx.js";import{a as hn,i as gn,n as _n,t as vn}from"./path-utils-DNJG-zQf.js";import{a as yn,i as bn,o as xn,r as lee,t as uee}from"./agent-bridge-C2T3pN-e.js";import{A as Sn,C as Cn,D as wn,E as Tn,S as En,T as Dn,_ as On,a as kn,c as An,d as jn,f as Mn,g as Nn,h as Pn,k as Fn,l as In,m as Ln,n as Rn,o as zn,p as Bn,r as Vn,s as Hn,t as Un,u as Wn,v as Gn,w as Kn,y as qn}from"./record-YqlVEfh_.js";import{c as Jn,d as Yn,i as Xn,l as Zn,n as Qn,o as $n,r as er,s as dee,u as tr}from"./descriptor-D-6Koktu.js";import{a as fee,c as pee,i as mee,l as nr,o as hee,r as gee,s as _ee,u as vee}from"./agent-message-to-chat-w7n13QEN.js";import{n as rr,t as ir}from"./thinking-level-5x0UAu9N.js";import{n as ar,t as or}from"./types-Dgm4REV3.js";import{i as sr}from"./mount-index-D9w_zMSm.js";import{a as cr,c as lr,i as ur,l as dr,n as fr,o as pr,r as mr,s as hr,u as gr}from"./mount-C_z-hY6d.js";import{o as _r}from"./mount-table-store-DrF_Ifaz.js";import{t as vr}from"./remote-cache-BE5T1-53.js";import{i as yr,n as br,r as xr}from"./fs-BjSQWu2g.js";import{r as Sr,t as Cr}from"./mount-recovery-Wt3z_gJ-.js";import{r as wr,t as Tr}from"./key-DExP84Xm.js";import{n as Er,t as Dr}from"./manager-CstXzWYQ.js";import{a as Or,c as kr,i as Ar,n as jr,o as Mr,r as Nr,s as Pr}from"./lick-urls-HYeTtmbf.js";import{C as Fr,D as Ir,E as Lr,S as Rr,_ as zr,a as Br,b as Vr,d as Hr,g as Ur,h as Wr,m as Gr,n as Kr,o as qr,r as Jr,s as Yr,t as Xr,u as Zr,w as Qr,y as $r}from"./db-DSIYsBgP.js";import"./tray-storage-keys-DbThbnIh.js";import"./tray-runtime-config--rtR6Gxd.js";import{n as ei,r as ti,t as ni}from"./slicc-version-CveLv8QB.js";import{r as ri}from"./virtual-device-paths-CS5o4QVz.js";import{a as ii,i as ai,n as B,r as oi,t as si}from"./browser-q8slJ96R.js";import{t as V}from"./subcommand-flags-BZi7j78Q.js";import{n as ci,r as li,t as ui}from"./subcommand-help-CgO7wRS5.js";import{a as di,i as fi,n as pi,r as mi}from"./cost-command-B5aRQX4l.js";import{a as hi,c as gi,d as _i,f as vi,h as yi,i as bi,l as xi,m as Si,n as Ci,o as wi,p as Ti,r as Ei,s as Di,t as Oi,u as ki}from"./sudoers-KgJRnN4b.js";import{a as Ai,i as ji,n as Mi,o as Ni,r as Pi,s as Fi}from"./skills-MQBhN1sp.js";import{a as Ii,c as Li,i as Ri,l as zi,n as Bi,o as Vi,r as yee,t as bee}from"./types-BfwydWt7.js";import{n as Hi,t as Ui}from"./boundary-Cp9c_bPu.js";import"./rest-paths-Dia19u9P.js";import{t as xee}from"./html-B_Hg2WOy.js";import{n as See,t as Cee}from"./llm-session-id-BZyXP_j2.js";import{a as wee}from"./frozen-archive-format-B4efpvB9.js";import{n as Tee,r as Eee}from"./derive-BqbmiIL9.js";import{n as Dee,t as Oee}from"./cone-memory-budget-ieIsscyt.js";import{i as kee,r as Aee}from"./browser-2rCVqcqy.js";import{a as jee}from"./gelatiere-constants-BYJlhm8R.js";import{n as Wi,t as Gi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{S as Ki,_ as qi,a as Ji,b as Yi,c as Xi,d as Mee,f as Nee,g as Pee,h as Fee,i as Zi,l as Iee,n as Qi,o as $i,p as Lee,r as ea,s as ta,t as na,u as ra,v as H,x as ia,y as aa}from"./state-BjKxySu5.js";import{a as oa,i as sa,r as ca,t as la}from"./git-config-Bdgu8kD2.js";import{a as ua,c as da,i as fa,o as pa,r as ma,s as ha,t as ga}from"./script-catalog-Bt94D0RP.js";import{t as _a}from"./process-manager-BkhAohXT.js";import{A as va,C as ya,F as ba,I as xa,N as Sa,P as Ree,_ as zee,a as Ca,b as wa,c as Ta,d as Ea,f as Da,g as Bee,h as Oa,i as ka,j as Vee,l as Hee,m as Uee,n as Wee,o as Aa,p as ja,r as Ma,s as Na,t as Pa,u as Fa,v as Ia,x as La,y as Ra}from"./shared-C_68vn79.js";import{t as za}from"./tmpdir-env-ate4iNcK.js";import{t as Ba}from"./realm-browser-fetch-V3uggGbM.js";import{n as Va,t as Ha}from"./esbuild-wasm-DS_YG2EY.js";import{n as Ua,t as Wa}from"./wasm-compiler-Ct7QZURL.js";import{n as Ga,r as Ka,t as qa}from"./just-bash-compat-_TMo8UnL.js";import{_ as Ja,a as Ya,c as Xa,f as Za,g as Qa,h as $a,l as eo,m as to,n as no,p as ro,r as io,u as ao,v as oo,y as so}from"./github-zip-DwdgFfY8.js";import{a as co,c as lo,d as uo,f as fo,i as po,l as mo,n as ho,o as go,p as _o,r as vo,s as yo,u as bo}from"./github-install-CB0ldULv.js";import{n as xo,t as So}from"./magick-wasm-DCNZhAyd.js";import{i as Co,n as wo,r as To,t as Eo}from"./pdf-raster-BWk6ezTX.js";import{n as Do,t as Oo}from"./lick-target-env-8JxfVcIV.js";import{a as ko,c as Ao,d as jo,f as Mo,i as No,l as Po,n as Fo,o as Io,p as Lo,r as Ro,s as zo,t as Bo,u as Vo}from"./installer-D4WxHb-C.js";import{n as Ho,r as Uo,t as Wo}from"./extension-media-capture-CRjN0St9.js";import{t as Go}from"./local-llm-BxL33fhK.js";import{t as Ko}from"./client-BOSdqiLb.js";import{t as qo}from"./redirect-uri-C6BjkDE0.js";let Jo=null;function Yo(e){Jo=e!==null&&Number.isFinite(e)&&e>0?e:null}function Xo(){if(Jo!==null)return Jo;let e=globalThis.performance?.timeOrigin;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:Date.now()}const Zo=[`/workspace`,`/shared`,`/scoops`,`/home`];var Qo=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function $o(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 es=r(`cdp`);function ts(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 ns=class{ws=null;nextId=1;_superseded=!1;pending=new Qo;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,es.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(es.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(),es.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),es.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 $o(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;es.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(es.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;es.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,es.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?es.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):es.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(ts(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{}}}},rs=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 is(e,t){if(e?.aborted)throw new rs(t)}function as(e,t){return e?{signal:e,error:()=>new rs(t)}:void 0}function os(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new rs(n));return}let a=()=>{clearTimeout(o),i(new rs(n))},o=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function ss(e,t,n){return t?t.aborted?Promise.reject(new rs(n)):new Promise((r,i)=>{let a=()=>i(new rs(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 cs=r(`har-recorder`);var ls=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)}`;is(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),is(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),is(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}`),cs.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=>{cs.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=>{cs.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 us(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return cs.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 cs.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)),cs.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 cs.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 us(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){cs.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return cs.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ds=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -880,7 +880,7 @@ import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}f
|
|
|
880
880
|
|
|
881
881
|
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function dae(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function fae(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function pae(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function mae(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function hae(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" to deny.`),{label:t,content:o.join(`
|
|
882
882
|
`)}}function gae(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
|
|
883
|
-
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function qg(e,t){let n=cae(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function _ae(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return qg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function vae(e,t){let n=qg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Jg(e){let t=sae[e.type];return e.type===`session-reload`?lae(e,t):e.type===`upgrade`?uae(e,t):e.type===`cherry`?dae(e,t):e.type===`preview`?fae(e,t):e.type===`workflow`?pae(e,t):e.type===`bash`?mae(e,t):e.type===`sudo-request`?hae(e,t):e.type===`navigate`?vae(e,t):e.type===`webhook`?_ae(e,t):e.type===`discovery`?gae(e,t):qg(e,t)}const Yg=new Map;function yae(e){let t=Yg.get(e.id);t&&(Yg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Xg=`slicc-sprinkle-routes`;function Zg(){try{let e=localStorage.getItem(Xg);return e?JSON.parse(e):{}}catch{return{}}}function Qg(e){try{localStorage.setItem(Xg,JSON.stringify(e))}catch{}}function $g(e){return Zg()[e]}function e_(e,t){let n=Zg();n[e]=t,Qg(n)}function t_(e){let t=Zg();delete t[e],Qg(t)}function bae(){return Zg()}const xae=r(`kernel-agent-event-stream`);var Sae=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){xae.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${Cae()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Cae(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var wae=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Tae(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=Tn(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Tae(e){let t=An(e),n=In(e),{level:r,effortOverride:i}=Pn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}let Eae={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function n_(){return{...Eae}}function Dae(){let e=n_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(Pr);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const r_=new Set;function Oae(e){return r_.add(e),()=>{r_.delete(e)}}const i_=`slicc.trayWorkerBaseUrl`,a_=`slicc.trayJoinUrl`;function kae(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return rc(t.toString());let i=nc(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function o_(e){let t=kae(e);return t?.joinUrl?t:null}function s_(){return Aae(Or(),n_())}function Aae(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const c_=`__slicc_binary__`;function l_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[c_]===`b64`&&typeof t.data==`string`}function jae(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function Mae(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!l_(e)}function u_(e){if(e instanceof Uint8Array)return{[c_]:`b64`,data:v(e)};if(Array.isArray(e))return e.map(u_);if(jae(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=u_(r);return t}return e}function d_(e){if(l_(e))return y(e.data);if(Array.isArray(e))return e.map(d_);if(Mae(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=d_(r);return t}return e}const Nae=r(`panel-transport`);function Pae(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Fae(){return{onMessage:e=>{let t=(t,n,r)=>(Pae(t)&&e(d_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=u_(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Nae.error(`Offscreen → panel transport send failed`,{error:t})})}}}const f_=r(`kernel-bridge`);function p_(){return globalThis}function Iae(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var m_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new Ug(e=>`compaction-${e}-${h_()}`);pendingMarkers=new Map;scoopPresentation=new wae;agentEventStream=new Sae;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Fae(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Vg;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${h_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{nr.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{nr.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=hee(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??h_(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=_ee(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:pee(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Rn(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],s_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...s_()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Iae(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??$g(e),s=o?fc(a,o):void 0;if(s||=this.originRootOf(a,r?.unitJid)??Tn(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Jg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,u={id:c,chatJid:s.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:l,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(s.jid).push({id:c,role:`user`,content:l,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(s.jid),await this.orchestrator.handleMessage(u)}originRootOf(e,t){if(t)return Dn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=Tn(this.orchestrator.getScoops())[0];if(!t)return;let n=__(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=Rn(t);this.sessionStore.saveMessages(n,e).catch(e=>{f_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?Tn(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-w7n13QEN.js`).then(e=>e.n),i=r(n,{source:Ln(e)}),{interleaveMarkers:a}=await import(`./derive-BqbmiIL9.js`).then(e=>e.t);return this.overlayPersistedLickDecisionsOn(e,await this.withPersistedErrorCards(e,__(a(i,await this.loadConversationMarkers(e)))))}async loadConversationMarkers(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return;let{conversationKeyFor:n}=await import(`./key-DExP84Xm.js`).then(e=>e.n);return(await t.load(n(e)))?.markers}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-DExP84Xm.js`).then(e=>e.n),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await import(`./derive-BqbmiIL9.js`).then(e=>e.t),a=await i(r,{source:Ln(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,await this.withPersistedErrorCards(e,__(a)))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];if(this.sessionStore)try{let t=await this.sessionStore.load(Rn(e));t?.messages&&n.push(...t.messages)}catch{}try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return zae(t,n)}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n,queuedIds:this.queuedIdsFor(e)});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r,queuedIds:this.queuedIdsFor(e)});return}let i=await this.buildBufferFromCanonicalRecord(t);if(i){this.messageBuffers.set(e,i),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:i});return}if(this.sessionStore){let n=Rn(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t,queuedIds:this.queuedIdsFor(e)});return}}catch(e){f_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[],queuedIds:this.queuedIdsFor(e)})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=Vn(e,i),o=a===Un,s=Tn(i)[0],c=r??(s?Hn(s):void 0),l=t?.trim(),u={...Er({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([mn().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(mn().catch(()=>null),cee()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:g_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-w7n13QEN.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:Ln(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:g_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=Rn(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}this.persistScoop(e);let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-DExP84Xm.js`).then(e=>e.n),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationKeyFor:i}=await import(`./key-DExP84Xm.js`).then(e=>e.n),a=i(r),o=[];for(let e of t)await n.putMarker(a,e)||o.push(e);o.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,o)}recordErrorCard(e,t){this.getBuffer(e).push({id:h_(),role:`assistant`,content:t,timestamp:Date.now(),error:!0}),this.persistScoop(e)}async withPersistedErrorCards(e,t){if(!this.sessionStore)return t;try{return Lae(t,(await this.sessionStore.load(Rn(e)))?.messages)}catch{return t}}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=Rn(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){f_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${h_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Ln(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){yae(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),Ms(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Ms(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Ms()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=p_()[uee];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&Cn(n)){if(Tn(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Rn({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??Tn(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Rn({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=p_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=p_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Rt.markMounted(t);return}try{await Rt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Rt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function h_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function g_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
883
|
+
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function qg(e,t){let n=cae(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function _ae(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return qg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function vae(e,t){let n=qg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill … --all\` with any branch/path scope from the body, so it installs EVERY skill under that scope — a broad path can be many); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Jg(e){let t=sae[e.type];return e.type===`session-reload`?lae(e,t):e.type===`upgrade`?uae(e,t):e.type===`cherry`?dae(e,t):e.type===`preview`?fae(e,t):e.type===`workflow`?pae(e,t):e.type===`bash`?mae(e,t):e.type===`sudo-request`?hae(e,t):e.type===`navigate`?vae(e,t):e.type===`webhook`?_ae(e,t):e.type===`discovery`?gae(e,t):qg(e,t)}const Yg=new Map;function yae(e){let t=Yg.get(e.id);t&&(Yg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Xg=`slicc-sprinkle-routes`;function Zg(){try{let e=localStorage.getItem(Xg);return e?JSON.parse(e):{}}catch{return{}}}function Qg(e){try{localStorage.setItem(Xg,JSON.stringify(e))}catch{}}function $g(e){return Zg()[e]}function e_(e,t){let n=Zg();n[e]=t,Qg(n)}function t_(e){let t=Zg();delete t[e],Qg(t)}function bae(){return Zg()}const xae=r(`kernel-agent-event-stream`);var Sae=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){xae.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${Cae()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Cae(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var wae=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Tae(e);return{jid:e.jid,name:e.name,folder:e.folder,parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=Tn(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Tae(e){let t=An(e),n=In(e),{level:r,effortOverride:i}=Pn(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}let Eae={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function n_(){return{...Eae}}function Dae(){let e=n_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(Pr);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const r_=new Set;function Oae(e){return r_.add(e),()=>{r_.delete(e)}}const i_=`slicc.trayWorkerBaseUrl`,a_=`slicc.trayJoinUrl`;function kae(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return rc(t.toString());let i=nc(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function o_(e){let t=kae(e);return t?.joinUrl?t:null}function s_(){return Aae(Or(),n_())}function Aae(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const c_=`__slicc_binary__`;function l_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[c_]===`b64`&&typeof t.data==`string`}function jae(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)}function Mae(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Uint8Array)&&!l_(e)}function u_(e){if(e instanceof Uint8Array)return{[c_]:`b64`,data:v(e)};if(Array.isArray(e))return e.map(u_);if(jae(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=u_(r);return t}return e}function d_(e){if(l_(e))return y(e.data);if(Array.isArray(e))return e.map(d_);if(Mae(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=d_(r);return t}return e}const Nae=r(`panel-transport`);function Pae(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Fae(){return{onMessage:e=>{let t=(t,n,r)=>(Pae(t)&&e(d_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=u_(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Nae.error(`Offscreen → panel transport send failed`,{error:t})})}}}const f_=r(`kernel-bridge`);function p_(){return globalThis}function Iae(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var m_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;conesBeingCreated=new Map;currentMessageId=new Map;compactionRows=new Ug(e=>`compaction-${e}-${h_()}`);pendingMarkers=new Map;scoopPresentation=new wae;agentEventStream=new Sae;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Fae(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Vg;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.flushPendingMarkers(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${h_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n,r)=>{let i=e.compactionRows.apply(t,n,r);e.emit({type:`compaction-state`,scoopJid:t,state:n,trigger:r.trigger,...r.transcriptPath?{transcriptPath:r.transcriptPath}:{},...r.roundId?{roundId:r.roundId}:{},...i?{rowId:i.messageId}:{}}),e.recordCompactionRow(t,i)},onError:(t,n)=>{e.recordErrorCard(t,n),e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{nr.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{nr.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=hee(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??h_(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=_ee(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:pee(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Rn(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],s_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...s_()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Iae(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=$g(e),s=[];n&&s.push({source:`explicit target`,value:n}),o&&o!==n&&s.push({source:`configured route`,value:o});let c=[],l;for(let e of s){if(l=fc(a,e.value),l)break;c.push(e)}if(l||=this.originRootOf(a,r?.unitJid)??Tn(a)[0],c.length>0&&f_.warn(`Sprinkle lick target could not be resolved; using fallback`,{sprinkleName:e,unresolvedTargets:c,fallbackJid:l?.jid}),!l)return;let u=`sprinkle-${e}-${Date.now()}`,d=Jg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r?.label})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,f=c.map(({source:e,value:t})=>`${e} ${JSON.stringify(t)}`).join(` and `),p=d+(f?`\n\n> Delivery note: ${f} could not be resolved; delivered to fallback ${JSON.stringify(l.folder)}.`:``),m={id:u,chatJid:l.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:p,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(l.jid).push({id:u,role:`user`,content:p,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(l.jid),await this.orchestrator.handleMessage(m)}originRootOf(e,t){if(t)return Dn(e,e.find(e=>e.jid===t))}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=Tn(this.orchestrator.getScoops())[0];if(!t)return;let n=__(e).map((t,n)=>({...t,isStreaming:e[n]?.isStreaming}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=Rn(t);this.sessionStore.saveMessages(n,e).catch(e=>{f_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?Tn(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-w7n13QEN.js`).then(e=>e.n),i=r(n,{source:Ln(e)}),{interleaveMarkers:a}=await import(`./derive-BqbmiIL9.js`).then(e=>e.t);return this.overlayPersistedLickDecisionsOn(e,await this.withPersistedErrorCards(e,__(a(i,await this.loadConversationMarkers(e)))))}async loadConversationMarkers(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return;let{conversationKeyFor:n}=await import(`./key-DExP84Xm.js`).then(e=>e.n);return(await t.load(n(e)))?.markers}async buildBufferFromCanonicalRecord(e){let t=this.orchestrator?.getConversationStore?.();if(!t)return null;let{conversationKeyFor:n}=await import(`./key-DExP84Xm.js`).then(e=>e.n),r=await t.load(n(e));if(!r)return null;let{toChatMessages:i}=await import(`./derive-BqbmiIL9.js`).then(e=>e.t),a=await i(r,{source:Ln(e)});return a.length===0?null:this.overlayPersistedLickDecisionsOn(e,await this.withPersistedErrorCards(e,__(a)))}async overlayPersistedLickDecisionsOn(e,t){if(!t.some(e=>e.channel===`sudo-request`||e.lickId||e.lickState))return t;let n=[];if(this.sessionStore)try{let t=await this.sessionStore.load(Rn(e));t?.messages&&n.push(...t.messages)}catch{}try{let t=await this.orchestrator?.getMessagesForScoop?.(e.jid);if(t)for(let e of t)n.push({id:e.id,content:e.content,channel:e.channel,lickId:e.lickId,lickState:e.lickState})}catch{}return zae(t,n)}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}queuedIdsFor(e){if(!(this.followerSync||!this.orchestrator))return this.orchestrator.getQueuedMessageIds(e)}async handleRequestScoopMessages(e){if(await this.conesBeingCreated.get(e),!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n,queuedIds:this.queuedIdsFor(e)});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r,queuedIds:this.queuedIdsFor(e)});return}let i=await this.buildBufferFromCanonicalRecord(t);if(i){this.messageBuffers.set(e,i),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:i});return}if(this.sessionStore){let n=Rn(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t,queuedIds:this.queuedIdsFor(e)});return}}catch(e){f_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[],queuedIds:this.queuedIdsFor(e)})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=Vn(e,i),o=a===Un,s=Tn(i)[0],c=r??(s?Hn(s):void 0),l=t?.trim(),u={...Er({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}},d=()=>{};this.conesBeingCreated.set(u.jid,new Promise(e=>{d=e}));let f=()=>{this.conesBeingCreated.delete(u.jid),d()};try{await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let e=n?.trim();if(!e)return;let t=this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:e,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});f(),await t}finally{f()}}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=t.approver;if(r&&r.kind!==`user`){let i=this.orchestrator;if(!i)console.warn(`[kernel-bridge] directed approval before orchestrator init — denying`);else try{n=await i.enqueueDirectedApproval(r,t)}catch(e){console.warn(`[kernel-bridge] directed approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n});return}let i=this.orchestrator?.getSudoManager()??null;if(!i)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await i.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}async handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}let o=await this.resolveBudgetWindow();this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a,...o?{budget:o}:{}})}budgetProbePending=!0;async resolveBudgetWindow(){return this.budgetProbePending?(this.budgetProbePending=!1,await Promise.race([mn().catch(()=>null),new Promise(e=>setTimeout(()=>e(null),2500))])??void 0):(mn().catch(()=>null),cee()??void 0)}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:g_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-w7n13QEN.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:Ln(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:g_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=Rn(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}async recordCompactionRow(e,t){if(!t||t.kind===`open`)return;let n=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n)return;let r=this.getBuffer(e);if(t.kind===`retract`){let e=r.findIndex(e=>e.id===t.messageId);e>=0&&r.splice(e,1)}else{let e=r.find(e=>e.id===t.messageId);e?e.compaction=t.marker:r.push({id:t.messageId,role:`assistant`,content:``,timestamp:Date.now(),compaction:t.marker})}this.persistScoop(e);let i=this.orchestrator?.getConversationStore?.();if(!i)return;let{conversationKeyFor:a}=await import(`./key-DExP84Xm.js`).then(e=>e.n),o=a(n);if(t.kind===`retract`){this.dropPendingMarker(e,t.messageId),await i.deleteMarker(o,t.messageId);return}let s={id:t.messageId,kind:`compaction`,timestamp:Date.now(),compaction:t.marker};await i.putMarker(o,s)||this.holdPendingMarker(e,s)}holdPendingMarker(e,t){let n=this.pendingMarkers.get(e)??[];this.pendingMarkers.set(e,[...n.filter(e=>e.id!==t.id),t].slice(-4))}dropPendingMarker(e,t){let n=this.pendingMarkers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,r)}async flushPendingMarkers(e){let t=this.pendingMarkers.get(e);if(!t||t.length===0)return;let n=this.orchestrator?.getConversationStore?.(),r=this.orchestrator?.getScoops().find(t=>t.jid===e);if(!n||!r)return;let{conversationKeyFor:i}=await import(`./key-DExP84Xm.js`).then(e=>e.n),a=i(r),o=[];for(let e of t)await n.putMarker(a,e)||o.push(e);o.length===0?this.pendingMarkers.delete(e):this.pendingMarkers.set(e,o)}recordErrorCard(e,t){this.getBuffer(e).push({id:h_(),role:`assistant`,content:t,timestamp:Date.now(),error:!0}),this.persistScoop(e)}async withPersistedErrorCards(e,t){if(!this.sessionStore)return t;try{return Lae(t,(await this.sessionStore.load(Rn(e)))?.messages)}catch{return t}}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=Rn(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){f_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${h_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Ln(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){yae(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid,e.discardLiveSnapshot===!0);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.handleWebhookEventMsg(e);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value)),Ms(e.key);break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key)),Ms(e.key);break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear()),Ms()}}handleWebhookEventMsg(e){let t=this.orchestrator?.handleWebhookEvent(e.webhookId,e.headers,e.body);e.requestId&&this.emit({type:`lick-webhook-delivery`,requestId:e.requestId,disposition:t??`unknown-webhook`})}async handleAgentSpawn(e){let t=p_()[uee];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.guestGate?{guestGate:e.guestGate}:{},...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&Cn(n)){if(Tn(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);let i=new Set(this.orchestrator.getScoops().map(e=>e.jid));for(let e of[...r,n])i.has(e.jid)||this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Rn({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t,n=!1){let r=this.orchestrator?.getScoops()??[],i=(t?r.find(e=>e.jid===t):void 0)??Tn(r)[0],a=i?.jid;a&&(n?await this.orchestrator?.clearScoopMessages(a,{discardLiveSnapshot:!0}):await this.orchestrator?.clearScoopMessages(a)),this.sessionStore&&await this.sessionStore.delete(Rn({folder:i?.folder??`cone`})),a&&(this.messageBuffers.delete(a),this.currentMessageId.delete(a),this.agentEventStream.clear(a)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.origin)}handleSetFollowerForwarding(e){let t=p_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=p_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Rt.markMounted(t);return}try{await Rt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Rt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function h_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function g_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
884
884
|
`)}function __(e){return e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,lickId:e.lickId,lickState:e.lickState,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1,compaction:e.compaction,error:e.error}))}function Lae(e,t){if(!t||t.length===0)return e;let n=t.filter(e=>e.error===!0);if(n.length===0)return e;let r=new Set(e.map(e=>e.id)),i=n.filter(e=>!r.has(e.id));return i.length===0?e:Rae(e,__(i))}function Rae(e,t){let n=[...t].sort((e,t)=>v_(e)-v_(t)),r=[],i=0;for(let t of e){let e=v_(t);for(;i<n.length&&v_(n[i])<=e;)r.push(n[i++]);r.push(t)}for(;i<n.length;)r.push(n[i++]);return r}function v_(e){let t=e.timestamp;if(typeof t==`number`&&Number.isFinite(t))return t;if(typeof t==`string`){let e=Date.parse(t);if(!Number.isNaN(e))return e}return-1/0}function y_(e){return e===`confirmed`||e===`dismissed`}function b_(e){return e.channel===`sudo-request`||!!e.lickId||!!e.lickState||e.id.startsWith(`sudo-request-`)}function x_(e){return e.lickId?e.lickId:b_(e)?/^(?:Lick ID|Request ID): (\S+)/m.exec(e.content)?.[1]||(e.id.startsWith(`sudo-request-`)?e.id.slice(13):void 0):void 0}function S_(e,t,n){let r=e.get(t);(!r||y_(n.lickState)&&!y_(r.lickState))&&e.set(t,n)}function zae(e,t){if(!t||t.length===0)return e;let n=new Map,r=new Map,i=new Map;for(let e of t){if(!b_(e))continue;let t=x_(e);t&&S_(n,t,e),S_(r,e.id,e),S_(i,e.content,e)}return e.map(e=>{if(!b_(e))return e;let t=x_(e),a=(t?n.get(t):void 0)??r.get(e.id)??i.get(e.content);if(!a||!a.lickId&&!a.lickState)return e;let o=a.lickId??t??x_(a),s=y_(a.lickState)?a.lickState:e.lickState??a.lickState;return o===e.lickId&&s===e.lickState&&a.id===e.id?e:{...e,id:a.id,lickId:o,lickState:s}})}const C_=r(`navigation-watcher`);function w_(e){if(!e)return null;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:null}catch{return null}}function T_(e){return e.replace(/\/+$/,``)||`/`}function Bae(e){return t=>{let n=w_(e()??void 0);if(!n)return!1;let r=w_(t.url);return r?n.origin===r.origin&&T_(n.pathname)===T_(r.pathname):!1}}function Vae(e,t){return E(e,t)}var Hae=class{transport;onEvent;sessions=new Map;started=!1;unsubscribeState=null;rearming=!1;rearmQueued=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;isOwnTab;probedOrigins=new Set;pendingAttachTargetIds=new Set;ownSessionIds=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);this.sessions.delete(t),this.ownSessionIds.delete(t),n&&this.pendingAttachTargetIds.delete(n.targetId)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId){for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url));this.reconcileTargetNetwork(t)}};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameRequestedNavigation=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameStartedNavigating=e=>{let t=e;this.maybeArmNetwork(t.sessionId,t.frameId,t.url)};onFrameNavigated=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r)return;let i=t.frame;i?.id&&(i.parentId||(r.rootFrameId=i.id,typeof i.url==`string`&&(r.url=i.url)))};onResponseReceived=e=>{let t=e,n=t.sessionId;if(!n)return;let r=this.sessions.get(n);if(!r||t.type!==`Document`)return;let i=t.frameId;if(!i||i!==r.rootFrameId)return;let a=t.response;if(!a)return;let o=typeof a.url==`string`&&a.url.length>0?a.url:r.url;if(!o)return;let{match:s,links:c}=Vae(a.headers,o);if(s){let e={url:o,verb:s.verb,target:s.target,links:c,targetId:r.targetId};s.instruction!=null&&(e.instruction=s.instruction),s.branch!=null&&(e.branch=s.branch),s.path!=null&&(e.path=s.path),r.title!=null&&(e.title=r.title),this.onEvent(e)}this.maybeRunDiscovery(o,c,r.targetId)};eventBindings=[[`Target.attachedToTarget`,this.onAttachedToTarget],[`Target.detachedFromTarget`,this.onDetachedFromTarget],[`Target.targetInfoChanged`,this.onTargetInfoChanged],[`Target.targetCreated`,this.onTargetCreated],[`Page.frameNavigated`,this.onFrameNavigated],[`Page.frameRequestedNavigation`,this.onFrameRequestedNavigation],[`Page.frameStartedNavigating`,this.onFrameStartedNavigating],[`Network.responseReceived`,this.onResponseReceived]];constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs,this.isOwnTab=n.isOwnTab??(()=>!1)}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=T(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await ac(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){C_.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){if(this.registerListeners(),!await this.enableDiscovery()){this.unregisterListeners();return}this.started=!0,this.subscribeTransportState(),await this.enumeratePreexistingTargets()}}registerListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t),this.transport.on(e,t)}unregisterListeners(){for(let[e,t]of this.eventBindings)this.transport.off(e,t)}async enableDiscovery(){try{return await this.transport.send(`Target.setDiscoverTargets`,{discover:!0}),!0}catch(e){return C_.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),!1}}async enumeratePreexistingTargets(){try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;e||typeof n!=`string`||await this.requestAttach(n,`Failed to attach to preexisting target`)}}catch(e){C_.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}subscribeTransportState(){this.unsubscribeState||=this.transport.onStateChange?.(e=>{if(e===`disconnected`){this.clearConnectionScopedState();return}e===`connected`&&(this.rearming?this.rearmQueued=!0:this.rearmAfterReconnect())})??null}clearConnectionScopedState(){this.sessions.clear(),this.pendingAttachTargetIds.clear(),this.ownSessionIds.clear()}async rearmAfterReconnect(){if(!(!this.started||this.rearming)){this.rearming=!0;try{if(this.clearConnectionScopedState(),this.registerListeners(),!await this.enableDiscovery())return;await this.enumeratePreexistingTargets()}finally{this.rearming=!1,this.rearmQueued&&(this.rearmQueued=!1,this.rearmAfterReconnect())}}}async stop(){if(this.started){this.started=!1,this.unsubscribeState?.(),this.unsubscribeState=null,this.unregisterListeners(),this.clearConnectionScopedState();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){C_.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;t?.type===`page`&&typeof t.targetId==`string`&&(t.attached||await this.requestAttach(t.targetId,`Failed to attach to discovered target`))}maybeArmNetwork(e,t,n){if(!e||!t)return;let r=this.sessions.get(e);!r||r.networkEnabled||!this.ownSessionIds.has(e)||r.rootFrameId===t&&(this.isOwnTabSafe({targetId:r.targetId,url:n})||this.setSessionNetwork(e,r,!0))}reconcileTargetNetwork(e){let t=this.isOwnTabSafe(e);for(let[n,r]of this.sessions)r.targetId===e.targetId&&this.ownSessionIds.has(n)&&r.networkEnabled!==!t&&this.setSessionNetwork(n,r,!t)}async setSessionNetwork(e,t,n){t.networkEnabled=n;try{await this.transport.send(n?`Network.enable`:`Network.disable`,{},e)}catch(r){t.networkEnabled=!n,C_.debug(`Failed to ${n?`enable`:`disable`} Network on session`,{sessionId:e,targetId:t.targetId,error:r instanceof Error?r.message:String(r)})}}isOwnTabSafe(e){try{return this.isOwnTab(e)}catch(t){return C_.debug(`isOwnTab predicate threw; treating target as foreign`,{targetId:e.targetId,error:t instanceof Error?t.message:String(t)}),!1}}async requestAttach(e,t){this.pendingAttachTargetIds.add(e);try{let t=(await this.transport.send(`Target.attachToTarget`,{targetId:e,flatten:!0}))?.sessionId;typeof t==`string`&&t.length>0&&(this.ownSessionIds.add(t),this.pendingAttachTargetIds.delete(e))}catch(n){this.pendingAttachTargetIds.delete(e),C_.debug(t,{targetId:e,error:n instanceof Error?n.message:String(n)})}}claimOwnSession(e,t){return this.ownSessionIds.has(e)?!0:this.pendingAttachTargetIds.has(t)?(this.pendingAttachTargetIds.delete(t),this.ownSessionIds.add(e),!0):!1}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!t||!n||n.type!==`page`||typeof n.targetId!=`string`||(this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,networkEnabled:!1,title:n.title,url:n.url}),!this.claimOwnSession(t,n.targetId)))return;let r=this.isOwnTabSafe(n);r&&C_.debug(`Attaching to the SLICC app tab with Network off`,{targetId:n.targetId,url:n.url});try{if(await this.transport.send(`Page.enable`,{},t),!r){let e=this.sessions.get(t);e&&await this.setSessionNetwork(t,e,!0)}let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){C_.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}};function Uae(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Wae=`# /etc/llmstxtignore — llms.txt discovery suppression
|
|
885
885
|
#
|
|
886
886
|
# One advertising hostname or glob per line. Matching is case-insensitive.
|
|
@@ -974,7 +974,7 @@ Write /etc/models
|
|
|
974
974
|
`,1)[0]?.trim()===`# Per-scoop sudoers — generated from ScoopConfig (sandbox surface).`&&(await this.fs.writeFile(n,fv),ov.info(`Discarded legacy generated per-scoop sudoers (ambiguous rules, fail-closed)`,{folder:e,path:n})),await this.reloadScoopPolicy(e)}async appendScoopRule(e,t,n){let r=Si(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=yi(e),o=``;try{if(await this.fs.exists(a)){let e=await this.fs.readFile(a,{encoding:`utf-8`});o=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof or&&e.code===`ENOENT`))throw e}let s=`NOPASSWD ${i} ${r}`;if(o.split(`
|
|
975
975
|
`).some(e=>e.trim()===s))return ov.info(`Per-scoop sudoers rule already present; skipping duplicate append`,{folder:e,kind:t,pattern:r}),r;try{await this.fs.mkdir(`/scoops/${e}/etc`,{recursive:!0})}catch{}let c=o?o.endsWith(`
|
|
976
976
|
`)?o:`${o}\n`:fv;return await this.fs.writeFile(a,`${c}${s}\n`),await this.reloadScoopPolicy(e),ov.info(`Appended per-scoop sudoers rule`,{folder:e,kind:t,pattern:r}),r}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}forgetScoopPolicies(e){this.scoopConfigPolicies.delete(e),this.scoopPolicies.delete(e),this.scoopReloadChains.delete(e),this.onPolicyReload(e)}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null,this.scoopUnwatch?.(),this.scoopUnwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=yi(e);try{if(!await this.fs.exists(t)){this.scoopPolicies.delete(e),this.onPolicyReload(e);return}}catch{this.scoopPolicies.delete(e),this.onPolicyReload(e);return}this.scoopPolicies.set(e,await this.readPolicyFile(t)),this.onPolicyReload(e)}async doReload(){let e=[await this.readPolicyFile(Ei)];try{let t=(await this.fs.readDir(Ci)).filter(e=>e.type===`file`).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${Ci}/${n}`))}catch{}this.policy=vi(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return gi();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return Ti(n)}catch(t){return ov.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),gi()}}async ensureDefaults(){try{await this.fs.mkdir(Ci,{recursive:!0})}catch{}await this.seedWhenAbsent(Ei,()=>Jae),await this.seedWhenAbsent(Oi,async()=>(await import(`./approver-agent-BA3dC9Lg.js`)).DEFAULT_APPROVALS_MD)}async seedWhenAbsent(e,t){try{if(await this.fs.exists(e))return;await this.fs.writeFile(e,await t()),ov.info(`Seeded bundled policy default`,{path:e})}catch(t){ov.warn(`Failed to seed bundled policy default`,{path:e,error:t instanceof Error?t.message:String(t)})}}persistCommandGrant(e){return this.persistGrant(`Cmnd`,e)}async persistGrant(e,t){let n=Si(t);if(!n)return;let r=``;try{if(await this.fs.exists(Pi)){let e=await this.fs.readFile(Pi,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof or&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(Ci,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
|
|
977
|
-
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Pi,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,sv,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,lv,e=>{let t=new Set;for(let n of e){let e=uv(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let hv=null;function gv(e){return hv=e,()=>{hv===e&&(hv=null)}}function _v(){if(!hv)throw new zs(`session-not-found`);return hv}function vv(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function yv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bv(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)bv(e[r],`${t}/${r}`,n);return}if(yv(e))for(let[r,i]of Object.entries(e))bv(i,`${t}/${vv(r)}`,n)}function xv(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=xv(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(yv(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=xv(o,`${t}/${vv(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Sv(e,t,n){if(yv(e))return xv(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=Sv(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function Cv(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function wv(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new zs(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new zs(`redaction-unavailable`)}if(c.length!==s.length)throw new zs(`redaction-unavailable`);r.push(...c),i=o}return r}function Tv(e,t,n,r){let i=[],a=Cv(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Cv(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=be(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function Ev(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function Dv(e,t,n,r){if(r?.aborted)throw new zs(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];bv(a,``,o);let s=o.filter(e=>!ste(e.pointer)),c=[...t.entries()],l=await wv([...s.map(e=>e.value),...c.map(([,e])=>e)],n,r),u=[],d={},f=1,p=new Map,m=[];for(let e=0;e<s.length;e++){let t=s[e],n=Tv(t.value,l[e],{kind:`json`,pointer:t.pointer},f);f=n.nextId,n.finalText!==t.value&&p.set(t.pointer,n.finalText),m.push(n)}Ev(m,u,d);let h=new Map,g=s.length,_=[];for(let e=0;e<c.length;e++){let[t,n]=c[e],r=Tv(n,l[g+e],{kind:`attachment`,attachmentId:t},f);f=r.nextId,h.set(t,r.finalText),_.push(r)}Ev(_,u,d);let v=Sv(e,``,p);return{document:{...v,privacy:{...v.privacy,redactionCounts:d,redactions:u}},textAttachments:h}}function Ov(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function kv(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Av={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function jv(e,t){return Av[e]??(t===`text-redacted`?`.txt`:`.bin`)}function Mv(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${jv(t,n)}`}function Nv(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Pv(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function Fv(e,t,n,r,i){let a=Ov(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(Nv(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=Nv(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function Iv(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:Nv(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(Fv(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Lv(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function Rv(e,t,n,r,i,a,o){let s=Lv(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(Fv(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function zv(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=Rv(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Bv(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,Mv(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function Vv(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Bv(e,n),s,c;try{let e=await Dv({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof zs?e:new zs(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new zs(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new zs(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await kv(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function Hv(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=Iv(Pv(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=zv(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await Vv(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function Uv(e){return Rn(e)}function Wv(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function Gv(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:Cn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Cn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=Uv(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Kv(e,t,n={}){let r=e=>n.rootJid===void 0?e:wn(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new zs(`transfer-aborted`);let i=Wv(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new zs(`transfer-aborted`);let s=r(e.listScoops());if(i===Wv(s,e))return Gv(s,a,o,e)}}function qv(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Jv(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function Yv(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Jv(t,r++));return n}function Xv(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Jv(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Zv(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Jv(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Qv(e,t,n){let r=qv(t,n),i=Yv(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function $v(e,t,n){let r=qv(t,n),{blocks:i,excluded:a,images:o}=Xv(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function ey(e,t,n){let r=qv(t,n),{blocks:i,images:a}=Zv(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function ty(e,t,n){return e.role===`user`?Qv(e,t,n):e.role===`assistant`?$v(e,t,n):e.role===`toolResult`?ey(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function ny(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function ry(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=ty(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:ny(e),excludedReasoningBlocks:t,canonicalImages:n}}var iy=`input is invalid type`,ay=`finalize already called`,oy=typeof ArrayBuffer<`u`,sy=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(oy&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(iy)},K=`0123456789abcdef`.split(``),cy=[-2147483648,8388608,32768,128],ly=[24,16,8,0],uy=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],dy=[`hex`,`array`,`digest`,`arrayBuffer`],fy=[],py=function(e,t){return function(n){return new _y(t,!0).update(n)[e]()}},my=function(e){var t=py(`hex`,e);t.create=function(){return new _y(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<dy.length;++n){var r=dy[n];t[r]=py(r,e)}return t},hy=function(e,t){return function(n,r){return new vy(n,t,!0).update(r)[e]()}},gy=function(e){var t=hy(`hex`,e);t.create=function(t){return new vy(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<dy.length;++n){var r=dy[n];t[r]=hy(r,e)}return t};function _y(e,t){t?(fy[0]=fy[16]=fy[1]=fy[2]=fy[3]=fy[4]=fy[5]=fy[6]=fy[7]=fy[8]=fy[9]=fy[10]=fy[11]=fy[12]=fy[13]=fy[14]=fy[15]=0,this.blocks=fy):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}_y.prototype.update=function(e){if(this.finalized)throw Error(ay);var t=sy(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<ly[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<ly[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<ly[a++&3],s[a>>>2]|=(128|r>>>12&63)<<ly[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<ly[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},_y.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=cy[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},_y.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+uy[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+uy[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+uy[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+uy[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},_y.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=K[e>>>28&15]+K[e>>>24&15]+K[e>>>20&15]+K[e>>>16&15]+K[e>>>12&15]+K[e>>>8&15]+K[e>>>4&15]+K[e&15]+K[t>>>28&15]+K[t>>>24&15]+K[t>>>20&15]+K[t>>>16&15]+K[t>>>12&15]+K[t>>>8&15]+K[t>>>4&15]+K[t&15]+K[n>>>28&15]+K[n>>>24&15]+K[n>>>20&15]+K[n>>>16&15]+K[n>>>12&15]+K[n>>>8&15]+K[n>>>4&15]+K[n&15]+K[r>>>28&15]+K[r>>>24&15]+K[r>>>20&15]+K[r>>>16&15]+K[r>>>12&15]+K[r>>>8&15]+K[r>>>4&15]+K[r&15]+K[i>>>28&15]+K[i>>>24&15]+K[i>>>20&15]+K[i>>>16&15]+K[i>>>12&15]+K[i>>>8&15]+K[i>>>4&15]+K[i&15]+K[a>>>28&15]+K[a>>>24&15]+K[a>>>20&15]+K[a>>>16&15]+K[a>>>12&15]+K[a>>>8&15]+K[a>>>4&15]+K[a&15]+K[o>>>28&15]+K[o>>>24&15]+K[o>>>20&15]+K[o>>>16&15]+K[o>>>12&15]+K[o>>>8&15]+K[o>>>4&15]+K[o&15];return this.is224||(c+=K[s>>>28&15]+K[s>>>24&15]+K[s>>>20&15]+K[s>>>16&15]+K[s>>>12&15]+K[s>>>8&15]+K[s>>>4&15]+K[s&15]),c},_y.prototype.toString=_y.prototype.hex,_y.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},_y.prototype.array=_y.prototype.digest,_y.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function vy(e,t,n){var r,i=sy(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new _y(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}_y.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}vy.prototype=new _y,vy.prototype.finalize=function(){if(_y.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();_y.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),_y.prototype.finalize.call(this)}};var yy=my(),by=my(!0);yy.sha256=yy,yy.sha224=by,yy.hmac=gy(),by.hmac=gy(!0);const xy=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function Sy(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^xy[(t^e[n])&255];return~t>>>0}const Cy=new TextEncoder;function wy(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function Ty(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function Ey(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,wy(r,4,20),wy(r,6,2048),wy(r,8,0),wy(r,10,0),wy(r,12,0),Ty(r,14,n),Ty(r,18,t),Ty(r,22,t),wy(r,26,e.length),wy(r,28,0),r.set(e,30),r}function Dy(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,wy(i,4,20),wy(i,6,20),wy(i,8,2048),wy(i,10,0),wy(i,12,0),wy(i,14,0),Ty(i,16,n),Ty(i,20,t),Ty(i,24,t),wy(i,28,e.length),wy(i,30,0),wy(i,32,0),wy(i,34,0),wy(i,36,0),Ty(i,38,0),Ty(i,42,r),i.set(e,46),i}function Oy(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,wy(r,4,0),wy(r,6,0),wy(r,8,e),wy(r,10,e),Ty(r,12,t),Ty(r,16,n),wy(r,20,0),r}function ky(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function Ay(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${ye(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*jy(e,t,n,r,i){if(n?.aborted)throw i(new zs(`transfer-aborted`)),new zs(`transfer-aborted`);let a=()=>i(new zs(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=yy.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=Cy.encode(`transcript.json`),f=Sy(i),p=Ey(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new zs(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new zs(`transfer-aborted`);let t=Cy.encode(e),i=Sy(r),a=Ey(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new zs(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new zs(`transfer-aborted`);yield*d(Dy(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new zs(`transfer-aborted`);yield*d(Oy(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new zs(`transfer-aborted`)))}}function My(e,t,n){for(let e of t.keys())if(!ky(e))throw new zs(`schema-invalid`);if(t.size+1>65535)throw new zs(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new zs(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:Ay(e),chunks:jy(e,t,n,r,i),completion:a}}function Ny(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:Rs},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function Py(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function Fy(e){let t=tc(e);if(!t.ok)throw new zs(`schema-invalid`,t.error)}function Iy(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path)){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function Ly(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function Ry(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var zy=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),Fy(i.document),r?.({phase:`packaging`}),My(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Kv(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=ry(n.sources),{document:i,bundleFiles:a}=await Hv({document:Ny(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});Fy(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Kv(this.deps.collection,e),r=ry(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=Ny(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),Hv({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await Dv(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new zs(`redaction-unavailable`)}let a=Iy(r.attachments,i,e.attachments),o=await Ly(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await wee(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new zs(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new zs(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-eMNv3Qki.js`),{title:o,messages:s}=await a(this.deps.vfs,i,r.filename),c=`legacy-cone`,l=Py(s,c),u=Ry(i),d={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:Rs},session:{id:e,title:o,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...u,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:c,kind:`cone`,name:o,messages:l}],delegations:[],attachments:[]},f=new Map([[c,s]]);return n?.({phase:`redacting`}),Hv({document:d,chatMessagesByConversation:f,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new zs(`attachment-unreadable`);return t}};const By=`/sessions/data`,Vy=`document.json`;async function Hy(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Uy(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new zs(`session-not-found`)}function Wy(e){return`${By}/${e}`}function Gy(e){return`${By}/.tmp-${e}`}async function Ky(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function qy(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await qy(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Jy(e,t,n){await Ky(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Jy(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function Yy(e,t,n){Uy(t);let r=Gy(t),i=Wy(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new zs(`schema-invalid`);await qy(e,i),await Ky(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await Hy(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${Vy}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await Ky(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Jy(e,r,i),await e.flush()}catch(t){throw await qy(e,r),t}await qy(e,r)}async function Xy(e,t){Uy(t);let n=Wy(t),r=`${n}/${Vy}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new zs(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new zs(`schema-invalid`)}if(!tc(a).ok)throw new zs(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new zs(`transfer-corrupt`)}if(await Hy(i)!==t.sha256)throw new zs(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Zy(e){return`error`in e}function Qy(){throw new zs(`redaction-unavailable`)}function $y(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Qy(),e.texts}function eb(){return{async redact(e){let t;try{t=await fetch(we(`/api/secrets/redact-export`),{method:`POST`,headers:P({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Qy()}t.ok||Qy();let n;try{n=await t.json()}catch{Qy()}return $y(n,e.length)}}}function tb(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Qy()}return typeof t==`object`&&t&&Zy(t)&&Qy(),$y(t,e.length)}}}function nb(){return{async redact(e){let t;try{t=await fn(`secrets.redact-export`,{texts:e})}catch{Qy()}return t??Qy(),typeof t==`object`&&t&&Zy(t)&&Qy(),$y(t,e.length)}}}function rb(){return{async redact(e){Qy()}}}function ib(){let e=qt();return e===`connect`?rb():e===`extension-direct`?tb():e===`extension-delegate`?nb():eb()}const ab=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function ob(e){return`e${e}`}function sb(e){let t=[];for(let n of e){let e=ub(n),r=fb(n);if(e===`assistant`){let e=t.length,i=ob(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:hb(n),message:n,model:mb(n)});for(let e of gb(n)){let n=t.length;t.push({id:ob(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:ob(i),seq:i,kind:`tool-result`,timestamp:r,text:hb(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=hb(n),a=e===`user`?lb(i):null,o=t.length,s=ob(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):ab.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function cb(e){let t=[];for(let n of e){let e=t.length,r=ob(e),i=pb(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:ob(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&vee(n.channel)?n.channel:lb(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):ab.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function lb(e){for(let t of fee(e)){let e=(t.sender?mee(t.sender):null)??gee(t.body);if(e)return e}return null}function ub(e){return e.role??``}function db(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function fb(e){return db(e.timestamp)}function pb(e){return db(e.timestamp)}function mb(e){let t=e.model;return typeof t==`string`?t:void 0}function hb(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function gb(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}const _b=r(`work-unit-conversation`),vb=`conversations`;async function yb(e){let t=e.now??(()=>Date.now()),n=await xb(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys);for(let a of e.units){let o={...a,parentJid:a.parentJid??null},s=Tr(o);if(i.has(s)){r.alreadyDone++;continue}try{let n=await bb(e,o,s,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(e){let t=e instanceof Error?e.message:String(e);r.skipped++,n.skipped.push({key:s,reason:t}),_b.warn(`Skipping a unit whose legacy conversation could not be read`,{key:s,folder:o.folder,error:t})}i.add(s),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${o.jid}`)}return n.done=!0,n.updatedAt=t(),await e.store.putMigrationState(n),_b.info(`Canonical conversation migration complete`,{...r}),r}async function bb(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return _b.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw Error(`canonical record unreadable: ${i.reason}`);let a={key:n,workUnitId:t.jid,workspaceId:wr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Rn(t)}},o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:1,origin:`agent-history`,entries:sb(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:1,origin:`ui-projection`,entries:cb(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function xb(e,t){let n=await e.getMigrationState(vb);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:vb,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}const Sb=r(`work-unit-conversation`),Cb=`conversations`,wb=`migrations`;var Tb=class{dbPromise=null;dbName;writeChains=new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await Ab((await this.getDb()).transaction(Cb,`readonly`).objectStore(Cb).get(e));return t?Eee(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(Sb.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(Sb.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return Sb.warn(`Conversation record read failed`,{key:e,error:Mb(t)}),{status:`error`,reason:Mb(t)}}}async save(e){let t=(await this.getDb()).transaction(Cb,`readwrite`);t.objectStore(Cb).put(e),await jb(t)}async delete(e){try{let t=(await this.getDb()).transaction(Cb,`readwrite`);t.objectStore(Cb).delete(e),await jb(t)}catch(t){Sb.warn(`Conversation record delete failed`,{key:e,error:Mb(t)})}}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){Sb.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){Sb.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:Mb(n)})}}async listKeys(){try{return(await Ab((await this.getDb()).transaction(Cb,`readonly`).objectStore(Cb).getAllKeys())).map(String)}catch(e){return Sb.warn(`Conversation key listing failed`,{error:Mb(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=sb(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=Eb(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?(await this.save(o),o):a}catch(t){return Sb.warn(`Conversation record write failed`,{key:e.key,error:Mb(t)}),null}}async putMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async deleteMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t){return this.serialize(e,()=>this.mutateRecord(e,t))}async mutateRecord(e,t){try{let n=await this.read(e);if(n.status!==`ok`)return!1;let r=t(n.record);return r?(await this.save({...r,updatedAt:Date.now()}),!0):!1}catch(t){return Sb.warn(`Conversation marker write failed`,{key:e,error:Mb(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await Ab((await this.getDb()).transaction(wb,`readonly`).objectStore(wb).get(e))??null}catch(t){return Sb.warn(`Migration state read failed`,{id:e,error:Mb(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(wb,`readwrite`);t.objectStore(wb).put(e),await jb(t)}catch(t){Sb.warn(`Migration state write failed`,{id:e.id,error:Mb(t)})}}async clearAll(){let e=(await this.getDb()).transaction([Cb,wb],`readwrite`);e.objectStore(Cb).clear(),e.objectStore(wb).clear(),await jb(e)}getDb(){return this.dbPromise||(this.dbPromise=kb(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function Eb(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:1,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&Db(a,t))return null;let o=t.length>a.length&&Db(a,t);return{...e,version:1,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function Db(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!Ob(e[n],t[n]))return!1;return!0}function Ob(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function kb(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(Cb)||e.createObjectStore(Cb,{keyPath:`key`}),e.objectStoreNames.contains(wb)||e.createObjectStore(wb,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function Ab(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function jb(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function Mb(e){return e instanceof Error?e.message:String(e)}const Nb=`focus`,Pb={type:`leaf`,surfaceId:`chat`};function Fb(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}const Ib={focus:{name:`focus`,tree:Fb({left:Pb},{left:3,middle:1})}};function Lb(e){return Ib[e]??null}const Rb=r(`skills`),zb=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-CWMPcWVI.js`).then(e=>e.default),"/packages/vfs-root/shared/DREAMING.md":()=>import(`./DREAMING-DKcamfu0.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CDj3aVTD.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-1jIGxLn4.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-CFQTt8oo.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-BXSAhY0E.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-C947OHCv.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/gelatiere/SKILL.md":()=>import(`./SKILL-DvHAkJSI.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-CuHGVKei.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/memory/SKILL.md":()=>import(`./SKILL-C9vwCrkC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-BPuaCaUr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DC91lupP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL--NWTI0kb.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-6coWmZ2q.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/slicc/SKILL.md":()=>import(`./SKILL-CRLGKQWi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-zHRhO4F3.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-DKvWxDlM.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-BflWplWz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-Dh6a4Qu2.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-DJtLE66_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-cqUV8C7U.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-CtxHowg1.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-Cc0Ep86w.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/SKILL.md":()=>import(`./SKILL-UcxSfshP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/wiki.jsh":()=>import(`./wiki-DA0qKUVC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/workflows/SKILL.md":()=>import(`./SKILL-Bt-RhG0L.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/SKILL.md":()=>import(`./SKILL-CED8RXQP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/x_search.jsh":()=>import(`./x_search-C-5p00-C.js`).then(e=>e.default)}),Bb=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function Vb(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Hb={};function Ub(){let e={};for(let[t,n]of Object.entries(zb))e[t]=n;for(let[t,n]of Object.entries(Bb))e[t]=async()=>Vb(await n());for(let[t,n]of Object.entries(Hb)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function Wb(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){Rb.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function Gb(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
977
|
+
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(Pi,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,sv,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,lv,e=>{let t=new Set;for(let n of e){let e=uv(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let hv=null;function gv(e){return hv=e,()=>{hv===e&&(hv=null)}}function _v(){if(!hv)throw new zs(`session-not-found`);return hv}function vv(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function yv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bv(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)bv(e[r],`${t}/${r}`,n);return}if(yv(e))for(let[r,i]of Object.entries(e))bv(i,`${t}/${vv(r)}`,n)}function xv(e,t,n){if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=xv(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}if(yv(e)){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=xv(o,`${t}/${vv(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}return e}function Sv(e,t,n){if(yv(e))return xv(e,t,n);if(typeof e==`string`)return n.get(t)??e;if(Array.isArray(e)){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=Sv(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}return e}function Cv(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function wv(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new zs(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new zs(`redaction-unavailable`)}if(c.length!==s.length)throw new zs(`redaction-unavailable`);r.push(...c),i=o}return r}function Tv(e,t,n,r){let i=[],a=Cv(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Cv(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=be(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function Ev(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function Dv(e,t,n,r){if(r?.aborted)throw new zs(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];bv(a,``,o);let s=o.filter(e=>!ste(e.pointer)),c=[...t.entries()],l=await wv([...s.map(e=>e.value),...c.map(([,e])=>e)],n,r),u=[],d={},f=1,p=new Map,m=[];for(let e=0;e<s.length;e++){let t=s[e],n=Tv(t.value,l[e],{kind:`json`,pointer:t.pointer},f);f=n.nextId,n.finalText!==t.value&&p.set(t.pointer,n.finalText),m.push(n)}Ev(m,u,d);let h=new Map,g=s.length,_=[];for(let e=0;e<c.length;e++){let[t,n]=c[e],r=Tv(n,l[g+e],{kind:`attachment`,attachmentId:t},f);f=r.nextId,h.set(t,r.finalText),_.push(r)}Ev(_,u,d);let v=Sv(e,``,p);return{document:{...v,privacy:{...v.privacy,redactionCounts:d,redactions:u}},textAttachments:h}}function Ov(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function kv(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const Av={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function jv(e,t){return Av[e]??(t===`text-redacted`?`.txt`:`.bin`)}function Mv(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${jv(t,n)}`}function Nv(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function Pv(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function Fv(e,t,n,r,i){let a=Ov(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(Nv(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=Nv(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function Iv(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:Nv(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(Fv(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function Lv(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function Rv(e,t,n,r,i,a,o){let s=Lv(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(Fv(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function zv(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=Rv(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function Bv(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,Mv(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function Vv(e,t,n,r,i){let{rawAttachments:a,textMap:o}=Bv(e,n),s,c;try{let e=await Dv({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof zs?e:new zs(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new zs(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new zs(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await kv(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function Hv(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=Iv(Pv(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=zv(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await Vv(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function Uv(e){return Rn(e)}function Wv(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function Gv(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:Cn(t)?`cone`:`scoop`,name:t.name,...t.folder&&!Cn(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=Uv(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function Kv(e,t,n={}){let r=e=>n.rootJid===void 0?e:wn(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new zs(`transfer-aborted`);let i=Wv(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new zs(`transfer-aborted`);let s=r(e.listScoops());if(i===Wv(s,e))return Gv(s,a,o,e)}}function qv(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Jv(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function Yv(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Jv(t,r++));return n}function Xv(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Jv(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Zv(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Jv(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Qv(e,t,n){let r=qv(t,n),i=Yv(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function $v(e,t,n){let r=qv(t,n),{blocks:i,excluded:a,images:o}=Xv(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function ey(e,t,n){let r=qv(t,n),{blocks:i,images:a}=Zv(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function ty(e,t,n){return e.role===`user`?Qv(e,t,n):e.role===`assistant`?$v(e,t,n):e.role===`toolResult`?ey(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function ny(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function ry(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=ty(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:ny(e),excludedReasoningBlocks:t,canonicalImages:n}}var iy=`input is invalid type`,ay=`finalize already called`,oy=typeof ArrayBuffer<`u`,sy=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(oy&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(iy)},K=`0123456789abcdef`.split(``),cy=[-2147483648,8388608,32768,128],ly=[24,16,8,0],uy=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],dy=[`hex`,`array`,`digest`,`arrayBuffer`],fy=[],py=function(e,t){return function(n){return new _y(t,!0).update(n)[e]()}},my=function(e){var t=py(`hex`,e);t.create=function(){return new _y(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<dy.length;++n){var r=dy[n];t[r]=py(r,e)}return t},hy=function(e,t){return function(n,r){return new vy(n,t,!0).update(r)[e]()}},gy=function(e){var t=hy(`hex`,e);t.create=function(t){return new vy(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<dy.length;++n){var r=dy[n];t[r]=hy(r,e)}return t};function _y(e,t){t?(fy[0]=fy[16]=fy[1]=fy[2]=fy[3]=fy[4]=fy[5]=fy[6]=fy[7]=fy[8]=fy[9]=fy[10]=fy[11]=fy[12]=fy[13]=fy[14]=fy[15]=0,this.blocks=fy):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}_y.prototype.update=function(e){if(this.finalized)throw Error(ay);var t=sy(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<ly[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<ly[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<ly[a++&3],s[a>>>2]|=(128|r>>>12&63)<<ly[a++&3],s[a>>>2]|=(128|r>>>6&63)<<ly[a++&3],s[a>>>2]|=(128|r&63)<<ly[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<ly[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},_y.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=cy[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},_y.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+uy[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+uy[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+uy[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+uy[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},_y.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=K[e>>>28&15]+K[e>>>24&15]+K[e>>>20&15]+K[e>>>16&15]+K[e>>>12&15]+K[e>>>8&15]+K[e>>>4&15]+K[e&15]+K[t>>>28&15]+K[t>>>24&15]+K[t>>>20&15]+K[t>>>16&15]+K[t>>>12&15]+K[t>>>8&15]+K[t>>>4&15]+K[t&15]+K[n>>>28&15]+K[n>>>24&15]+K[n>>>20&15]+K[n>>>16&15]+K[n>>>12&15]+K[n>>>8&15]+K[n>>>4&15]+K[n&15]+K[r>>>28&15]+K[r>>>24&15]+K[r>>>20&15]+K[r>>>16&15]+K[r>>>12&15]+K[r>>>8&15]+K[r>>>4&15]+K[r&15]+K[i>>>28&15]+K[i>>>24&15]+K[i>>>20&15]+K[i>>>16&15]+K[i>>>12&15]+K[i>>>8&15]+K[i>>>4&15]+K[i&15]+K[a>>>28&15]+K[a>>>24&15]+K[a>>>20&15]+K[a>>>16&15]+K[a>>>12&15]+K[a>>>8&15]+K[a>>>4&15]+K[a&15]+K[o>>>28&15]+K[o>>>24&15]+K[o>>>20&15]+K[o>>>16&15]+K[o>>>12&15]+K[o>>>8&15]+K[o>>>4&15]+K[o&15];return this.is224||(c+=K[s>>>28&15]+K[s>>>24&15]+K[s>>>20&15]+K[s>>>16&15]+K[s>>>12&15]+K[s>>>8&15]+K[s>>>4&15]+K[s&15]),c},_y.prototype.toString=_y.prototype.hex,_y.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},_y.prototype.array=_y.prototype.digest,_y.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function vy(e,t,n){var r,i=sy(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new _y(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}_y.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}vy.prototype=new _y,vy.prototype.finalize=function(){if(_y.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();_y.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),_y.prototype.finalize.call(this)}};var yy=my(),by=my(!0);yy.sha256=yy,yy.sha224=by,yy.hmac=gy(),by.hmac=gy(!0);const xy=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function Sy(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^xy[(t^e[n])&255];return~t>>>0}const Cy=new TextEncoder;function wy(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function Ty(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function Ey(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,wy(r,4,20),wy(r,6,2048),wy(r,8,0),wy(r,10,0),wy(r,12,0),Ty(r,14,n),Ty(r,18,t),Ty(r,22,t),wy(r,26,e.length),wy(r,28,0),r.set(e,30),r}function Dy(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,wy(i,4,20),wy(i,6,20),wy(i,8,2048),wy(i,10,0),wy(i,12,0),wy(i,14,0),Ty(i,16,n),Ty(i,20,t),Ty(i,24,t),wy(i,28,e.length),wy(i,30,0),wy(i,32,0),wy(i,34,0),wy(i,36,0),Ty(i,38,0),Ty(i,42,r),i.set(e,46),i}function Oy(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,wy(r,4,0),wy(r,6,0),wy(r,8,e),wy(r,10,e),Ty(r,12,t),Ty(r,16,n),wy(r,20,0),r}function ky(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function Ay(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${ye(e.session.title,{maxLen:40,fallback:`transcript`})}-${n}.zip`}async function*jy(e,t,n,r,i){if(n?.aborted)throw i(new zs(`transfer-aborted`)),new zs(`transfer-aborted`);let a=()=>i(new zs(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=yy.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=Cy.encode(`transcript.json`),f=Sy(i),p=Ey(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new zs(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new zs(`transfer-aborted`);let t=Cy.encode(e),i=Sy(r),a=Ey(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new zs(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new zs(`transfer-aborted`);yield*d(Dy(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new zs(`transfer-aborted`);yield*d(Oy(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new zs(`transfer-aborted`)))}}function My(e,t,n){for(let e of t.keys())if(!ky(e))throw new zs(`schema-invalid`);if(t.size+1>65535)throw new zs(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new zs(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:Ay(e),chunks:jy(e,t,n,r,i),completion:a}}function Ny(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:Rs},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function Py(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function Fy(e){let t=tc(e);if(!t.ok)throw new zs(`schema-invalid`,t.error)}function Iy(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path)){if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}}return r}async function Ly(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function Ry(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var zy=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),Fy(i.document),r?.({phase:`packaging`}),My(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await Kv(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=ry(n.sources),{document:i,bundleFiles:a}=await Hv({document:Ny(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});Fy(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await Kv(this.deps.collection,e),r=ry(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=Ny(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),Hv({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await Dv(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new zs(`redaction-unavailable`)}let a=Iy(r.attachments,i,e.attachments),o=await Ly(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await wee(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new zs(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new zs(`session-not-found`)}let{loadFrozenArchive:a}=await import(`./session-jsonl-eMNv3Qki.js`),{title:o,messages:s}=await a(this.deps.vfs,i,r.filename),c=`legacy-cone`,l=Py(s,c),u=Ry(i),d={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:Rs},session:{id:e,title:o,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...u,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:c,kind:`cone`,name:o,messages:l}],delegations:[],attachments:[]},f=new Map([[c,s]]);return n?.({phase:`redacting`}),Hv({document:d,chatMessagesByConversation:f,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new zs(`attachment-unreadable`);return t}};const By=`/sessions/data`,Vy=`document.json`;async function Hy(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Uy(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new zs(`session-not-found`)}function Wy(e){return`${By}/${e}`}function Gy(e){return`${By}/.tmp-${e}`}async function Ky(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function qy(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await qy(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Jy(e,t,n){await Ky(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Jy(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function Yy(e,t,n){Uy(t);let r=Gy(t),i=Wy(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new zs(`schema-invalid`);await qy(e,i),await Ky(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await Hy(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${Vy}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await Ky(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Jy(e,r,i),await e.flush()}catch(t){throw await qy(e,r),t}await qy(e,r)}async function Xy(e,t){Uy(t);let n=Wy(t),r=`${n}/${Vy}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new zs(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new zs(`schema-invalid`)}if(!tc(a).ok)throw new zs(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new zs(`transfer-corrupt`)}if(await Hy(i)!==t.sha256)throw new zs(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Zy(e){return`error`in e}function Qy(){throw new zs(`redaction-unavailable`)}function $y(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Qy(),e.texts}function eb(){return{async redact(e){let t;try{t=await fetch(we(`/api/secrets/redact-export`),{method:`POST`,headers:P({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Qy()}t.ok||Qy();let n;try{n=await t.json()}catch{Qy()}return $y(n,e.length)}}}function tb(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Qy()}return typeof t==`object`&&t&&Zy(t)&&Qy(),$y(t,e.length)}}}function nb(){return{async redact(e){let t;try{t=await fn(`secrets.redact-export`,{texts:e})}catch{Qy()}return t??Qy(),typeof t==`object`&&t&&Zy(t)&&Qy(),$y(t,e.length)}}}function rb(){return{async redact(e){Qy()}}}function ib(){let e=qt();return e===`connect`?rb():e===`extension-direct`?tb():e===`extension-delegate`?nb():eb()}const ab=new Set([`scoop-notify`,`scoop-idle`,`scoop-wait`]);function ob(e){return`e${e}`}function sb(e){let t=[];for(let n of e){let e=ub(n),r=fb(n);if(e===`assistant`){let e=t.length,i=ob(e);t.push({id:i,seq:e,kind:`assistant`,timestamp:r,text:hb(n),message:n,model:mb(n)});for(let e of gb(n)){let n=t.length;t.push({id:ob(n),seq:n,kind:`tool-call`,timestamp:r,toolCallId:e.id,name:e.name,assistantEntryId:i})}continue}if(e===`toolResult`){let e=n,i=t.length;t.push({id:ob(i),seq:i,kind:`tool-result`,timestamp:r,text:hb(n),message:n,toolCallId:e.toolCallId??``,isError:e.isError});continue}let i=hb(n),a=e===`user`?lb(i):null,o=t.length,s=ob(o);a===null?t.push({id:s,seq:o,kind:`user`,timestamp:r,text:i,message:n}):ab.has(a)?t.push({id:s,seq:o,kind:`child-result`,timestamp:r,text:i,message:n,channel:a}):t.push({id:s,seq:o,kind:`external-event`,timestamp:r,text:i,message:n,channel:a})}return t}function cb(e){let t=[];for(let n of e){let e=t.length,r=ob(e),i=pb(n),a=typeof n.content==`string`?n.content:``;if(n.role===`assistant`){t.push({id:r,seq:e,kind:`assistant`,timestamp:i,text:a,chat:n,model:n.model});for(let e of n.toolCalls??[]){let n=t.length;t.push({id:ob(n),seq:n,kind:`tool-call`,timestamp:i,toolCallId:e.id,name:e.name,assistantEntryId:r})}continue}let o=n.source===`lick`&&n.channel&&vee(n.channel)?n.channel:lb(a);o===null?t.push({id:r,seq:e,kind:`user`,timestamp:i,text:a,chat:n}):ab.has(o)?t.push({id:r,seq:e,kind:`child-result`,timestamp:i,text:a,chat:n,channel:o}):t.push({id:r,seq:e,kind:`external-event`,timestamp:i,text:a,chat:n,channel:o})}return t}function lb(e){for(let t of fee(e)){let e=(t.sender?mee(t.sender):null)??gee(t.body);if(e)return e}return null}function ub(e){return e.role??``}function db(e){if(typeof e==`number`)return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isNaN(t)?0:t}return e instanceof Date?e.getTime():0}function fb(e){return db(e.timestamp)}function pb(e){return db(e.timestamp)}function mb(e){let t=e.model;return typeof t==`string`?t:void 0}function hb(e){let t=e.content;if(typeof t==`string`)return t;if(!Array.isArray(t))return``;let n=[];for(let e of t)e?.type===`text`&&n.push(e.text);return n.join(``)}function gb(e){let t=e.content;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(e?.type!==`toolCall`)continue;let t=e;n.push({id:t.id??``,name:t.name??``})}return n}const _b=r(`work-unit-conversation`),vb=`conversations`;async function yb(e){let t=e.now??(()=>Date.now()),n=await xb(e.store,t()),r={migrated:0,alreadyDone:0,empty:0,skipped:0};if(n.done)return r.alreadyDone=e.units.length,r;let i=new Set(n.completedKeys);for(let a of e.units){let o={...a,parentJid:a.parentJid??null},s=Tr(o);if(i.has(s)){r.alreadyDone++;continue}try{let n=await bb(e,o,s,t());n===`migrated`?r.migrated++:n===`already`?r.alreadyDone++:r.empty++}catch(e){let t=e instanceof Error?e.message:String(e);r.skipped++,n.skipped.push({key:s,reason:t}),_b.warn(`Skipping a unit whose legacy conversation could not be read`,{key:s,folder:o.folder,error:t})}i.add(s),n.completedKeys=[...i],n.updatedAt=t(),await e.store.putMigrationState(n),e.onProgress?.(`conversation-migrated:${o.jid}`)}return n.done=!0,n.updatedAt=t(),await e.store.putMigrationState(n),_b.info(`Canonical conversation migration complete`,{...r}),r}async function bb(e,t,n,r){let i=await e.store.read(n);if(i.status===`ok`)return`already`;if(i.status===`incompatible`)return _b.info(`Leaving a newer-schema conversation record untouched`,{key:n,version:i.version}),`already`;if(i.status===`error`)throw Error(`canonical record unreadable: ${i.reason}`);let a={key:n,workUnitId:t.jid,workspaceId:wr(t),folder:t.folder,legacyKeys:{agentSessionId:t.jid,chatSessionId:Rn(t)}},o=await e.loadAgentSession(t.jid);if(o&&!Array.isArray(o.messages))throw Error(`agent-sessions record has no message list`);if(o&&o.messages.length>0){let t={...a,version:1,origin:`agent-history`,entries:sb(o.messages),createdAt:o.createdAt??r,updatedAt:r,migratedFrom:`agent-sessions`};return await e.store.save(t),`migrated`}let s=await e.loadChatSession(a.legacyKeys.chatSessionId);if(s&&!Array.isArray(s.messages))throw Error(`browser-coding-agent record has no message list`);if(s&&s.messages.length>0){let t={...a,version:1,origin:`ui-projection`,entries:cb(s.messages),createdAt:s.createdAt??r,updatedAt:r,migratedFrom:`browser-coding-agent`};return await e.store.save(t),`migrated`}return`empty`}async function xb(e,t){let n=await e.getMigrationState(vb);return n&&n.version===1?{...n,completedKeys:Array.isArray(n.completedKeys)?n.completedKeys:[],skipped:Array.isArray(n.skipped)?n.skipped:[]}:{id:vb,version:1,completedKeys:[],skipped:[],done:!1,startedAt:t,updatedAt:t}}const Sb=r(`work-unit-conversation`),Cb=`conversations`,wb=`migrations`;var Tb=class{dbPromise=null;dbName;writeChains=new Map;constructor(e={}){this.dbName=e.dbName??`slicc-work-units`}async load(e){let t=await this.read(e);return t.status===`ok`?t.record:null}async read(e){try{let t=await Ab((await this.getDb()).transaction(Cb,`readonly`).objectStore(Cb).get(e));return t?Eee(t)?Array.isArray(t.entries)?{status:`ok`,record:t}:(Sb.warn(`Conversation record has no entry list`,{key:e}),{status:`malformed`,reason:`entries is not a list`}):(Sb.warn(`Ignoring conversation record from a newer schema`,{key:e,version:t.version}),{status:`incompatible`,version:t.version}):{status:`absent`}}catch(t){return Sb.warn(`Conversation record read failed`,{key:e,error:Mb(t)}),{status:`error`,reason:Mb(t)}}}async save(e){let t=(await this.getDb()).transaction(Cb,`readwrite`);t.objectStore(Cb).put(e),await jb(t)}async delete(e){try{let t=(await this.getDb()).transaction(Cb,`readwrite`);t.objectStore(Cb).delete(e),await jb(t)}catch(t){Sb.warn(`Conversation record delete failed`,{key:e,error:Mb(t)})}}async rekey(e,t){if(e!==t.key)try{let n=await this.read(e);if(n.status!==`ok`)return;let r=await this.read(t.key);if(r.status===`incompatible`||r.status===`error`){Sb.warn(`Conversation rekey refused: target is not writable`,{fromKey:e,toKey:t.key,status:r.status});return}let i=Date.now();await this.save({...n.record,key:t.key,workUnitId:t.workUnitId,workspaceId:t.workspaceId,folder:t.folder,legacyKeys:t.legacyKeys,updatedAt:i}),await this.delete(e)}catch(n){Sb.warn(`Conversation rekey failed`,{fromKey:e,toKey:t.key,error:Mb(n)})}}async listKeys(){try{return(await Ab((await this.getDb()).transaction(Cb,`readonly`).objectStore(Cb).getAllKeys())).map(String)}catch(e){return Sb.warn(`Conversation key listing failed`,{error:Mb(e)}),[]}}async syncAgentMessages(e,t,n={}){let r=n.now??Date.now(),i=sb(t);return this.serialize(e.key,()=>this.ingestEntries(e,i,n,r))}async ingestEntries(e,t,n,r){try{let i=await this.read(e.key);if(i.status===`incompatible`||i.status===`error`)return null;let a=i.status===`ok`?i.record:null,o=Eb(a,t,e,`agent-history`,{createdAt:n.createdAt??r,now:r});return o?(await this.save(o),o):a}catch(t){return Sb.warn(`Conversation record write failed`,{key:e.key,error:Mb(t)}),null}}async putMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t.id);return n.push(t),n.sort((e,t)=>e.timestamp-t.timestamp),{...e,markers:n.slice(-64)}})}async deleteMarker(e,t){return this.withRecord(e,e=>{let n=(e.markers??[]).filter(e=>e.id!==t);return n.length===(e.markers?.length??0)?null:{...e,markers:n}})}withRecord(e,t){return this.serialize(e,()=>this.mutateRecord(e,t))}async mutateRecord(e,t){try{let n=await this.read(e);if(n.status!==`ok`)return!1;let r=t(n.record);return r?(await this.save({...r,updatedAt:Date.now()}),!0):!1}catch(t){return Sb.warn(`Conversation marker write failed`,{key:e,error:Mb(t)}),!1}}serialize(e,t){let n=(this.writeChains.get(e)??Promise.resolve()).then(t,t),r=n.then(()=>void 0,()=>void 0);return this.writeChains.set(e,r),r.then(()=>{this.writeChains.get(e)===r&&this.writeChains.delete(e)}),n}async getMigrationState(e){try{return await Ab((await this.getDb()).transaction(wb,`readonly`).objectStore(wb).get(e))??null}catch(t){return Sb.warn(`Migration state read failed`,{id:e,error:Mb(t)}),null}}async putMigrationState(e){try{let t=(await this.getDb()).transaction(wb,`readwrite`);t.objectStore(wb).put(e),await jb(t)}catch(t){Sb.warn(`Migration state write failed`,{id:e.id,error:Mb(t)})}}async clearAll(){let e=(await this.getDb()).transaction([Cb,wb],`readwrite`);e.objectStore(Cb).clear(),e.objectStore(wb).clear(),await jb(e)}getDb(){return this.dbPromise||(this.dbPromise=kb(this.dbName).then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}};function Eb(e,t,n,r,i){if(!e)return t.length===0?null:{key:n.key,version:1,workUnitId:n.workUnitId,workspaceId:n.workspaceId,folder:n.folder,origin:r,entries:t,createdAt:i.createdAt,updatedAt:i.now,legacyKeys:n.legacyKeys};let a=e.entries;if(t.length===a.length&&Db(a,t))return null;let o=t.length>a.length&&Db(a,t);return{...e,version:1,origin:r,entries:t,updatedAt:i.now,rewrites:o?e.rewrites:(e.rewrites??0)+1,legacyKeys:n.legacyKeys}}function Db(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(!Ob(e[n],t[n]))return!1;return!0}function Ob(e,t){return e.kind!==t.kind||e.seq!==t.seq?!1:e.kind===`tool-call`&&t.kind===`tool-call`?e.toolCallId===t.toolCallId&&e.name===t.name:(`text`in e?e.text:``)===(`text`in t?t.text:``)}function kb(e){return new Promise((t,n)=>{let r=indexedDB.open(e,1);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(Cb)||e.createObjectStore(Cb,{keyPath:`key`}),e.objectStoreNames.contains(wb)||e.createObjectStore(wb,{keyPath:`id`})},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}function Ab(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error)})}function jb(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error),e.onabort=()=>n(e.error)})}function Mb(e){return e instanceof Error?e.message:String(e)}const Nb=`focus`,Pb={type:`leaf`,surfaceId:`chat`};function Fb(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}const Ib={focus:{name:`focus`,tree:Fb({left:Pb},{left:3,middle:1})}};function Lb(e){return Ib[e]??null}const Rb=r(`skills`),zb=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-DT25ppH5.js`).then(e=>e.default),"/packages/vfs-root/etc/APPROVALS.md":()=>import(`./APPROVALS-CoZKeFYV.js`).then(e=>e.default),"/packages/vfs-root/etc/slicc/keys.json":()=>import(`./keys-BMebW-sj.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-CWMPcWVI.js`).then(e=>e.default),"/packages/vfs-root/shared/DREAMING.md":()=>import(`./DREAMING-DKcamfu0.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/GELATIERE.md":()=>import(`./GELATIERE-CDj3aVTD.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-1jIGxLn4.js`).then(e=>e.n).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/suggestions/suggestions.shtml":()=>import(`./suggestions-CFQTt8oo.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-BzW33ZtP.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/WIKI.md":()=>import(`./WIKI-DoBxwf2u.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/index.md":()=>import(`./wiki-BXN4hgmw.js`).then(e=>e.default),"/packages/vfs-root/shared/wiki/log.md":()=>import(`./log-DEDI5t_h.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-BXSAhY0E.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BNnF2azP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-BTVvFyRd.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-C947OHCv.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-BmzmDv0e.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ffmpeg/SKILL.md":()=>import(`./SKILL-C6co9TnL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/gelatiere/SKILL.md":()=>import(`./SKILL-DvHAkJSI.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-CuHGVKei.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-DpjPj8Lx.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/memory/SKILL.md":()=>import(`./SKILL-C9vwCrkC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-BPuaCaUr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-BS0BC3cr.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DC91lupP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL--NWTI0kb.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-6coWmZ2q.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/slicc/SKILL.md":()=>import(`./SKILL-CRLGKQWi.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-B0M2f1rt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-DKvWxDlM.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-BflWplWz.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-Dh6a4Qu2.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-DJtLE66_.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-cqUV8C7U.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-CtxHowg1.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-Cc0Ep86w.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/SKILL.md":()=>import(`./SKILL-UcxSfshP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/wiki/wiki.jsh":()=>import(`./wiki-DA0qKUVC.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/workflows/SKILL.md":()=>import(`./SKILL-Bt-RhG0L.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/SKILL.md":()=>import(`./SKILL-CED8RXQP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/x_search.jsh":()=>import(`./x_search-C-5p00-C.js`).then(e=>e.default)}),Bb=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function Vb(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Hb={};function Ub(){let e={};for(let[t,n]of Object.entries(zb))e[t]=n;for(let[t,n]of Object.entries(Bb))e[t]=async()=>Vb(await n());for(let[t,n]of Object.entries(Hb)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function Wb(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){Rb.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function Gb(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
978
978
|
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break;case`layout`:i.layout=a;break;case`theme`:i.theme=a}}return{metadata:i,body:r}}async function Kb(e,t){let n=await qb(e,t),r=await Jb(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Wb([...i,...r,...a]);return Rb.info(`Skills loaded`,{count:o.length,dir:t}),o}async function qb(e,t){let n=await Mi(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=Gb(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),Rb.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{Rb.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function Jb(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=Gb(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),Rb.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{Rb.debug(`Standalone skills directory not found`,{dir:t})}return n}function Yb(e){return e.length===0?``:`
|
|
979
979
|
---
|
|
980
980
|
AVAILABLE SKILLS
|
|
@@ -1629,7 +1629,7 @@ except BaseException:
|
|
|
1629
1629
|
`)?a:`${a}\n`;t(n>0?`${` `.repeat(n)}${o}`:o)}function RV(e,t,n){let r=MV(n);if(e.has(r)){t(`Label '${r}' already exists for console.time()`);return}e.set(r,NV())}function zV(e,t,n,r){let i=MV(r),a=e.get(i);if(a===void 0){t(`No such label '${i}' for console.timeEnd()`);return}e.delete(i),n(`${i}: ${PV(NV()-a)}`)}function BV(e,t,n,r,i){let a=MV(r),o=e.get(a);if(o===void 0){t(`No such label '${a}' for console.timeLog()`);return}let s=`${a}: ${PV(NV()-o)}`;i.length===0?n(s):n(s,...i)}function VV(e,t,n){let r=MV(n),i=(e.get(r)??0)+1;e.set(r,i),t(`${r}: ${i}`)}function HV(e,t,n){let r=MV(n);if(!e.has(r)){t(`Count for '${r}' does not exist`);return}e.set(r,0)}function UV(e,t,n){n.length>0&&t(...n),e.depth+=1}function WV(e){e.depth>0&&--e.depth}function GV(e,t){let n=new Map,r=new Map,i={depth:0},a=(...t)=>FV(e,i.depth,t),o=(...e)=>FV(t,i.depth,e),s=(...e)=>UV(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:()=>WV(i),assert:(e,...t)=>IV(o,e,t),trace:(...e)=>LV(o,t,i.depth,e),time:e=>RV(r,o,e),timeEnd:e=>zV(r,o,a,e),timeLog:(e,...t)=>BV(r,o,a,e,t),count:e=>VV(n,a,e),countReset:e=>HV(n,o,e)}}function KV(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=JV(e.stdin??``,o),c=SV(e.argv),l={write:t,end:()=>void 0,isTTY:!r},u={write:n,end:()=>void 0,isTTY:!r};return{processShim:{argv:c,env:e.env,versions:{node:ba},version:`v${ba}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new kV(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var qV=class extends SI.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 kV){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 JV(e,t){return new qV(e,t)}function YV(e){if(e===``)return[];let t=e.split(`
|
|
1630
1630
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function XV(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function ZV(e){return new TextDecoder(`utf-8`).decode(TF(e))}function QV(e){if(e&&typeof e.write==`function`)return e}var $V=class extends gI{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=YV(ZV(XV(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 kV&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function eH(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=QV(e.output)}else r=t,i=QV(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new $V(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:$V,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var tH=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`?`: ${nH(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 nH(e){try{return JSON.stringify(e)}catch{return String(e)}}function rH(e){return new Promise(t=>setTimeout(t,e))}function iH(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 aH(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?iH(r,n):r}function oH(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 sH(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function cH(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 lH(e){if(sH(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 uH(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 dH(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function fH(e,t,n){let r=await t(n);r&&!dH(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function pH(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 mH(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function hH(e,t){let n=await lH(e);return t?mH(e,n):n}async function gH(e,t){let n=await lH(e).catch(()=>null);throw new tH(e.status,e.statusText,t,n)}function _H(e,t){let n=cH(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function vH(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=pH(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 hH(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return gH(l,t);await e.sleep(_H(l,a))}if(i)return gH(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function yH(e){let t=e.sleep??rH;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=aH(n.baseUrl,o,s.params),l=oH(n.headers,s.headers);n.token&&await fH(l,n.token,{method:a,path:o,url:c});let u=uH(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),vH({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 bH(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 xH(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`,bH(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 SH(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(xH(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 CH(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 wH(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=CH(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 TH(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 EH(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 EH(e){if(typeof e==`string`)return{body:e};if(e instanceof URLSearchParams)return{body:e.toString(),defaultContentType:`application/x-www-form-urlencoded;charset=UTF-8`};if(e instanceof Blob)return{body:new Uint8Array(await e.arrayBuffer()),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:new Uint8Array(e).slice(),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice(),defaultContentType:`application/octet-stream`};if(lr(e)){let t=await hr(e);return{body:t.bytes,defaultContentType:t.contentType}}throw typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, Blob, FormData, or URLSearchParams`)}function DH(e){return{findTab:t=>e.call(`browser`,`findTab`,[kH(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,AH(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[CH(t),OH(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[CH(t),OH(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[CH(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[CH(t),n]),fetch:(t,n,r={})=>Ba(n,r).then(n=>e.call(`browser`,`evalAsync`,[CH(t),n])),websocket:wH(e)}}function OH(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 kH(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 AH(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function jH(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function MH(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:jH(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}const NH=new Set([204,205,304]),PH=new Set([`content-encoding`,`transfer-encoding`,`content-length`]);function FH(e,t){let n=IH(e.body),r=LH(e.headers),i=NH.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 RH(a,n),a}function IH(e){return e.byteLength===0?new Uint8Array:e.slice()}function LH(e){let t=new Headers;for(let[n,r]of Object.entries(e))if(!PH.has(n.toLowerCase()))try{t.set(n,r)}catch{}return t}function RH(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 zH(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 BH(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function VH(e){return e==null?[]:Array.isArray(e)?e:[e]}function HH(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:BH(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,zH(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,zH(r)]),receiveFeatureReport:async t=>BH((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 UH(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>HH(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[VH(t)]))[0];if(!n)throw Error(`No device selected.`);return HH(e,n)}}}function WH(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 GH=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 };`)}},KH=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=WH(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 GH(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 GH(this.rpc,this.targetId,e,r));return n}async $$eval(e,t,...n){if(typeof t==`string`)return this.rpc.call(`browser`,`evalAsync`,[this.targetId,t]);let r=`(${t.toString()}).apply(null, [Array.from(document.querySelectorAll(${JSON.stringify(e)}))].concat(JSON.parse(${JSON.stringify(JSON.stringify(n))})))`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,r])}async content(){return this.rpc.call(`browser`,`evalAsync`,[this.targetId,`document.documentElement.outerHTML`])}async setViewportSize(e){await this.rpc.call(`browser`,`setViewport`,[this.targetId,e.width,e.height])}async close(){this.closed||(this.closed=!0,await this.rpc.call(`browser`,`closeTab`,[this.targetId]),this.onClose?.())}},qH=class{rpc;openPages=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]);let n=new KH(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()}},JH=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 KH(this.rpc,t,()=>{let e=this.openPages.indexOf(n);e!==-1&&this.openPages.splice(e,1)});return this.openPages.push(n),n}async newContext(e){let t=new qH(this.rpc);return this.openContexts.push(t),t}contexts(){return[...this.openContexts]}async close(){let e=this.openPages.splice(0,this.openPages.length);for(let t of e)await t.close();let t=this.openContexts.splice(0,this.openContexts.length);for(let e of t)await e.close()}};function YH(e){let t=async t=>new JH(e),n=async(t,n)=>new JH(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const XH=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`]),ZH={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 QH(e,t){let n=ZH[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function $H(e){return{...e,time:DV,fmt:nI,pool:CV}}function eU(e,t){return e?.startsWith(`/`)?OV(e):t}function tU(e){return e.includes(`require`)||e.includes(`import`)||/(?:^|[;\n}])\s*export\b/.test(e)}async function nU(e,t,n,r){return tU(t)?e.call(`module`,`buildGraph`,[t,eU(r,n),r]):{files:[],entryMap:{},edges:{},edgeErrors:{},errors:{}}}function rU(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 iU(e){return{playwright:YH(e)}}function aU(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=zL,nodeUtilModule:u=BI}=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=PL({requireFrom:(e,t)=>b(e,t),resolveFrom:(e,t)=>y(e,t)}),h=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:cU(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=oU(t,{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:l,nodeUtilModule:u,nodeReadline:c,nodeModule:m});if(a.hit)return a;if(XH.has(t))throw QH(e,t);if(Ree.has(t))throw uU(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},g=(e,n,r)=>{let i=h(n);if(i.hit)return i.value;let a=e?.[n];if(a)return _(a);let o=r===null?t.errors[n]:t.edgeErrors?.[r]?.[n];throw o?Error(o):sU(n)};function _(e){let n=p.get(e);if(n)return n.exports;let i=d.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};p.set(e,o);let s=n=>g(t.edges[e],n,e),c=OV(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`&&rU(o.exports),o.exports}function v(e){return d.has(e)}function y(e,n){if(xa(n))return n;let r=t.edges[e]?.[n];if(r)return r;let i=OV(e);if(NL(n)){let e=jL(i,n,v);if(e)return e}else{let e=ML(i,n,v);if(e)return e}let a=t.edgeErrors?.[e]?.[n];throw a?Error(a):sU(n)}function b(e,t){let n=h(t);return n.hit?n.value:_(y(e,t))}return{require:e=>g(t.entryMap,e,null)}}function oU(e,t){let{fsBridge:n,processShim:r,childProcess:i,nodeOsModule:a,nodeUtilModule:o,nodeReadline:s,nodeModule:c}=t;return e===`fs`||e===`fs/promises`?{hit:!0,value:n}:e===`path`?{hit:!0,value:SL}:e===`crypto`?{hit:!0,value:dL}: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:mI}:e===`assert/strict`?{hit:!0,value:pI}:e===`util`?{hit:!0,value:o}:e===`events`?{hit:!0,value:_I}:e===`os`?{hit:!0,value:a}:e===`tty`?{hit:!0,value:BL}:e===`stream`?{hit:!0,value:SI}:e===`url`?{hit:!0,value:TL}:e===`zlib`?{hit:!0,value:bV}:e===`readline`&&s?{hit:!0,value:s}:e===`readline/promises`&&s?{hit:!0,value:s.promises}:e===`module`&&c?{hit:!0,value:c}:{hit:!1}}function sU(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 cU(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 lU={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function uU(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${lU[t]||``}`)}async function dU(e,t,n,r){let i=Object.keys(t),a=i.map(e=>t[e]),o=Object.getPrototypeOf(async function(){}).constructor,s=new o(...i,`${r?`"use strict";
|
|
1631
1631
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof kV?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function fU(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?zH(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,zH(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function pU(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>fU(e,t)),request:async t=>fU(e,await e.call(`serial`,`request`,[VH(t)]))}}function mU(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 hU(e,t){let n=t.handle,r=e=>({status:e.status,data:BH(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),clearHalt:(t,r)=>e.call(`usb`,`clearHalt`,[n,t,r]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:t=>e.call(`usb`,`claim`,[n,t]),releaseInterface:t=>e.call(`usb`,`release`,[n,t]),controlTransferIn:async(t,i)=>r(await e.call(`usb`,`controlIn`,[n,t,i])),controlTransferOut:(t,r)=>e.call(`usb`,`controlOut`,[n,t,zH(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,zH(r)])}}function gU(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>hU(e,t)),request:async t=>hU(e,await e.call(`usb`,`request`,[VH(t)]))}}function _U(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function vU(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 yU(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function bU(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function xU(e){let t=_U(e.argv[1]??``),n=vU(t),r=bU(n,`references`),i=bU(n,`assets`),a=bU(t,`.config`);async function o(){let t;try{t=await e.fs.exists(a)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(a)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let i;try{i=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${a}: ${t}`)}if(i&&typeof i==`object`&&!Array.isArray(i))return i;throw Error(`skill.config(): ${a} must contain a JSON object`)}async function s(t){let n=await o();if(t===void 0)return n;if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(`skill.config(updates): updates must be a plain object`);let r={...n??{},...t};return await e.fs.writeFile(a,JSON.stringify(r,null,2)+`
|
|
1632
|
-
`),r}async function c(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${yU(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 SU=new Map,CU=new Map;function wU(e){let t=crypto.randomUUID();return SU.set(t,e),t}function TU(e){return SU.get(e)??null}function EU(e,t){if(!SU.has(e))return t.abort(),()=>{};let n=CU.get(e);return n||(n=new Set,CU.set(e,n)),n.add(t),()=>{let n=CU.get(e);n&&(n.delete(t),n.size===0&&CU.delete(e))}}function DU(e){SU.delete(e);let t=CU.get(e);if(t){CU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function OU(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 kU(e){let t=TU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return OU(e)}}function AU(e){return`slicc-sync-fs-`+e}const jU=`sync-fs-ack`,MU=`sync-fs-res`,NU=6e5,PU=5e3,FU=`exec`;function IU(e){return e.channel===FU}function LU(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 RU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,NU)}async function zU(e){let t=TU(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=LU(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()},RU(e.timeoutMs,NU)),o=EU(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`}:OU(e)}finally{clearTimeout(a),o()}}function BU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function VU(e){let t=UU(e);if(WU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw BU(`EIO`,e.label);GU(t,e.label)}function HU(e){let t=VU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw BU(`EIO`,e.label)}}function UU(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 BU(`EIO`,e.label)}return t}function WU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function GU(e,t){throw BU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function KU(e){return(t,n,r)=>{let i=HU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:FU})),timeoutMs:n+PU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw BU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function qU(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function JU(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??KU(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&qU(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=RU(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 YU(e,t){return BU(e,`sync-fs bridge, '${t}'`)}function XU(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function ZU(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:XU(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return VU(r(`GET`,e))},writeFile(e,t){VU(r(`POST`,e,t))},stat(e){let t=HU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw YU(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=HU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw YU(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=HU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw YU(`EIO`,e);return t},exists(e){let t=HU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw YU(`EIO`,e);return t},mkdir(e){VU(r(`POST`,e,void 0,`mkdir`))},rm(e){VU(r(`POST`,e,void 0,`rm`))}}}const QU=new TextEncoder,$U=new TextDecoder;function eW(e){if(!e.ok)return{status:4,payload:QU.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:QU.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function tW(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($U.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse($U.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 nW(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 rW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function iW(e,t,n={}){let{header:r,window:i}=nW(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 BU(`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 BU(`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 BU(`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 BU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return tW(f,d)}}}function aW(e,t){return BU(e,`sync-sab bridge, '${t}'`)}function oW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function sW(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 aW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw aW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw aW(`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(!oW(t))throw aW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!oW(t))throw aW(`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 aW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw aW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function cW(e){return(t,n,r)=>{let i=e.call({...t,channel:FU},n+PU,r);if(!i.ok)throw BU(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 BU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function lW(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 CF(r)}function uW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function dW(e,t){return t?sW(t):e.syncFsToken?ZU(e.syncFsToken):void 0}function fW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return iW(e.syncSab,t)}function pW(e,t,n,r,i){let a=fW(e,t),o=dW(e,a);if(Object.assign(r,UF(n,e.cwd,o,i)),e.syncFsToken)return JU(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:cW(a)}:{}})}function mW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:ei().version,writable:!1,enumerable:!1,configurable:!1})}function hW(e,t,n){let r=KF({isTTY:!e,noColor:e});return{colorApi:r,cliApi:WF({writeStdout:t,writeStderr:n,exit:e=>{throw new kV(e)},color:r})}}function gW(e,t,n){return{readStdinBytes:()=>TF(e.stdin??``),writeStdout:t,writeStderr:n}}function _W(e){return{usbBridge:gU(e),serialBridge:pU(e),hidBridge:UH(e)}}async function vW(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=GV(i,a),s=KV(e,i,a),{colorApi:c,cliApi:l}=hW(!!e.env?.NO_COLOR,i,a),u=new PP(t),d=gW(e,i,a),f=LF(u,C,d),p=await lW(u,e.cwd,uW(e,a)),m=pW(e,t,p,f,d),h=MH(u,p,e.cwd,a),g=SH(h,{cwd:e.cwd}),_=xU({argv:e.argv,fs:f,exec:h}),v=DH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=_W(u),S=yH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return FH(await u.call(`fetch`,`request`,[n,await TH(t,e)]),n)}let w=$H({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=OV(T),D=await nU(u,e.code,e.cwd,T),ee=aU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:YI(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:iU(u),nodeReadline:eH({output:{write:i},onExit:s.recordExit}),nodeOsModule:RL(e.env),nodeUtilModule:zI(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await yW({entryCode:D.entrySource??e.code,isEsmEntry:ne,filename:T,dirname:E,proc:s,nodeConsole:o,requireShim:ee,moduleShim:te,realmFetch:C,writeStderr:a,rpc:u,syncFs:p,stdoutChunks:n,stderrChunks:r,port:t})}async function yW(e){let t=globalThis;mW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=mU(globalThis,{onCallbackError(e){if(!(e instanceof kV))throw e}});n.install();try{let r=await bW({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 bW(e){let t=await dU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await xW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await SW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await xW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function xW(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 SW(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 CW(){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 wW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=CW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&vW(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 TW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=CW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&GP(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 EW=wW(),DW=TW();function OW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?AW():DW({kind:e,ctx:t}):typeof Worker<`u`?kW():EW({kind:e,ctx:t})}function kW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return jW(new Worker(new URL(`/assets/js-realm-worker-BMbF2DPc.js`,``+import.meta.url),{type:`module`}))}function AW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return jW(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function jW(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 MW(){if(ja())return decodeURIComponent(Bee(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function NW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function PW(e){return e instanceof Error?e.message:String(e)}function FW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function IW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:FW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function LW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:FW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const RW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,zW=/\bimport\s*\.\s*meta\b/g;function BW(e,t){let n=JSON.stringify(t);return e.replace(RW,n).replace(zW,`({ url: ${n} })`)}async function VW(e,t,n,r){let i=await e();return i.transpileModule(BW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function HW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Va(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ea(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!wa(e))return e;let a=NW(t),o;try{return await IW(n,e,t,a)}catch(e){o=e}try{return await VW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${PW(o)}; typescript fallback: ${PW(e)}`)}}}function UW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Va(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ea(t));return async({source:e,filename:t})=>{if(!wa(e)&&!Ra(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?NW(t):void 0,o=i?t:`[eval].js`,s;try{return await LW(n,e,t,a)}catch(e){s=e}try{return await VW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${PW(s)}; typescript fallback: ${PW(e)}`)}}}function WW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1632
|
+
`),r}async function c(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${yU(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 SU=new Map,CU=new Map;function wU(e){let t=crypto.randomUUID();return SU.set(t,e),t}function TU(e){return SU.get(e)??null}function EU(e,t){if(!SU.has(e))return t.abort(),()=>{};let n=CU.get(e);return n||(n=new Set,CU.set(e,n)),n.add(t),()=>{let n=CU.get(e);n&&(n.delete(t),n.size===0&&CU.delete(e))}}function DU(e){SU.delete(e);let t=CU.get(e);if(t){CU.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function OU(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 kU(e){let t=TU(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return OU(e)}}function AU(e){return`slicc-sync-fs-`+e}const jU=`sync-fs-ack`,MU=`sync-fs-res`,NU=6e5,PU=5e3,FU=`exec`;function IU(e){return e.channel===FU}function LU(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 RU(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,NU)}async function zU(e){let t=TU(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=LU(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()},RU(e.timeoutMs,NU)),o=EU(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`}:OU(e)}finally{clearTimeout(a),o()}}function BU(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function VU(e){let t=UU(e);if(WU(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw BU(`EIO`,e.label);GU(t,e.label)}function HU(e){let t=VU(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw BU(`EIO`,e.label)}}function UU(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 BU(`EIO`,e.label)}return t}function WU(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function GU(e,t){throw BU(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function KU(e){return(t,n,r)=>{let i=HU({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:FU})),timeoutMs:n+PU,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw BU(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function qU(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function JU(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??KU(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&qU(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=RU(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 YU(e,t){return BU(e,`sync-fs bridge, '${t}'`)}function XU(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function ZU(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:XU(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return VU(r(`GET`,e))},writeFile(e,t){VU(r(`POST`,e,t))},stat(e){let t=HU(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw YU(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=HU(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw YU(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=HU(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw YU(`EIO`,e);return t},exists(e){let t=HU(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw YU(`EIO`,e);return t},mkdir(e){VU(r(`POST`,e,void 0,`mkdir`))},rm(e){VU(r(`POST`,e,void 0,`rm`))}}}const QU=new TextEncoder,$U=new TextDecoder;function eW(e){if(!e.ok)return{status:4,payload:QU.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:QU.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function tW(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($U.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse($U.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 nW(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 rW(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function iW(e,t,n={}){let{header:r,window:i}=nW(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 BU(`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 BU(`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 BU(`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 BU(`EIO`,a)}}finally{Atomics.store(r,0,0)}return tW(f,d)}}}function aW(e,t){return BU(e,`sync-sab bridge, '${t}'`)}function oW(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function sW(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 aW(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw aW(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw aW(`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(!oW(t))throw aW(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!oW(t))throw aW(`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 aW(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw aW(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function cW(e){return(t,n,r)=>{let i=e.call({...t,channel:FU},n+PU,r);if(!i.ok)throw BU(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 BU(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function lW(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 CF(r)}function uW(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function dW(e,t){return t?sW(t):e.syncFsToken?ZU(e.syncFsToken):void 0}function fW(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return iW(e.syncSab,t)}function pW(e,t,n,r,i){let a=fW(e,t),o=dW(e,a);if(Object.assign(r,UF(n,e.cwd,o,i)),e.syncFsToken)return JU(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:cW(a)}:{}})}function mW(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:ei().version,writable:!1,enumerable:!1,configurable:!1})}function hW(e,t,n){let r=KF({isTTY:!e,noColor:e});return{colorApi:r,cliApi:WF({writeStdout:t,writeStderr:n,exit:e=>{throw new kV(e)},color:r})}}function gW(e,t,n){return{readStdinBytes:()=>TF(e.stdin??``),writeStdout:t,writeStderr:n}}function _W(e){return{usbBridge:gU(e),serialBridge:pU(e),hidBridge:UH(e)}}async function vW(e,t){let n=[],r=[],i=e=>{n.push(typeof e==`string`?e:String(e))},a=e=>{r.push(typeof e==`string`?e:String(e))},o=GV(i,a),s=KV(e,i,a),{colorApi:c,cliApi:l}=hW(!!e.env?.NO_COLOR,i,a),u=new PP(t),d=gW(e,i,a),f=LF(u,C,d),p=await lW(u,e.cwd,uW(e,a)),m=pW(e,t,p,f,d),h=MH(u,p,e.cwd,a),g=SH(h,{cwd:e.cwd}),_=xU({argv:e.argv,fs:f,exec:h}),v=DH(u),{usbBridge:y,serialBridge:b,hidBridge:x}=_W(u),S=yH({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e);return FH(await u.call(`fetch`,`request`,[n,await TH(t,e)]),n)}let w=$H({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=OV(T),D=await nU(u,e.code,e.cwd,T),ee=aU({graph:D,fsBridge:f,processShim:s.processShim,childProcess:YI(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:iU(u),nodeReadline:eH({output:{write:i},onExit:s.recordExit}),nodeOsModule:RL(e.env),nodeUtilModule:zI(e=>a(`${e}\n`))}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0;await yW({entryCode:D.entrySource??e.code,isEsmEntry:ne,filename:T,dirname:E,proc:s,nodeConsole:o,requireShim:ee,moduleShim:te,realmFetch:C,writeStderr:a,rpc:u,syncFs:p,stdoutChunks:n,stderrChunks:r,port:t})}async function yW(e){let t=globalThis;mW(),t.__slicc_compileWasm=t=>e.rpc.call(`wasm`,`compile`,[t]);let n=mU(globalThis,{onCallbackError(e){if(!(e instanceof kV))throw e}});n.install();try{let r=await bW({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 bW(e){let t=await dU(e.entryCode,e.bridges,e.writeStderr,e.isEsmEntry);return await xW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?(e.timers.clearPending(),e.proc.getExitCode()):(await SW(e.rpc,e.timers,e.proc),e.proc.getDidCallProcessExit()&&e.timers.clearPending(),await xW(e.rpc,e.syncFs,e.writeStderr),e.proc.getDidCallProcessExit()?e.proc.getExitCode():t)}async function xW(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 SW(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 CW(){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 wW(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=CW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&vW(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 TW(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=CW(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&GP(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 EW=wW(),DW=TW();function OW(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?AW():DW({kind:e,ctx:t}):typeof Worker<`u`?kW():EW({kind:e,ctx:t})}function kW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return jW(new Worker(new URL(`/assets/js-realm-worker-CYo2Tual.js`,``+import.meta.url),{type:`module`}))}function AW(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return jW(new Worker(new URL(`/assets/py-realm-worker-BRyQamcA.js`,``+import.meta.url),{type:`module`}))}function jW(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 MW(){if(ja())return decodeURIComponent(Bee(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function NW(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function PW(e){return e instanceof Error?e.message:String(e)}function FW(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function IW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:FW(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function LW(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:FW(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const RW=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,zW=/\bimport\s*\.\s*meta\b/g;function BW(e,t){let n=JSON.stringify(t);return e.replace(RW,n).replace(zW,`({ url: ${n} })`)}async function VW(e,t,n,r){let i=await e();return i.transpileModule(BW(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function HW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Va(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ea(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!wa(e))return e;let a=NW(t),o;try{return await IW(n,e,t,a)}catch(e){o=e}try{return await VW(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${PW(o)}; typescript fallback: ${PW(e)}`)}}}function UW(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Va(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Ea(t));return async({source:e,filename:t})=>{if(!wa(e)&&!Ra(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?NW(t):void 0,o=i?t:`[eval].js`,s;try{return await LW(n,e,t,a)}catch(e){s=e}try{return await VW(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${PW(s)}; typescript fallback: ${PW(e)}`)}}}function WW(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1633
1633
|
`);return t===-1?``:e.slice(t+1)}function GW(e){return hn(e).dir}const KW=[`node`,`require`,`default`],qW=[`node`,`import`,`default`],JW=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,YW=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,XW=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,ZW=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,QW=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function $W(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function eG(e){let t=La(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!$W(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(JW,`require`,`require`),r(YW,`import`,`import`),r(XW,`import`,`import`),r(ZW,`import`,`export`),r(QW,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function tG(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=WW(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${Pa} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function nG(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??KW,s=e.importConditions??qW,c=i??o,l=new Map,u=[],d={},f={};async function p(e,t){if(l.has(e))return;let n=await r.readFile(e),i=await tG(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=GW(e),m={},h={};for(let{specifier:e,kind:t}of eG(n)){let n;try{n=await ya(e,c,r,{conditions:t===`import`?s:o})}catch(t){h[e]=t instanceof Error?t.message:String(t);continue}n.type===`file`&&(m[e]=n.path,await p(n.path,n.moduleKind))}d[e]=m,Object.keys(h).length>0&&(f[e]=h),u.push(e)}let m={};for(let e of t){let t=await ya(e,n,r,{conditions:c});t.type===`file`&&(m[e]=t.path,await p(t.path,t.moduleKind))}return{files:u.map(e=>{let t=l.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return t}),entryMap:m,edges:d,edgeErrors:f}}function rG(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Sa.has(e)||XH.has(e))}function iG(e,t){for(let[n,r]of Object.entries(t))e[n]={...e[n]??{},...r}}async function aG(e){let{entryCode:t,fromDir:n,entryFilename:r,reader:i,transpile:a,transpileEntry:o}=e,s=new Map,c=[],l={},u={},d={},f={};for(let{specifier:e,kind:r}of eG(t))if(rG(e))try{let t=await nG({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?qW:KW,requireConditions:KW,importConditions:qW});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap),iG(u,t.edges),iG(d,t.edgeErrors)}catch(t){f[e]=t instanceof Error?t.message:String(t)}let p;o&&(wa(t)||Ra(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 oG(){return globalThis.navigator?.hid??null}function sG(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function cG(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&sG(e)===sG(t)&&!!e.productName}var lG=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(cG(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 uG=null;function dG(){return uG||=new lG,uG}const fG=4194304;function pG(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 mG(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function hG(e){e.opened||await e.open()}function gG(e,t){if(e>4194304)throw Error(`${t} exceeds the ${fG}-byte (4 MiB) v1 limit`)}function _G(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function vG(e,t){return(await t.getDevices()).map(t=>pG(e.register(t),t))}async function yG(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>pG(e.register(t),t))}function bG(e,t){return pG(t,mG(e,t))}async function xG(e,t){await mG(e,t).open()}async function SG(e,t){await mG(e,t).close()}async function CG(e,t,n,r){gG(r.byteLength,`send report payload`);let i=mG(e,t);await hG(i),await i.sendReport(n,r)}async function wG(e,t,n,r){gG(r.byteLength,`send feature report payload`);let i=mG(e,t);await hG(i),await i.sendFeatureReport(n,r)}async function TG(e,t,n){let r=mG(e,t);return await hG(r),{reportId:n,bytes:_G(await r.receiveFeatureReport(n))}}async function EG(e,t,n){let r=mG(e,t);await hG(r);let i=e=>{n({reportId:e.reportId,bytes:_G(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const DG=6e4;function OG(){return kS()}function kG(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),DG);AS(`hid-device`,e??[],void 0,{timeoutMs:DG}).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 AG(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var jG=class{registry;constructor(e){this.registry=e}hid(){let e=oG();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return vG(this.registry,this.hid())}async request(e){if(OG()){let t=await kG(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=>pG(this.registry.register(e),e))}return yG(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(bG(this.registry,e))}open(e){return xG(this.registry,e)}close(e){return SG(this.registry,e)}sendReport(e,t,n){return CG(this.registry,e,t,AG(n))}sendFeatureReport(e,t,n){return wG(this.registry,e,t,AG(n))}async receiveFeatureReport(e,t){let n=await TG(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return EG(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},MG=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:AG(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:AG(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 NG(e,t){return e&&oG()?new jG(dG()):t?new MG(t):null}function PG(e){return async function(t,n){let r=t instanceof Request?t:null,i=FG(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=LG(r?.headers,n?.headers),s=await BG(n,r,a,o);s.defaultContentType&&!RG(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 FG(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function IG(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 LG(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=IG(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function RG(e,t){return zG(e,t)!==void 0}function zG(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function BG(e,t,n,r){if(e&&`body`in e&&e.body!==void 0)return VG(e.body,n);if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=zG(r,`content-type`)??``,a=e&&(!i||!x(i));return{body:n.byteLength===0?void 0:a?Ce(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function VG(e,t){if(lr(e)){if(t===`GET`||t===`HEAD`)return{};let n=await hr(e);return{body:n.bytes,defaultContentType:n.contentType}}return{body:await HG(e,t),defaultContentType:WG(e,t)}}async function HG(e,t){if(e!=null&&t!==`GET`&&t!==`HEAD`){if(typeof e==`string`)return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof Uint8Array)return Ce(e);if(e instanceof ArrayBuffer)return new Uint8Array(e).slice();if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice()}if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw typeof ReadableStream<`u`&&e instanceof ReadableStream?Error(`node fetch shim: ReadableStream request bodies are not supported (collect into a Uint8Array or string before calling fetch)`):Error(`node fetch shim: unsupported request body type (${Object.prototype.toString.call(e)}); use a string, Uint8Array, ArrayBuffer, Blob, FormData, or URLSearchParams`)}}function UG(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function WG(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!UG(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function GG(){return globalThis.navigator?.serial??null}var KG=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(n.port===e)return t;let t=`serial${++this.counter}`;return this.byHandle.set(t,{port:e,opened:!1}),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,entry:t}))}retainOnly(e){let t=[];for(let[n,r]of[...this.byHandle])e.includes(r.port)||(this.byHandle.delete(n),t.push({handle:n,entry:r}));return t}};let qG=null;function JG(){return qG||=new KG,qG}const YG=4194304;function XG(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 ZG(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function QG(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function $G(e,t,n){if(t.length===0)return-1;outer:for(let r=Math.max(0,n);r+t.length<=e.length;r++){for(let n=0;n<t.length;n++)if(e[r+n]!==t[n])continue outer;return r}return-1}async function eK(e){if(e.reader){try{await e.reader.cancel()}catch{}try{e.reader.releaseLock()}catch{}e.reader=void 0}if(e.pendingRead=void 0,e.leftover=void 0,e.writer){try{e.writer.releaseLock()}catch{}e.writer=void 0}}async function tK(e){if(await eK(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function nK(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await tK(t);return n.map(t=>{let n=e.register(t);return XG(n,e.get(n))})}async function rK(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return XG(i,e.get(i))}function iK(e,t){return XG(t,ZG(e,t))}async function aK(e,t,n){let r=ZG(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 oK(e,t){let n=ZG(e,t);await eK(n);try{await n.port.close()}catch(e){if(!sK(e))throw e}n.opened=!1}function sK(e){let t=e instanceof Error?e.message:String(e);return/already closed|not open/i.test(t)}function cK(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 lK(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 uK(e,t,n){let r=ZG(e,t),i=Math.min(n.maxBytes??4194304,YG),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=$G(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=cK(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=QG(c,a.value);let e=u();if(e)return e}}return c}async function dK(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${YG}-byte (4 MiB) v1 limit`);return await lK(ZG(e,t)).write(n),n.length}async function fK(e,t){return ZG(e,t).port.getSignals()}async function pK(e,t,n){await ZG(e,t).port.setSignals(n)}const mK=6e4;function hK(){return kS()}function gK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),mK);AS(`serial-port`,e??[],void 0,{timeoutMs:mK}).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 _K(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var vK=class{registry;constructor(e){this.registry=e}serial(){let e=GG();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return nK(this.registry,this.serial())}async request(e){if(hK()){let t=await gK(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 XG(r,this.registry.get(r))}return rK(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(iK(this.registry,e))}open(e,t){return aK(this.registry,e,t)}close(e){return oK(this.registry,e)}read(e,t){return uK(this.registry,e,t)}write(e,t){return dK(this.registry,e,t)}getSignals(e){return fK(this.registry,e)}setSignals(e,t){return pK(this.registry,e,t)}},yK=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?_K(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:_K(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 bK(e,t){return e&&GG()?new vK(JG()):t?new yK(t):null}function xK(){return globalThis.navigator?.usb??null}function SK(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var CK=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(SK(n,e))return this.byHandle.set(t,e),t;let t=`usb${++this.counter}`;return this.byHandle.set(t,e),t}get(e){return this.byHandle.get(e)}remove(e){return this.byHandle.delete(e)}list(){return[...this.byHandle].map(([e,t])=>({handle:e,device:t}))}};let wK=null;function TK(){return wK||=new CK,wK}const EK=4194304,DK=new Set([`in`,`out`]),OK=new Set([`bulk`,`interrupt`,`isochronous`]);function kK(e){return e.map(e=>({configurationValue:e.configurationValue,...e.configurationName?{configurationName:e.configurationName}:{},interfaces:(e.interfaces??[]).map(e=>({interfaceNumber:e.interfaceNumber,claimed:!!e.claimed,alternates:(e.alternates??[]).map(e=>({alternateSetting:e.alternateSetting,interfaceClass:e.interfaceClass,interfaceSubclass:e.interfaceSubclass,interfaceProtocol:e.interfaceProtocol,...e.interfaceName?{interfaceName:e.interfaceName}:{},endpoints:(e.endpoints??[]).filter(e=>DK.has(e.direction)&&OK.has(e.type)).map(e=>({endpointNumber:e.endpointNumber,direction:e.direction,type:e.type,packetSize:e.packetSize}))}))}))}))}function AK(e,t){return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...t.manufacturerName?{manufacturerName:t.manufacturerName}:{},...t.serialNumber?{serialNumber:t.serialNumber}:{},opened:t.opened,...t.configurations?{configurations:kK(t.configurations)}:{}}}function jK(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function MK(e,t){if(e>4194304)throw Error(`${t} exceeds the ${EK}-byte (4 MiB) v1 limit`)}function NK(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function PK(e,t){return(await t.getDevices()).map(t=>AK(e.register(t),t))}async function FK(e,t,n){let r=await t.requestDevice({filters:n});return AK(e.register(r),r)}function IK(e,t){return AK(t,jK(e,t))}async function LK(e,t){await jK(e,t).open()}async function RK(e,t){await jK(e,t).close()}async function zK(e,t,n){await jK(e,t).selectConfiguration(n)}async function BK(e,t,n){await jK(e,t).claimInterface(n)}async function VK(e,t,n){await jK(e,t).releaseInterface(n)}async function HK(e,t,n,r){MK(r,`control-in length`);let i=await jK(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?NK(i.data):new ArrayBuffer(0)}}async function UK(e,t,n,r){MK(r.byteLength,`control-out payload`);let i=await jK(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function WK(e,t,n,r){MK(r,`transfer-in length`);let i=await jK(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?NK(i.data):new ArrayBuffer(0)}}async function GK(e,t,n,r){MK(r.byteLength,`transfer-out payload`);let i=await jK(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function KK(e,t){await jK(e,t).reset()}async function qK(e,t,n,r){await jK(e,t).clearHalt(n,r)}const JK=6e4;function YK(){return kS()}function XK(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),JK);AS(`usb-device`,e??[],void 0,{timeoutMs:JK}).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 ZK(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var QK=class{registry;constructor(e){this.registry=e}usb(){let e=xK();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return PK(this.registry,this.usb())}async request(e){if(YK()){let t=await XK(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 AK(this.registry.register(n),n)}return FK(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(IK(this.registry,e))}open(e){return LK(this.registry,e)}close(e){return RK(this.registry,e)}selectConfig(e,t){return zK(this.registry,e,t)}claim(e,t){return BK(this.registry,e,t)}release(e,t){return VK(this.registry,e,t)}async controlIn(e,t,n){let r=await HK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return UK(this.registry,e,t,ZK(n))}async transferIn(e,t,n){let r=await WK(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return GK(this.registry,e,t,ZK(n))}clearHalt(e,t,n){return qK(this.registry,e,t,n)}reset(e){return KK(this.registry,e)}},$K=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:ZK(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:ZK(n)})}async clearHalt(e,t,n){await this.rpc.call(`usb-clear-halt`,{handle:e,direction:t,endpointNumber:n})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function eq(e,t){return e&&xK()?new QK(TK()):t?new $K(t):null}function tq(e,t,n,r={}){let{header:i,window:a}=nW(t),o=new Map,s=!1,c=r.dispatch??(e=>IU(e)?zU(e):kU(e));function l(e){let t=o.get(e);t&&(clearTimeout(t.timer),o.delete(e))}function u(e,t,n){let r=Math.min(a.byteLength,t.payload.byteLength-n);r>0&&a.set(t.payload.subarray(n,n+r)),Atomics.store(i,2,t.status),Atomics.store(i,3,t.payload.byteLength),Atomics.store(i,4,r),Atomics.store(i,5,n),Atomics.store(i,1,e),Atomics.store(i,0,2),Atomics.notify(i,0),n+r>=t.payload.byteLength&&l(e)}function d(e,t){if(s)return;let{status:n,payload:r}=eW(t);l(e);let i={status:n,payload:r,timer:setTimeout(()=>l(e),605e3)};o.set(e,i),u(e,i,0)}let f=e=>{let t=e.data;if(!t||typeof t.id!=`number`)return;if(t.type===`sync-sab-next`){let e=o.get(t.id),n=t.offset;if(!e||typeof n!=`number`||!Number.isInteger(n)||n<0||n>e.payload.byteLength){d(t.id,{ok:!1,errno:`EIO`,message:`sync-sab: bad continuation`});return}u(t.id,e,n);return}if(t.type!==`sync-sab-req`||!t.req||typeof t.req!=`object`)return;let r=t.id,i={...t.req,token:n},a;try{a=c(i)}catch(e){d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)});return}a.then(e=>d(r,e),e=>d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return e.addEventListener(`message`,f),{dispose:()=>{if(!s){s=!0,e.removeEventListener(`message`,f);for(let e of[...o.keys()])l(e)}}}}const nq=r(`realm-host`);function rq(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?wU({fs:t.fs,...t.exec?{exec:t.exec}:{},cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;iq(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?tq(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&DU(i),e.removeEventListener(`message`,l);for(let{controller:e}of s.values())try{e.signal.aborted||e.abort()}catch{}s.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear()}}}}async function iq(e,t,n,r,i,a){try{let o=await aq(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=Jq(o);e.postMessage(s,c)}catch(n){let r=n instanceof Error?n.message:String(n),i={type:`realm-rpc-res`,id:t.id,error:r};e.postMessage(i)}}async function aq(e,t,n,r,i){switch(e.channel){case`vfs`:return dq(e.op,e.args,t);case`exec`:return wq(e.op,e.args,t,i);case`fetch`:return Oq(e.op,e.args,t);case`browser`:return Mq(e.op,e.args,oq(n),n);case`usb`:return Gq(e.op,e.args,cq(n));case`serial`:return Kq(e.op,e.args,lq(n));case`hid`:return qq(e.op,e.args,uq(n),r);case`module`:return Aq(e.op,e.args,t);case`wasm`:return jq(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function oq(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 sq(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 cq(e){if(e.usbBackend)return e.usbBackend;let t=eq(d(),u());if(!t)throw Error(`usb is not available in this runtime`);return t}function lq(e){if(e.serialBackend)return e.serialBackend;let t=bK(d(),u());if(!t)throw Error(`serial is not available in this runtime`);return t}function uq(e){if(e.hidBackend)return e.hidBackend;let t=NG(d(),u());if(!t)throw Error(`hid is not available in this runtime`);return t}async function dq(e,t,n){let r=typeof t[0]==`string`?t[0]:null,i=r===null?null:n.fs.resolvePath(n.cwd,r);switch(e){case`readFile`:return n.fs.readFile(i);case`readFileBinary`:return n.fs.readFileBuffer(i);case`writeFile`:return await n.fs.writeFile(i,t[1]),!0;case`writeFileBinary`:return await n.fs.writeFile(i,t[1]),!0;case`readDir`:return n.fs.readdir(i);case`exists`:return n.fs.exists(i);case`stat`:{let e=await n.fs.stat(i);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(i,{recursive:!0}),!0;case`rm`:return await n.fs.rm(i,{recursive:!0}),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),r=n.fs;if(r.rename)await r.rename(i,e);else{let t=await n.fs.readFileBuffer(i);await n.fs.writeFile(e,t),await n.fs.rm(i,{recursive:!0})}return!0}case`resolvePath`:return n.fs.resolvePath(n.cwd,t[0]);case`invalidatePaths`:{let e=t[0],r=n.fs;return r.invalidatePaths&&r.invalidatePaths(e),!0}case`snapshot`:return bq(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await xq(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const fq=10485760;function pq(e){return e.fileCount>=500||e.totalBytes>=fq}function mq(e){return e.entries.length>=2e4}async function hq(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 gq(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 _q(e,t,n,r,i){if(n>1048576||pq(r)||r.totalBytes+n>fq){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 vq(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function vq(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await hq(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function yq(e,t,n){if(mq(n))return;let r=[t];for(;r.length>0;){if(mq(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await gq(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await hq(e,t,r,n):a.isFile&&await _q(e,t,a.size,n,r)}}async function bq(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await yq(e,t,n),t!==`/tmp`&&await yq(e,`/tmp`,n),{entries:n.entries}}async function xq(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 Sq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),Cq=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function wq(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 Eq(t,n,r);if(e===`kill`)return Dq(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function Tq(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 Eq(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??{};Tq(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 Dq(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Sq.has(r)?r:`SIGTERM`;Cq.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 Oq(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?PG(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 kq(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 Aq(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=kq(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return aG({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:HW({ipk:s}),transpileEntry:UW({ipk:s})})}async function jq(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 Wa(e=>n.fs.readFileBuffer(e),i)}async function Mq(e,t,n,r){switch(e){case`findTab`:return Fq(n,t[0]??{});case`ensureTab`:{let e=t[0];return Iq(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return Lq(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return Lq(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return Vq(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return Hq(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await sq(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return sq(r).update(e,n)}case`wsClose`:{let e=t[0];return sq(r).close(e)}case`wsList`:return sq(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 Bq(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function Nq(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function Pq(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=Nq()?u():null;if(n)try{let{targets:e}=await n.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(t.map(e=>e.targetId));for(let n of e)r.has(n.targetId)||(r.add(n.targetId),t.push({targetId:n.targetId,url:n.url,title:n.title}))}catch(e){nq.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function Fq(e,t){let n=await Pq(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Uq(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 Iq(e,t,n){let r=await Pq(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=Wq(t);if(e){let t=r.find(t=>Wq(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function Lq(e,t,n,r){return e.withTab(t,async e=>Rq(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function Rq(e){if(typeof e!=`string`)return e;let t=zq(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=zq(t);if(typeof e==`object`&&e)return e}return t}return e}function zq(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 Bq(e,t,n){if(n===`networkidle`)return e.withTab(t,async e=>{for(let t=0;t<20;t++)if(await new Promise(e=>setTimeout(e,250)),await e.evaluate(`(function(){
|
|
1634
1634
|
try {
|
|
1635
1635
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1646,7 +1646,7 @@ except BaseException:
|
|
|
1646
1646
|
})()`,{returnByValue:!0}))return})}async function Vq(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 Hq(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 Uq(e){try{return new URL(e).hostname}catch{return null}}function Wq(e){try{return new URL(e).origin}catch{return null}}async function Gq(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`reset`:return n.reset(t[0]);case`clearHalt`:return n.clearHalt(t[0],t[1],t[2]);case`selectConfig`:return n.selectConfig(t[0],t[1]);case`claim`:return n.claim(t[0],t[1]);case`release`:return n.release(t[0],t[1]);case`controlIn`:return n.controlIn(t[0],t[1],t[2]);case`controlOut`:return n.controlOut(t[0],t[1],t[2]);case`transferIn`:return n.transferIn(t[0],t[1],t[2]);case`transferOut`:return n.transferOut(t[0],t[1],t[2]);default:throw Error(`realm-host: unknown usb op '${e}'`)}}async function Kq(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 qq(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 Jq(e){if(e instanceof Uint8Array)return[e.buffer];if(e&&typeof e==`object`){let t=e;if(t.body instanceof Uint8Array)return[t.body.buffer];if(t.bytes instanceof Uint8Array)return[t.bytes.buffer]}return[]}async function Yq(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?Xq(e.syncSabBytes):void 0,a=rq(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:!!e.syncFsBridgeEnabled||i!==void 0,...i?{syncSab:i}:{}});return new Promise(t=>{let o=!1,s=null,c=null,l=null,u=null,d=()=>{c&&r.controlPort.removeEventListener(`message`,c),r.removeEventListener&&(l&&r.removeEventListener(`error`,l),u&&r.removeEventListener(`messageerror`,u)),s?.(),a.dispose()},f=(i,a)=>{if(!o){o=!0,d();try{r.terminate()}catch{}e.pm.exit(n.pid,a),t(i)}};c=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;f({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;f({stdout:``,stderr:t.message+`
|
|
1647
1647
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1648
1648
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1649
|
-
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function Xq(e){if(rW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let Zq=!1;function Qq(e){Zq=e}function $q(){return Zq}const eJ=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function tJ(e){return eJ[e]??null}function nJ(e,t){let n=tJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let rJ=null;function iJ(e){let t=rJ;return rJ=e,t}async function aJ(){if(!rJ)return{};try{return await rJ()??{}}catch{return{}}}function oJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1649
|
+
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function Xq(e){if(rW())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let Zq=!1;function Qq(e){Zq=e}function $q(){return Zq}const eJ=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function tJ(e){return eJ[e]??null}function nJ(e,t){let n=tJ(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let rJ=null;function iJ(e){let t=rJ;return rJ=e,t}async function aJ(){if(!rJ)return{};try{return await rJ()??{}}catch{return{}}}function oJ(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t);return nJ(t(),e())}}async function sJ(e,t,n,r,i={}){return await n.fs.exists(e)?cJ(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 cJ(e,t,n,r,i={}){let a=i.realmFactory??lJ(),o=r?.processManager??fJ()??dJ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await Yq({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await aJ(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:Ga(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:$q()})}function lJ(){return typeof Worker<`u`||typeof document<`u`?OW():wW()}let uJ=null;function dJ(){return uJ||=new _a,uJ}function fJ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function pJ(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 mJ=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=Ut();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?hJ(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=gJ(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:gJ(i)})})}};async function hJ(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function gJ(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function _J(e,t){return t.length?`${e} ${t.join(` `)}`:e}function vJ(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function yJ(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:vJ(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 bJ={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}},xJ=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function SJ(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 CJ(e,t){switch(e.type){case`CommandSubstitution`:return PJ(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=CJ(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function wJ(e,t){let n=0;for(let r of e.parts){let e=CJ(r,t);if(e===null)return null;n+=e}return n}function TJ(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=wJ(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=wJ(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=SJ(e.name);if(r===null||xJ.has(r))return null;if(!t.has(r))return n;n+=1;let i=bJ[r];if(i){let r=e.args.map(SJ);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(xJ.has(a))return null;t.has(a)&&(n+=1)}return n}function EJ(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 DJ(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||SJ(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=SJ(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 OJ(e){let t=0;for(let n of e){let e=n.type===`Word`?kJ(n.word):EJ(n);if(e===null)return null;t+=e}return t}function kJ(e){let t=DJ(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=OJ(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function AJ(e){let t=0;for(let n of e){let e=kJ(n);if(e===null)return null;t+=e}return t}function jJ(e,t){let n=0;for(let r of e){let e=NJ(r,t);if(e===null)return null;n+=e}return n}function MJ(e,t){switch(e.type){case`SimpleCommand`:return TJ(e,t);case`For`:{if(!e.words)return null;let n=AJ(e.words),r=jJ(e.body,t);return n===null||r===null?null:e.words.filter(e=>DJ(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return jJ(e.body,t);case`FunctionDef`:return 0;default:return null}}function NJ(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=MJ(e,t);if(r===null)return null;n+=r}return n}function PJ(e,t){return jJ(e.statements,t)}function FJ(e,t){let n=PJ(e,t);return{totalSteps:n!==null&&n>0?n:null}}function IJ(e){return e.split(`
|
|
1650
1650
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var LJ=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 RJ=globalThis.setTimeout.bind(globalThis);function zJ(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function BJ(e,t={}){let n=t.now??Date.now,r=t.setTimeout??RJ,i=t.isAborted??(()=>!1),a=t.label??zJ,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 VJ=globalThis.setTimeout.bind(globalThis);function HJ(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 UJ(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 WJ(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??VJ;return{...e,async execute(n,a){let o=UJ(n),s=o>=0?HJ(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=_J(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 GJ=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 KJ(e,t,n={}){if((n.skip??GJ).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=_J(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 qJ=new Map([[`jsh`,`node`]]);function JJ(e,t){return`${qJ.get(e)??e} ${t.join(` `)}`.trim()}function YJ(e){return Ai(`sudo`,e)}async function XJ(e,t){let n=e.trim();if(!n||bi(xi(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:YJ(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const ZJ={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 QJ(e,t=[],n){let r=ZJ[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${xee(n)}</div>`:``;return`
|
|
1651
1651
|
<div class="sprinkle-action-card">
|
|
1652
1652
|
<div class="sprinkle-action-card__header">
|
|
@@ -1768,7 +1768,7 @@ Examples:
|
|
|
1768
1768
|
skill list
|
|
1769
1769
|
skill info bluebubbles
|
|
1770
1770
|
skill read bluebubbles
|
|
1771
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1771
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-MQBhN1sp.js`).then(e=>e.t);try{switch(r){case`list`:return VY(t,e,i);case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1772
1772
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:zY(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
|
|
1773
1773
|
`,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+`
|
|
1774
1774
|
`,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 UY=[{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=>po(e)!==null,error:`upskill: --from requires a GitHub source (owner/repo, owner/repo@branch, or a github.com URL)`,apply:(e,t)=>{e.from=t}},{names:[`--path`,`-p`],validate:e=>C(e),error:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters`,apply:(e,t)=>{e.path=t}}];function WY(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=UY.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 GY(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function KY(e,t){try{let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(String(n))}catch{return}}async function qY(e,t,n,r){let i=await KY(e,t);return ro(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?GY(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function JY(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await qY(e,n,r,a);i.changes.push({path:r,status:o}),s&&i.writes.push({path:n,content:a})}let a=new Set(r.files??[]);for(let r of await to(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 YY(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 eo(t),d=await uo(s,c,o.ref,u,!0);if(d&&r.sha===d&&await XY(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await ZY(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 JY(e,`${Qa}/${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 nX(e,{changes:h,writes:g,removals:_}),await _o(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 XY(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 ZY(e,t,n,r,i,a,o){let s=await io(e,t,a,i??`main`);if(s.status===`ok`){let i=Ya(s.files),a=n||QY(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:tX(i,a),path:a}}try{return{files:eX($Y(await no(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 QY(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 $Y(e){return new Map([...e].filter(([e])=>Xa(e)))}function eX(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function tX(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);Xa(e)&&r.set(e,i)}return eX(r)}async function nX(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 rX(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 PY(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${Qa}/${n}/SKILL.md`,u=await KY(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&MY(new TextDecoder().decode(u))===MY(c.content);if(GY(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${Qa}/${n}`,{recursive:!0}),await e.writeFile(l,d),await _o(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function iX(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 aX(e,t,n,r){let i=po(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 oX(e,t,n){if(t.length===0){let t=await fo(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await bo(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?aX(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 sX(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1779,7 +1779,7 @@ Examples:
|
|
|
1779
1779
|
`}function uX(e,t,n,r,i){let a=t?`Skill update (dry run — nothing written):
|
|
1780
1780
|
`:`Skill update:
|
|
1781
1781
|
`;for(let n of e)a+=iX(n,t);if(i.length>0&&(a+=lX(i)),!n&&r&&e.length>0){let n=i.length>0?`all ${cX(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 dX(e,t,n){let{targets:r,missing:i,skipped:a}=await oX(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 rX(e,t,i.name,i.provenance,n.dryRun):await YY(e,t,i.name,i.provenance,n.branch,n.dryRun));return{results:o,skipped:a,missing:i}}async function fX(e,t,n){let r=WY(e);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{results:i,missing:a,skipped:o}=await dX(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`:uX([],r.dryRun,!1,!0,o),stderr:``,exitCode:0}:{stdout:``,stderr:a.length?a.map(sX).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 lo();let l=a.map(sX).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:uX(i,r.dryRun,c,u,o),stderr:l,exitCode:+!u}}function pX(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 mX(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 hX(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}${mX(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(`
|
|
1782
|
-
`)}\n`}async function gX(e,t){let n=await(await import(`./skills-
|
|
1782
|
+
`)}\n`}async function gX(e,t){let n=await(await import(`./skills-MQBhN1sp.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${IY()}`,stderr:``,exitCode:0}:{stdout:RY(n,`Discoverable local skills`),stderr:``,exitCode:0}}async function _X(e,t,n){let{results:r,skipped:i}=await dX(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:hX(r,i),stderr:c,exitCode:+!s}}async function vX(e,t,n){let r=pX(e);return r.error?{stdout:``,stderr:`${r.error}\n`,exitCode:1}:r.outdated?_X(t,n,r.json):gX(t,r.json)}async function yX(e,t){let n=`${so}/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(ao(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=Se(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=co(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 bX(e,t){let n=`${so}/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: ${ao(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=Se(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=co(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 xX=[{label:`Tessl`,host:new URL(so).host,fetch:yX},{label:`browse.sh`,host:new URL($a).host,fetch:EY}];function SX(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 CX(e,t,n=1){let r=await Promise.allSettled(xX.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=SX(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=xX[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+=`
|
|
1783
1783
|
`}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:
|
|
1784
1784
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
1785
1785
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
@@ -1802,7 +1802,7 @@ Examples:
|
|
|
1802
1802
|
`,{stdout:s,stderr:``,exitCode:0}}function AX(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1803
1803
|
`,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
|
|
1804
1804
|
`,exitCode:1}}function jX(e){let t={selectedSkills:[],listOnly:!1,installAll:!1,force:!1,sourceRef:``},n=0;for(;n<e.length;){let r=e[n];if(r===`--skill`)t.selectedSkills.push(e[++n]);else if(r===`--path`||r===`-p`){let r=e[++n];if(typeof r!=`string`||!C(r))return t.earlyReturn={stdout:``,stderr:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters
|
|
1805
|
-
`,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=AX(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 MX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-
|
|
1805
|
+
`,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=AX(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 MX(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-MQBhN1sp.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 bo(n,t),a=i?mo(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:zY(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+`
|
|
1806
1806
|
`,stderr:``,exitCode:0}}async function NX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await go(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 PX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await ho(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 FX(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await ho(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 IX(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 LX(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await eo(r),l=await vo(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:IX(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:IX(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 io(i,a,r,o);if(e.status===`ok`){let r=await uo(i,a,o,c),s=await NX(u,i,a,Ya(e.files),n,t.force,f,{kind:`github`,source:`${i}/${a}`,ref:o,sha:r});({output:p,errors:m,successCount:h}=s)}else{let e=await PX(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await FX(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 lo()),{stdout:p,stderr:m,exitCode:+!!m}}async function RX(e,t,n,r){switch(e[0]){case`tabs`:return OX(t,n,r,e.includes(`--json`));case`recommendations`:return kX(t,n,e.includes(`--install`));case`update`:case`upgrade`:return fX(e.slice(1),t,n);case`list`:return vX(e.slice(1),t,n);case`info`:case`read`:return MX(e[0],e[1],t);case`search`:return BX(e,n);default:return null}}function zX(e,t,n){return B(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return BY();let a=await RX(r,e,t,n);if(a)return a;let o=jX(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return BY();if(o.sourceRef.startsWith(`tessl:`))return VX(o.sourceRef,o.force,e,t);let s=kY(o.sourceRef);if(s)return FY(s.hostname,s.task,e,t,o.force);let c=po(o.sourceRef);return c?LX(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 BX(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?CX(a,t,i):BY()}async function VX(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1807
1807
|
`,exitCode:1};let a=await bX(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await eo(r);return ho(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function HX(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1808
1808
|
|
|
@@ -2223,7 +2223,7 @@ Examples:
|
|
|
2223
2223
|
`;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+=`
|
|
2224
2224
|
`;return t}async function x1(e,t){let n=V(e.slice(1),{});if(`error`in n)return v1(n.error);if(!t()){let e=await d1();if(!e)return m1(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2225
2225
|
`,stderr:``,exitCode:0}:{stdout:b1(t),stderr:``,exitCode:0}}let{ok:r,data:i}=await g1(`GET`,``);if(!r)return{stdout:``,stderr:`crontask: failed to list: ${i.error??`unknown error`}\n`,exitCode:1};let a=i;return a.length===0?{stdout:`No active cron tasks
|
|
2226
|
-
`,stderr:``,exitCode:0}:{stdout:b1(a),stderr:``,exitCode:0}}async function S1(e,t){let n=e[0],r=V(e.slice(1),{});if(`error`in r)return v1(r.error);let i=r.positionals[0];if(!i)return{stdout:``,stderr:`crontask: ${n} requires an ID\n`,exitCode:1};if(!t()){let e=await d1();return e?await e.deleteCronTask(i)?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:m1(`delete`)}let{ok:a,status:o,data:s}=await g1(`DELETE`,`/${i}`);return a?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:o===404?{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${s.error??`unknown error`}\n`,exitCode:1}}function C1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return B(`crontask`,async(e,n)=>{let r=e[0];if(!r||ui(e,{valueFlags:_1}))return h1();try{switch(r){case`create`:return await y1(e,n.env,t);case`list`:return await x1(e,t);case`delete`:case`kill`:return await S1(e,t);default:return{stdout:``,stderr:`crontask: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function w1(e){return B(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2226
|
+
`,stderr:``,exitCode:0}:{stdout:b1(a),stderr:``,exitCode:0}}async function S1(e,t){let n=e[0],r=V(e.slice(1),{});if(`error`in r)return v1(r.error);let i=r.positionals[0];if(!i)return{stdout:``,stderr:`crontask: ${n} requires an ID\n`,exitCode:1};if(!t()){let e=await d1();return e?await e.deleteCronTask(i)?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:m1(`delete`)}let{ok:a,status:o,data:s}=await g1(`DELETE`,`/${i}`);return a?{stdout:`Deleted cron task "${i}"\n`,stderr:``,exitCode:0}:o===404?{stdout:``,stderr:`crontask: task "${i}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${s.error??`unknown error`}\n`,exitCode:1}}function C1(e={}){let t=e.hasLocalNodeServer??(()=>!1);return B(`crontask`,async(e,n)=>{let r=e[0];if(!r||ui(e,{valueFlags:_1}))return h1();try{switch(r){case`create`:return await y1(e,n.env,t);case`list`:return await x1(e,t);case`delete`:case`kill`:return await S1(e,t);default:return{stdout:``,stderr:`crontask: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function w1(e){return B(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-BiC8nBGs.js`);return r(e,t,n)})}const T1=`slicc-fs`;async function E1(){try{let e=globalThis.indexedDB;if(!e)return!1;let t=e.databases;return typeof t!=`function`||(await t.call(e)).some(e=>e.name===T1)}catch{return!0}}async function D1(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(T1)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function O1(){if(!await E1())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await D1();return e===`deleted`?{kind:`deleted`,message:`legacy slicc-fs IDB deleted`}:e===`blocked`?{kind:`blocked`,message:`legacy slicc-fs IDB delete blocked by another connection — close other tabs and retry`}:{kind:`error`,message:`legacy slicc-fs IDB delete failed`}}function k1(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2227
2227
|
|
|
2228
2228
|
Usage:
|
|
2229
2229
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -2715,7 +2715,7 @@ Options:
|
|
|
2715
2715
|
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function C4(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!Nee(e))throw e}t.sessionDirsCreated=!0}}async function Sue(e,t,n,r){try{return await e.withTab(n,async e=>{let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:u}=await l(e),d={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:u,content:o,timestamp:Date.now()};r.snapshots.set(n,d);let f=[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
2716
2716
|
`),p=`/.playwright/snapshots/page-${Xi(new Date)}.yml`;return await t.writeFile(p,f),p})}catch{return null}}async function Cue(e,t,n){await C4(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
|
|
2717
2717
|
`)+`
|
|
2718
|
-
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function w4(){return import(`./snapshot-features-
|
|
2718
|
+
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}function w4(){return import(`./snapshot-features-DQZYYxXB.js`)}async function wue(e,t,n,r){let i=await e.getAccessibilityTreeForFrame(r.frameId),a=new Map,o=new Map,s=new Map,l=c(i,a,o,{value:0},``,`f1`);for(let e of a.keys())s.set(e,r.frameId);let u=l.join(`
|
|
2719
2719
|
`);return t.snapshots.set(n,{url:r.url,title:r.name,refToSelector:a,refToBackendNodeId:o,refToFrameId:s,content:u,timestamp:Date.now()}),u}async function Tue(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() {
|
|
2720
2720
|
this.scrollIntoView({ block: 'center' });
|
|
2721
2721
|
const r = this.getBoundingClientRect();
|
|
@@ -2793,7 +2793,7 @@ Options:
|
|
|
2793
2793
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
2794
2794
|
return el.files.length;
|
|
2795
2795
|
})()`,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`,Pue],[`state-load`,Fue],[`console`,Zce],[`requests`,cue],[`request`,lue],[`request-headers`,uue],[`request-body`,due],[`response-headers`,fue],[`response-body`,pue],[`mousemove`,Nle],[`mousedown`,Ple],[`mouseup`,Fle],[`mousewheel`,Ile],[`drop`,Lle],[`route`,yue],[`route-list`,bue],[`unroute`,xue],[`generate-locator`,ale],[`highlight`,ole]]);function Xue(){let e=(Zi.string??[]).map(e=>`--${e}`),t=new Set(Zi.boolean??[]);for(let[e,n]of Object.entries(Zi.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 Zue(e){return e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e)}function Que(e){return{...e,bool:[...e.bool??[],`--_noiframes`],value:[...e.value??[],`--_noiframes`]}}const F4=2e3;function $ue(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 ede(e,t,n,r){if(!t||typeof e.getTabLockStats!=`function`)return r;let i=e.getTabLockStats(),a=i.totalWaitMs-t.totalWaitMs;if(a<F4)return r;let o=(a/1e3).toFixed(1),s=n&&t.tabWaitMs!==void 0?e.getTabLockStats(n).tabWaitMs-t.tabWaitMs:0,c=`note: browser bridge contended — lock waits totaled ${o}s while this command ran, ${s>=F4?`${(s/1e3).toFixed(1)}s of it waiting on this tab (--tab=${n})`:`all of it waiting on the bridge, not on this tab`} (queue depth ${i.queueDepth}). Commands on the same tab serialize; commands on different tabs run in parallel — stagger callers on THIS tab, or give each caller its own tab.
|
|
2796
|
-
`;return{...r,stderr:r.stderr+c}}async function tde(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Iee(e,t.tab,n):null)??r}\n`,exitCode:1}}function I4(e,t,n){return{stdout:``,stderr:`${e} ${t}: ${n===void 0?`aborted: the caller stopped waiting for it`:n instanceof Error?n.message:String(n)}\n`,exitCode:130}}async function nde(e,t,n){let r=Yue.get(t);if(!r)return{stdout:``,stderr:`Unknown command: ${t}\nRun "playwright-cli help" for usage.\n`,exitCode:1};let{signal:i}=n;try{let a=await r(n);return i?.aborted?I4(e,t,void 0):a}catch(r){return i?.aborted?I4(e,t,r):await tde(n.browser,n.flags,r)}}async function rde(e,t,n,r){let i=V(Zue(n),Que(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Fee(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-
|
|
2796
|
+
`;return{...r,stderr:r.stderr+c}}async function tde(e,t,n){let r=n instanceof Error?n.message:String(n);return{stdout:``,stderr:`Error: ${(t.tab?await Iee(e,t.tab,n):null)??r}\n`,exitCode:1}}function I4(e,t,n){return{stdout:``,stderr:`${e} ${t}: ${n===void 0?`aborted: the caller stopped waiting for it`:n instanceof Error?n.message:String(n)}\n`,exitCode:130}}async function nde(e,t,n){let r=Yue.get(t);if(!r)return{stdout:``,stderr:`Unknown command: ${t}\nRun "playwright-cli help" for usage.\n`,exitCode:1};let{signal:i}=n;try{let a=await r(n);return i?.aborted?I4(e,t,void 0):a}catch(r){return i?.aborted?I4(e,t,r):await tde(n.browser,n.flags,r)}}async function rde(e,t,n,r){let i=V(Zue(n),Que(r));if(`error`in i)return{answer:{stdout:``,stderr:`${e} ${t}: ${i.error}\n`,exitCode:1}};let a;try{({flags:a}=Fee(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-ChVsqTeK.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 ide(e,t,n){let r=t?Mee(t,n):null,i=Xue();return B(e,async(a,o)=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`){let{formatHelp:t}=await import(`./help-ChVsqTeK.js`);return{stdout:t(e)+`
|
|
2797
2797
|
`,stderr:``,exitCode:0}}let s=a[0],c=a.slice(1),l=await rde(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=$ue(t,f),m=await nde(e,s,{browser:t,fs:n,state:r,positional:u,flags:d,scratchDir:za(o.env),onTab:(e,n)=>t.withTab(e,n,{signal:o.signal}),signal:o.signal}),h=d.tab??null,g=null;na.has(s)&&m.exitCode===0&&h&&(g=await Sue(t,n,h,r));try{await Cue(n,r,{command:s,args:c,result:m,snapshotPath:g,targetId:h})}catch{}return ede(t,p,f,m)})}const ade=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`,`file`,`rmdir`,`rsync`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`,`patch`,`column`,`comm`,`egrep`,`fgrep`,`expand`,`unexpand`,`fold`,`join`,`nl`,`od`,`paste`,`rev`,`split`,`strings`,`tac`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`,`gunzip`,`gzip`,`zcat`]],[`Media`,[`convert`,`magick`,`pdftoppm`,`pdftocairo`,`pdftotext`,`ffmpeg`,`ffprobe`,`screencapture`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,`echo.printf.env.printenv.export.alias.unalias.history.clear.true.false.bash.sh.commands.which.uname.man.host.oauth-token.secret.nuke.models.local-llm.cost.hostname.whoami.id.help.sleep.time.timeout.oauth-domain`.split(`.`)],[`Data processing`,[`xargs`,`jq`,`base64`,`date`,`expr`,`seq`]],[`Hashes`,[`md5sum`,`sha1sum`,`sha256sum`]],[`Network`,[`curl`,`curlwright`,`wget`,`dig`,`websocat`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`jsh`,`python`,`python3`,`sqlite3`]],[`Virtualization`,[`v86`]],[`Build tools`,[`tsc`,`test`,`esbuild`,`biome`]],[`Packages`,[`ipk`,`hf`,`npm`,`i`,`ipx`,`npx`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...ea,`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)`,[...DZ]]]);function ode(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:
|
|
2798
2798
|
`);let a=[];for(let[e,t]of ade){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(`
|
|
2799
2799
|
`)+`
|
|
@@ -3051,7 +3051,7 @@ Common base URLs:
|
|
|
3051
3051
|
`)+`
|
|
3052
3052
|
`,stderr:``,exitCode:0}}function lpe(e,t){let n=t.models.length;return{stdout:[`✓ ${e} (${J3(t.runtime,!1)})`,` Saved ${n} model${n===1?``:`s`} to Settings:`,...Y3(t.models)].join(`
|
|
3053
3053
|
`)+`
|
|
3054
|
-
`,stderr:``,exitCode:0}}function upe(){return B(q3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:ope(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
3054
|
+
`,stderr:``,exitCode:0}}function upe(){return B(q3,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:ope(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-BxL33fhK.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(q3);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
3055
3055
|
`,exitCode:1};let c=await a(s,t(q3)??void 0);if(!c.ok)return spe(s,c);if(o===`discover`){let e=n(q3)??``;return i(q3,e,s,c.models.join(`, `)),lpe(s,c)}return cpe(s,c)})}function dpe(){return{stdout:`usage: man <topic>
|
|
3056
3056
|
|
|
3057
3057
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3089,20 +3089,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3089
3089
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3090
3090
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3091
3091
|
short name resolves on the PATH.
|
|
3092
|
-
`);let n=V(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length<2)return $3(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return $3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return $3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3092
|
+
`);let n=V(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length<2)return $3(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return $3(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return $3(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CCdCzj9v.js`).then(e=>e.r);if(await a(i,t.fs))return $3(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BOSdqiLb.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 vpe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>a6(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await Lpe(i,t);let m=await c6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BZm95oFT.js`);e({name:i,serverUrl:r,auth:u})}return Q3([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${Z3}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3093
3093
|
`)+`
|
|
3094
|
-
`)}async function vpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3095
|
-
`);let n=V(e,{});if(`error`in n)return e6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3094
|
+
`)}async function vpe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t),c=await Fpe(r.oauthFetchImpl),l=r.oauthLauncher??await o6(),u=await i(e,n,c);X3.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await qo(qt()),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 ype(e,t){if(ui(e))return Q3(`usage: mcp list
|
|
3095
|
+
`);let n=V(e,{});if(`error`in n)return e6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-BZm95oFT.js`);await r();let{listServers:i}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),a=await i(t.fs),o=Object.keys(a).sort();if(o.length===0)return Q3("No MCP servers configured. Use `mcp add <url> <name>`.\n");let s=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of o){let t=a[e];s.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return Q3(t6(s))}function t6(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
|
|
3096
3096
|
`)+`
|
|
3097
3097
|
`}async function bpe(e,t){if(ui(e))return Q3(`usage: mcp search <query>
|
|
3098
3098
|
|
|
3099
3099
|
Case-insensitive substring search across the cached tools of every
|
|
3100
3100
|
registered MCP server. Matches tool name OR description and prints a
|
|
3101
3101
|
table of (server, tool, description, match-field) rows.
|
|
3102
|
-
`);let n=V(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length===0)return $3(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-
|
|
3103
|
-
`);let n=V(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-
|
|
3102
|
+
`);let n=V(e,{});if(`error`in n)return e6(n.error);if(n.positionals.length===0)return $3(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-BZm95oFT.js`);await a();let{listServers:o}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),s=await o(t.fs),c=Object.keys(s).sort();if(c.length===0)return Q3("No MCP servers configured. Use `mcp add <url> <name>`.\n");let l=[];for(let e of c){let t=s[e].tools??[];for(let n of t){let t=n.description??``,r=n.name.toLowerCase().includes(i),a=t.toLowerCase().includes(i);if(!r&&!a)continue;let o=r&&a?`name+description`:r?`name`:`description`;l.push({server:e,tool:n.name,description:t,match:o})}}if(l.length===0)return Q3(`No tools matched "${r}".\n`);l.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let u=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of l)u.push([e.server,e.tool,xpe(e.description),e.match]);return Q3(t6(u))}function xpe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Spe(e,t){if(e.length===0||ui(e))return e.length===0?$3(`mcp delete: expected <name>`):Q3(`usage: mcp delete <name>
|
|
3103
|
+
`);let n=V(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-BZm95oFT.js`);await i(r);let{deleteServer:o}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),s=await o(r,t.fs);await Rpe(r,t),await zpe(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t);t().some(e=>e.providerId===c)&&(await e(c),l=!0)}catch(e){X3.warn(`mcp delete: OAuth removal failed`,{providerId:c,error:e instanceof Error?e.message:String(e)})}let u=a(r);return!s&&!l&&!u?$3(`mcp delete: no server, alias, or account found for "${r}"`):Q3([`Removed MCP server "${r}"`,` servers.json: ${s?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${l?`removed`:`not present`}`,` provider: ${u?`unregistered`:`not registered`}`].join(`
|
|
3104
3104
|
`)+`
|
|
3105
|
-
`)}async function Cpe(e,t){if(e.length===0)return $3(`mcp invoke: expected <name>`);if(ui(e.slice(0,1)))return Q3(Tpe());let n=V([e[0]],{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-
|
|
3105
|
+
`)}async function Cpe(e,t){if(e.length===0)return $3(`mcp invoke: expected <name>`);if(ui(e.slice(0,1)))return Q3(Tpe());let n=V([e[0]],{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-BZm95oFT.js`);await a(r);let{getServer:o}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),s=await o(r,t.fs);if(!s)return $3(`mcp invoke: unknown server "${r}" (run \`mcp add <url> ${r}\` first)`);let c=s.tools??[];if(i.length===0||ui(i.slice(0,1)))return Q3(Epe(r,s,c));let l=V([i[0]],{});if(`error`in l)return e6(l.error);let u=l.positionals[0];if(!u)return $3(`mcp invoke: expected <tool>`);let d=c.find(e=>e.name===u);if(!d)return $3(`mcp invoke: unknown tool "${u}" on "${r}" (run \`${r}\` to list tools)`);let{timeoutMs:f,remaining:p,warnings:m}=wpe(i.slice(1));if(ui(p))return Q3(Dpe(r,d));let h=Ope(p,d.inputSchema);if(!h.ok)return $3(`mcp invoke: ${h.error}`);let{McpClient:g}=await import(`./client-BOSdqiLb.js`).then(e=>e.n),_=new g({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>a6(r):void 0,...f===void 0?{}:{timeoutMs:f}});await _.initialize();let v=Mpe(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function wpe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=n6(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=n6(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function n6(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function Tpe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3106
3106
|
|
|
3107
3107
|
mcp invoke <name> List tools on <name>.
|
|
3108
3108
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3132,7 +3132,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3132
3132
|
|
|
3133
3133
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3134
3134
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3135
|
-
`);let n=V(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3135
|
+
`);let n=V(e,{});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-BZm95oFT.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),s=await a(r,t.fs);if(!s)return $3(`mcp refresh: unknown server "${r}"`);let{McpClient:c,McpAuthRequiredError:l}=await import(`./client-BOSdqiLb.js`).then(e=>e.n),u=new c({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>a6(r):void 0});try{await u.initialize()}catch(e){if(e instanceof l)return $3(`mcp refresh: server "${r}" returned 401 — token may have expired. Run \`mcp auth ${r}\` to re-authenticate.`);throw e}let d=await u.toolsList(),f=await u.appsList();await o(r,{...s,protocolVersion:u.getNegotiatedProtocolVersion(),tools:d,apps:f,lastRefreshedAt:new Date().toISOString()},t.fs);let p=await c6(r,f,t);return Q3(`Refreshed "${r}" — tools: ${d.length}, apps: ${f.length} (${p} sprinkle${p===1?``:`s`})\n`)}async function Ppe(e,t){if(ui(e))return Q3(`usage: mcp auth <name> [--silent | --interactive]
|
|
3136
3136
|
|
|
3137
3137
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3138
3138
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3144,7 +3144,7 @@ Options:
|
|
|
3144
3144
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3145
3145
|
directly. Use after revoking a refresh token or
|
|
3146
3146
|
when the AS no longer accepts the cached one.
|
|
3147
|
-
`);let n=V(e,{bool:mpe});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp auth: expected <name>`);let i=n.bools.has(`--silent`)||n.bools.has(`-s`),a=n.bools.has(`--interactive`)||n.bools.has(`-i`);if(i&&a)return $3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3147
|
+
`);let n=V(e,{bool:mpe});if(`error`in n)return e6(n.error);let r=n.positionals[0];if(!r)return $3(`mcp auth: expected <name>`);let i=n.bools.has(`--silent`)||n.bools.has(`-s`),a=n.bools.has(`--interactive`)||n.bools.has(`-i`);if(i&&a)return $3(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BZm95oFT.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-CCdCzj9v.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return $3(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return $3(`mcp auth: server "${r}" does not use OAuth`);if(!s)return $3(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-CKUtckcc.js`).then(e=>e.r),f=d(u);if(!f)return $3(`mcp auth: provider "${u}" is not registered`);if(a)return await i6(r,f,t);if(!f.onSilentRenew)return i?$3(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await i6(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return $3(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);X3.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?Q3(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?$3(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await i6(r,f,t)}async function i6(e,t,n){if(!t.onOAuthLogin)return $3(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await o6(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?Q3(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):$3(`mcp auth: interactive login for "${e}" did not complete`)}async function a6(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-CKUtckcc.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){X3.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function o6(){let{createOAuthLauncher:e}=await import(`./oauth-service-BZl-9EoE.js`);return e()}async function Fpe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-B57RqgUb.js`).then(e=>e.i),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function s6(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BjSQWu2g.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 Ipe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3148
3148
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3149
3149
|
const { promisify } = require('util');
|
|
3150
3150
|
const { exec } = require('child_process');
|
|
@@ -3173,7 +3173,7 @@ try {
|
|
|
3173
3173
|
if (stdout) process.stdout.write(stdout);
|
|
3174
3174
|
if (stderr) process.stderr.write(stderr);
|
|
3175
3175
|
process.exit(exitCode);
|
|
3176
|
-
`}async function Lpe(e,t){let n=await s6(t.fs);await n.mkdir(Z3,{recursive:!0}),await n.writeFile(`${Z3}/${e}.jsh`,Ipe(e)),t.scriptCatalog?.invalidateJsh()}async function Rpe(e,t){let n=await s6(t.fs),r=`${Z3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){X3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function zpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3176
|
+
`}async function Lpe(e,t){let n=await s6(t.fs);await n.mkdir(Z3,{recursive:!0}),await n.writeFile(`${Z3}/${e}.jsh`,Ipe(e)),t.scriptCatalog?.invalidateJsh()}async function Rpe(e,t){let n=await s6(t.fs),r=`${Z3}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){X3.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function zpe(e,t){let{removeAppSprinkles:n}=await import(`./apps-C8k6TOsm.js`);await n(e,t.fs)}async function c6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-C8k6TOsm.js`);return(await r(e,t,n.fs)).length}catch(t){return X3.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function l6(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function u6(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e,r=`B`;for(let e of t){if(n<1024)break;n/=1024,r=e}return`${n.toFixed(1)} ${r}`}function Bpe(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 Vpe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function Hpe(e){if(e[0]===`--help`||e[0]===`-h`||e[0]===`help`)return{help:!0};let t=!1;for(let n of e){if(n!==`--json`)return{error:`unknown option '${n}' — see \`meminfo --help\``};t=!0}return{help:!1,json:t}}function Upe(e){let t=[`total: ${u6(e.bytes)}`],n=[...e.breakdown].filter(e=>e.bytes>0).sort((e,t)=>t.bytes-e.bytes);if(n.length>0){t.push(``,`BYTES TYPES ATTRIBUTION`);for(let e of n)t.push(`${u6(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${Bpe(e)}`)}return`${t.join(`
|
|
3177
3177
|
`)}\n`}function Wpe(e={}){return B(`meminfo`,async t=>{let n=Hpe(t);if(`error`in n)return l6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3178
3178
|
|
|
3179
3179
|
Usage:
|
|
@@ -3200,7 +3200,7 @@ Options:
|
|
|
3200
3200
|
-h, --help Show this help message
|
|
3201
3201
|
`}function tme(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function h6(e){return`$${e.toFixed(2)}`}const nme=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function rme(e){let t=`${e.id} ${e.name??``}`;return!nme.test(t)}function ime(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 ame(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),ime(t)??t.replace(/-[\d.]+$/,``)}function ome(e){let t=new Map;for(let n of e){let e=ame(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function sme(e,t,n,r,i){let a=i?$pe(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 cme(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${h6(e.cost.input)} / ${h6(e.cost.output)}`,a=`${tme(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(`
|
|
3202
3202
|
`)+`
|
|
3203
|
-
`}function lme(e){let t=V(e,{bool:qpe,value:f6});return`error`in t?t:{jsonMode:t.bools.has(`--json`),allMode:t.bools.has(`--all`),allVersions:t.bools.has(`--all-versions`),forceRefresh:t.bools.has(`--refresh`),noBenchmarks:t.bools.has(`--no-benchmarks`),explicitProvider:t.values.get(`--provider`)}}function ume(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 dme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(rme);if(o.length===0)return[];let s=o.map(e=>sme(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=ome(s)),s}function fme(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 pme(e,t){if(ui(e,{valueFlags:f6}))return{stdout:eme(),stderr:``,exitCode:0};let n=lme(e);if(`error`in n)return p6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3203
|
+
`}function lme(e){let t=V(e,{bool:qpe,value:f6});return`error`in t?t:{jsonMode:t.bools.has(`--json`),allMode:t.bools.has(`--all`),allVersions:t.bools.has(`--all-versions`),forceRefresh:t.bools.has(`--refresh`),noBenchmarks:t.bools.has(`--no-benchmarks`),explicitProvider:t.values.get(`--provider`)}}function ume(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 dme(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(rme);if(o.length===0)return[];let s=o.map(e=>sme(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=ome(s)),s}function fme(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 pme(e,t){if(ui(e,{valueFlags:f6}))return{stdout:eme(),stderr:``,exitCode:0};let n=lme(e);if(`error`in n)return p6(`models: ${n.error}`);let r=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t);if(r.getAccounts().length===0)return p6(`No provider accounts configured. Run the provider settings to add one.
|
|
3204
3204
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await Qpe(t,n.forceRefresh);e.length>0&&(l=e)}let u=ume(r,n,s);if(`error`in u)return p6(u.error);let d=[],f=[];for(let e of u){let t=dme(r,e,a,o,l,n.allVersions);if(t.length===0){if(!n.allMode)return p6(`No models available for provider ${e}.\n`);continue}if(d.push(...t),!n.jsonMode){let n=r.getProviderConfig(e);f.push(cme(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3205
3205
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3206
3206
|
`),f.push(fme(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3258,7 +3258,7 @@ Examples:
|
|
|
3258
3258
|
`)}\n`,stderr:``,exitCode:0}}async function Mme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3259
3259
|
`,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 Nme(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3260
3260
|
`,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 Pme(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>
|
|
3261
|
-
`,exitCode:1}}async function Fme(e,t,n,r){switch(t){case`list`:return jme(e,n);case`add`:return Mme(e,n,r);case`remove`:return Nme(e,n,r);case`clear`:return Pme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${b6()}`,exitCode:1}}}function Ime(){return B(`oauth-domain`,async e=>{if(e.length===0||ui(e))return{stdout:b6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return x6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3261
|
+
`,exitCode:1}}async function Fme(e,t,n,r){switch(t){case`list`:return jme(e,n);case`add`:return Mme(e,n,r);case`remove`:return Nme(e,n,r);case`clear`:return Pme(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${b6()}`,exitCode:1}}}function Ime(){return B(`oauth-domain`,async e=>{if(e.length===0||ui(e))return{stdout:b6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return x6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-B3TDSGgR.js`).then(e=>e.t);try{return await Fme(a,n,r,i)}catch(e){return x6(e instanceof Error?e.message:String(e))}})}function Lme(){return B(`oauth-token`,async(e,t)=>{let{runOAuthToken:n}=await import(`./run-BoLpdccP.js`);return n(e,t)})}const Rme=[`--download`,`-d`,`--view`,`-v`],S6=[`--size`],C6={low:256,medium:768,high:1536};function w6(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
3262
3262
|
|
|
3263
3263
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
3264
3264
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -3284,7 +3284,7 @@ Examples:
|
|
|
3284
3284
|
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=EN(e,await Ta(t.fs,i?e:Aa(e))),o;try{o=await r(a)}catch(e){return D6(`${e instanceof Error?e.message:String(e)}\n`)}return E6(`opened ${e} → ${a}${O6(o)}`)}async function Qme(e,t,n,r){if(!Da(e)&&e.endsWith(`.shtml`)&&t.fs)return qme(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return D6(`open: browser APIs are unavailable in this environment
|
|
3285
3285
|
`);if(Da(e))return Jme(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?Yme(e,i,t,n.sizeSpec):n.download?Xme(e,i,t,r.hasDom):Zme(i,t,r.canOpenWindow,r.openExternal)}function $me(e){return B(`open`,async(t,n)=>{if(t.length===0||ui(t,{valueFlags:S6}))return w6();let r=Gme(t);if(`error`in r)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:i,view:a,sizeSpec:o,targets:s}=r;if(s.length===0)return w6();let c=globalThis.__slicc_sprinkleManager,l=typeof window<`u`&&typeof document<`u`,d=l?null:u(),f={canOpenWindow:!!e||l||!!d,hasDom:l,sprinkleManager:c,openExternal:Kme(e,l,d)},p=[];for(let e of s){let t=await Qme(e,n,{view:a,download:i,sizeSpec:o},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
3286
3286
|
`)+`
|
|
3287
|
-
`,stderr:``,exitCode:0}})}function ehe(){return B(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-
|
|
3287
|
+
`,stderr:``,exitCode:0}})}function ehe(){return B(`patch`,async(e,t)=>{let{runPatch:n}=await import(`./run-BGcMWlan.js`);return n(e,t)})}function k6(e=`pdftk`){return B(e,async(t,n)=>{let{runPdftk:r}=await import(`./run-ChkY2Agc.js`);return r(e,t,n)})}function the(){return{stdout:`usage: pdftoppm [options] <input.pdf> [output-prefix]
|
|
3288
3288
|
|
|
3289
3289
|
Rasterize PDF pages to images. Writes <prefix>-<n>.<ext> per page, where <n>
|
|
3290
3290
|
is zero-padded to the digit width of the last page (out-1.png for a 9-page
|
|
@@ -3344,7 +3344,7 @@ Examples:
|
|
|
3344
3344
|
plugin list
|
|
3345
3345
|
plugin info my-plugin
|
|
3346
3346
|
plugin remove my-plugin
|
|
3347
|
-
`}function phe(e={}){return B(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return N6(fhe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await hhe(i,a,e);case`list`:case`ls`:return await yhe(i,e);case`info`:return await bhe(i,e);case`validate`:return await xhe(i,a,e,za(n?.env));case`remove`:case`rm`:case`delete`:return await She(i,e);default:return P6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return P6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function I6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3347
|
+
`}function phe(e={}){return B(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return N6(fhe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await hhe(i,a,e);case`list`:case`ls`:return await yhe(i,e);case`info`:return await bhe(i,e);case`validate`:return await xhe(i,a,e,za(n?.env));case`remove`:case`rm`:case`delete`:return await She(i,e);default:return P6(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return P6(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function I6(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-BjSQWu2g.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return t.create({dbName:n})}async function L6(e,t,n){let r=Che(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-CB0ldULv.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 mhe(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function R6(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${M6}/${t.map(mhe).join(`--`)}`}async function z6(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-DwdgFfY8.js`).then(e=>e.i),s=await i(e.owner,e.repo,r,e.branch);if(s.status===`error`)return`failed to download ${e.display}: ${s.message}`;let c=a(s.files),l=e.path?e.path.replace(/^\/|\/$/g,``)+`/`:``;if(!c[`${l}plugin.json`])return`no plugin.json found at ${e.display} — not an Agent Plugins package`;try{await n.rm(t,{recursive:!0})}catch{}return await n.mkdir(t,{recursive:!0}),(await o(c,l,t,n,!1)).length===0?`no files found at ${e.display}`:null}async function B6(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function hhe(e,t,n){if(ui(e))return N6(`usage: plugin install <path|repo>
|
|
3348
3348
|
|
|
3349
3349
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3350
3350
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3355,19 +3355,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3355
3355
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3356
3356
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3357
3357
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3358
|
-
`);let r=F6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return P6(`plugin install: expected <path|repo>`);let i=await I6(n),a=await L6(r.positionals[0],t,i);if(a.kind===`error`)return P6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return P6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=R6(a.ref),s=a.ref.display;let e=await z6(a.ref,o,i,n.fetch);if(e)return P6(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-Dw-TPPKt.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await B6(i,o),P6(`plugin install: plugin at ${s??o} was rejected:\n${V6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3358
|
+
`);let r=F6(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return P6(`plugin install: expected <path|repo>`);let i=await I6(n),a=await L6(r.positionals[0],t,i);if(a.kind===`error`)return P6(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return P6(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=R6(a.ref),s=a.ref.display;let e=await z6(a.ref,o,i,n.fetch);if(e)return P6(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-Dw-TPPKt.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await B6(i,o),P6(`plugin install: plugin at ${s??o} was rejected:\n${V6(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-BXnbNdZV.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await B6(i,o),P6(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await vhe(u,n),g=await _he(d,m?.mcpServerNames,h.registered,n);return await p(d,{root:o,version:u.manifest.version,description:u.manifest.description,installedAt:new Date().toISOString(),mcpServerNames:h.registered,...s?{source:s}:{}},n.fs),N6(ghe(u,h,g,s??o,l.diagnostics))}function ghe(e,t,n,r,i){let a=e.manifest.name,o=t.registered,s=e.mcp.servers.filter(e=>e.status!==`supported`),c=[`Installed agent plugin "${a}"${e.manifest.version?` v${e.manifest.version}`:``} from ${r}`,` skills: ${e.skills.length}${e.skills.length>0?` (${e.skills.map(e=>e.name).join(`, `)})`:``}`,` mcp: ${o.length} registered${o.length>0?` (${o.join(`, `)})`:``}${s.length>0?`, ${s.length} skipped`:``}${n>0?`, ${n} removed from previous install`:``}`];return t.conflicts.length>0&&c.push(` warning: not bridged — MCP server name(s) already in use and not owned by this plugin: ${t.conflicts.join(`, `)} (remove them with \`mcp remove\` first)`),i.length>0&&c.push(`Diagnostics:`,V6(i)),c.join(`
|
|
3359
3359
|
`)+`
|
|
3360
|
-
`}async function _he(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-
|
|
3361
|
-
`);let n=F6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3360
|
+
`}async function _he(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-CCdCzj9v.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 vhe(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-CCdCzj9v.js`).then(e=>e.r),{McpClient:a}=await import(`./client-BOSdqiLb.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 yhe(e,t){if(ui(e))return N6(`usage: plugin list
|
|
3361
|
+
`);let n=F6(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-BXnbNdZV.js`),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return N6("No agent plugins installed. Use `plugin install <path>`.\n");let o=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of a){let t=i[e];o.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let s=o[0].map((e,t)=>Math.max(...o.map(e=>e[t].length)));return N6(o.map(e=>e.map((e,t)=>e.padEnd(s[t])).join(` `)).join(`
|
|
3362
3362
|
`)+`
|
|
3363
3363
|
`)}async function bhe(e,t){if(ui(e))return N6(`usage: plugin info <name>
|
|
3364
|
-
`);let n=F6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-
|
|
3364
|
+
`);let n=F6(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-BXnbNdZV.js`),a=await i(r,t.fs);if(!a)return P6(`plugin info: no installed plugin named "${r}"`);let o=await I6(t),{loadPluginFromDirectory:s}=await import(`./loader-Dw-TPPKt.js`),c=await s(o,a.root);if(!c.ok)return P6(`plugin info: plugin at ${a.root} no longer loads:\n${V6(c.diagnostics)}`);let{plugin:l}=c,u=l.manifest,d=[`${u.name}${u.version?` v${u.version}`:``}`,...u.description?[` ${u.description}`]:[],` root: ${l.root}`,...u.license?[` license: ${u.license}`]:[],...u.homepage?[` home: ${u.homepage}`]:[],``,`Skills (${l.skills.length}):`,...l.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${l.mcp.servers.length}):`,...l.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return c.diagnostics.length>0&&d.push(``,`Diagnostics:`,V6(c.diagnostics)),N6(d.join(`
|
|
3365
3365
|
`)+`
|
|
3366
3366
|
`)}async function xhe(e,t,n,r){if(ui(e))return N6(`usage: plugin validate <path|repo>
|
|
3367
3367
|
`);let i=F6(`validate`,e);if(!(`ok`in i))return i;if(i.positionals.length<1)return P6(`plugin validate: expected <path|repo>`);let a=await I6(n),o=await L6(i.positionals[0],t,a);if(o.kind===`error`)return P6(`plugin validate: ${o.message}`);let s,c=null;if(o.kind===`github`){if(!n.fetch)return P6(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);c=`${r}/.plugin-validate/${R6(o.ref).split(`/`).pop()}`;let e=await z6(o.ref,c,a,n.fetch);if(e)return P6(`plugin validate: ${e}`);s=c}else s=o.root;let{loadPluginFromDirectory:l}=await import(`./loader-Dw-TPPKt.js`),u;try{u=await l(a,s)}finally{c&&await B6(a,c)}if(!u.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${V6(u.diagnostics)}\n`,exitCode:1};let{plugin:d}=u,f=d.mcp.servers.filter(e=>e.status===`supported`).length,p=[`plugin validate: OK — "${d.manifest.name}"${d.manifest.version?` v${d.manifest.version}`:``}`,` skills: ${d.skills.length}`,` mcp servers: ${f} supported, ${d.mcp.servers.length-f} skipped (mcp.json ${d.mcp.status})`];return u.diagnostics.length>0&&p.push(`Diagnostics:`,V6(u.diagnostics)),N6(p.join(`
|
|
3368
3368
|
`)+`
|
|
3369
3369
|
`)}async function She(e,t){if(ui(e))return N6(`usage: plugin remove <name>
|
|
3370
|
-
`);let n=F6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-
|
|
3370
|
+
`);let n=F6(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return P6(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-BXnbNdZV.js`),o=await i(r,t.fs);if(!o)return P6(`plugin remove: no installed plugin named "${r}"`);let s=0;if(o.mcpServerNames&&o.mcpServerNames.length>0){let{deleteServer:e,getServer:n}=await import(`./store-CCdCzj9v.js`).then(e=>e.r);for(let i of o.mcpServerNames)(await n(i,t.fs))?.pluginOrigin===r&&await e(i,t.fs)&&(s+=1)}await a(r,t.fs);let c=o.root.startsWith(`${M6}/`);return c&&await B6(await I6(t),o.root),N6([`Removed agent plugin "${r}"`,` registry: removed`,` mcp servers: ${s} removed`,c?` files: removed (${o.root})`:` files: left in place (${o.root})`].join(`
|
|
3371
3371
|
`)+`
|
|
3372
3372
|
`)}function Che(e,t){let n=t.startsWith(`/`)?t:`${e.replace(/\/$/,``)}/${t}`,r=[];for(let e of n.split(`/`))e!==``&&e!==`.`&&(e===`..`?r.pop():r.push(e));return`/${r.join(`/`)}`}function V6(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3373
3373
|
`)}const H6=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],whe=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],The={running:`R`,pending:`S`,exited:`Z`,killed:`K`},Ehe=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],U6=[`-o`,`--columns`];function Dhe(e={}){return B(`ps`,async t=>{if(ui(t,{valueFlags:U6}))return zhe();let n=e.processManager??Ohe();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -3595,7 +3595,7 @@ Examples:
|
|
|
3595
3595
|
`,stderr:``,exitCode:0}}function P_e(e){return e.map(e=>{let t=e.runtime?` (${e.runtime})`:``;return` instance: ${e.runtimeId}${t}`})}function F_e(e){return[...e.map(e=>({name:e,runtimeId:T8})),...A_e()]}async function I_e(e,t){let n=V(t.slice(1),{value:[`--runtime`]});if(`error`in n)return D8(`list`,n.error);let r=n.values.get(`--runtime`);if(r!==void 0&&!O8().includes(r))return D8(`list`,k8(r));await e.refresh();let i=e.available();if(i.length===0)return{stdout:`No .shtml sprinkles found.
|
|
3596
3596
|
`,stderr:``,exitCode:0};let a=new Set(e.opened()),o=F_e([...a]).filter(e=>r===void 0||e.runtimeId===r),s=[];for(let e of i){let t=o.filter(t=>t.name===e.name);if(r!==void 0&&t.length===0)continue;let n=a.has(e.name)?` [open]`:``;s.push(` ${e.name}${n} ${e.title} (${e.path})`),s.push(...P_e(t))}return s.length===0?{stdout:`No sprinkles are open on runtime "${r}".\n`,stderr:``,exitCode:0}:{stdout:s.join(`
|
|
3597
3597
|
`)+`
|
|
3598
|
-
`,stderr:``,exitCode:0}}function L_e(e,t){
|
|
3598
|
+
`,stderr:``,exitCode:0}}function L_e(e,t){return!t||$g(e)?null:(e_(e,t),$g(e)===t?t:null)}async function R_e(e,t,n){let r=V(t.slice(1),{});if(`error`in r)return D8(`open`,r.error);let i=r.positionals[0];if(!i)return D8(`open`,`name required`);let a=Do(void 0,n),o=L_e(i,a);try{a?await e.open(i,void 0,{lickOriginTarget:a}):await e.open(i)}catch(e){return o&&t_(i),D8(`open`,e instanceof Error?e.message:String(e))}return{stdout:`Sprinkle "${i}" opened${o?`; licks route to "${o}"`:``}.\n`,stderr:``,exitCode:0}}function z_e(e,t){let n=V(t.slice(1),{});if(`error`in n)return D8(`close`,n.error);let r=n.positionals[0];return r?(e.close(r),{stdout:`Sprinkle "${r}" closed.\n`,stderr:``,exitCode:0}):D8(`close`,`name required`)}async function B_e(e,t){let n=V(t.slice(1),{});if(`error`in n)return D8(`reload`,n.error);let r=n.positionals[0];if(!r)return D8(`reload`,`name required`);try{return await e.reload(r),{stdout:`Sprinkle "${r}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return D8(`reload`,e instanceof Error?e.message:String(e))}}async function V_e(e,t){let n=V(t.slice(1),{});if(`error`in n)return D8(`refresh`,n.error);await e.refresh();let r=e.available().length;return{stdout:`Found ${r} sprinkle${r===1?``:`s`}.\n`,stderr:``,exitCode:0}}function H_e(e){let t=V(e.slice(1),{value:[`--scoop`],bool:[`--clear`]});if(`error`in t)return D8(`route`,t.error);let n=t.positionals[0];if(!n){let e=bae(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
|
|
3599
3599
|
`,stderr:``,exitCode:0}:{stdout:`Sprinkle routes (applied to every runtime — the leader resolves the
|
|
3600
3600
|
route for follower-forwarded licks too):
|
|
3601
3601
|
`+t.map(([e,t])=>` ${e} -> ${t}`).join(`
|
|
@@ -4995,7 +4995,7 @@ pass --wait to block and print the full result.`,kxe=new Set([`list`,`status`,`s
|
|
|
4995
4995
|
`)}`}}function _Ce({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}:{},...vCe(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 vCe(e,t,n,r,i){let a=`/scoops/${t}/`;return{visiblePaths:r??(e===`private`?[]:n),writablePaths:i??(e===`private`?[a]:[a,`/shared/`])}}async function yCe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return Y7.error(`Auto-feed failed`,{name:n,error:t}),{content:`Scoop "${n}" created as "${r}" but the initial task could not be sent: ${t}. Use feed_scoop to retry.`,isError:!0}}return{content:`Scoop "${n}" created as "${r}" and task sent. It is now working on it.`}}async function bCe(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=Sn(s);if(!f.ok)return{content:f.error,isError:!0};let p=oCe(l);if(!p.ok)return{content:p.content,isError:p.isError};let m=sCe(u);if(!m.ok)return{content:m.content,isError:!0};let h=cCe(r,t.resolveModelSelection);if(!h.ok)return{content:h.content,isError:h.isError};let g=aCe(n),_=Z7(t).find(e=>e.jid!==t.scoop.jid&&e.parentJid!==null&&(e.name===n||e.folder===g));if(_)return{content:`A scoop named "${_.name}" (${_.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let v=Nn(g,t.getScoops().map(e=>e.folder));try{let e=_Ce({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:$n(tr(t.scoop)),canCreateChildren:d===!0}),r=await t.onScoopScoop(e);return Y7.info(`Scoop created`,{name:n,folder:v}),i&&t.onFeedScoop?yCe(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 xCe(e,t){let{scoop_name:n,cross_cone:r}=e;if($7(n)(t.scoop))return{content:`Cannot drop yourself.`,isError:!0};let i=e9(n,t);if(!i)return o9([n],t);let a=r9([i],r,`drop "${n}"`,t);if(a)return a;try{return await t.onDropScoop(i.scoop.jid),Y7.info(`Scoop dropped`,{name:i.scoop.name,folder:i.scoop.folder,relation:i.relation}),{content:`Scoop "${i.scoop.name}" (${i.scoop.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function s9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}async function SCe(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return s9();let{resolved:i,unknown:a}=t9(n,t);return i.length===0?o9(a,t):r9(i,r,`mute these scoops`,t)||(t.onMuteScoops(i.map(e=>e.scoop.jid)),Y7.info(`Scoops muted`,{names:i.map(e=>e.scoop.folder)}),{content:`Muted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`})}function CCe(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 wCe(e,t){let{scoop_names:n,cross_cone:r}=e;if(!Array.isArray(n)||n.length===0)return s9();let{resolved:i,unknown:a}=t9(n,t);if(i.length===0)return o9(a,t);let o=r9(i,r,`unmute these scoops`,t);if(o)return o;let s=i.map(e=>e.scoop.jid),c=new Map(i.map(e=>[e.scoop.jid,e.scoop.folder])),l=await t.onUnmuteScoops(s);Y7.info(`Scoops unmuted`,{names:i.map(e=>e.scoop.folder),stashedCount:l.length});let u=[`Unmuted: ${i.map(e=>e.scoop.folder).join(`, `)}${a.length>0?` (unknown: ${a.join(`, `)})`:``}`];return u.push(...CCe(l,c)),{content:u.join(`
|
|
4996
4996
|
`)}}function TCe(e,t){return!Array.isArray(e)||e.length===0?s9():t!==void 0&&(typeof t!=`number`||!Number.isFinite(t)||t<0)?{content:`timeout_ms must be a non-negative finite number (or omitted).`,isError:!0}:null}function ECe(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 DCe(e,t){let{scoop_names:n,timeout_ms:r,cross_cone:i}=e,a=TCe(n,r);if(a)return a;let{resolved:o,unknown:s}=t9(n,t);if(o.length===0)return o9(s,t);let c=r9(o,i,`wait on these scoops`,t);if(c)return c;let l=o.map(e=>e.scoop.jid),u=t.onScheduleScoopWait(l,r),d=new Map(o.map(e=>[e.scoop.jid,e.scoop.folder])),f=u.scheduled.map(e=>d.get(e)??e).join(`, `),p=u.unknown.map(e=>d.get(e)??e).join(`, `);return Y7.info(`Wait scheduled`,{scheduled:u.scheduled.map(e=>d.get(e)??e),droppedAtSchedule:p?p.split(`, `):[],unknownNames:s,timeout_ms:r}),u.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${p||u.unknown.join(`, `)}).${s.length>0?` Unknown names: ${s.join(`, `)}.`:``}`,isError:!0}:{content:ECe(f,s,p,r)}}function OCe(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`:e.persistError?`Approved (always) but could NOT persist a rule (${e.persistError}). The current action is allowed; future occurrences will prompt again.`:`Approved (always) — no persistable rule applied for this request.`:`Approved (once) — the current action proceeds; future ones will prompt again.`}async function kCe(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(Y7.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:OCe(e,!!r)}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_confirm failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function ACe(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(Y7.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_dismiss failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function jCe(e){let t=e.onListSudoRequests();return t.length===0?{content:`No pending sudo requests.`}:{content:`Pending sudo requests:\n${t.map(t=>{let n=e.getScoops().find(e=>e.jid===t.scoopJid)?.folder??t.scoopJid,r=t.request.suggestedPattern?` (suggested: ${t.request.suggestedPattern})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
|
|
4997
4997
|
`)}`}}async function MCe(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),Y7.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function NCe(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=>uCe(t,e)}}function PCe(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). If your sudoers already grants the subject with NOPASSWD, this resolves allow immediately without prompting the cone. 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...a9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>pCe(t,e)}}function FCe(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`},[X7]:i9(`feed`)},required:[`scoop_name`,`prompt`]},execute:t=>mCe(t,e)}}function ICe(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:()=>gCe(e)}}function LCe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, a workspace isolation mode (private | shared-readonly), and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default for workspaceMode: shared-readonly (the default) is YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other; private is []. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable in shared-readonly; private does not auto-include them. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},workspaceMode:{type:`string`,enum:[`private`,`shared-readonly`,`snapshot`,`shared-live`],description:`Workspace isolation mode. Default "shared-readonly" is today's scoop: parent workspace + skills are visible, own sandbox + /shared/ are writable, mounts stay readable. "private" is an isolated sandbox (own /scoops/<folder>/ only — no parent workspace, no implicit /shared/, mounts are NOT auto-visible). "snapshot" and "shared-live" are not implemented and are rejected. Explicit visiblePaths / writablePaths still replace the mode's path defaults.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...ir],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`},canCreateChildren:{type:`boolean`,description:`Explicit nested-delegation grant. When true, the new scoop may create and manage its own children (grandchildren of you). Omit or false (the default) keeps it a leaf. The grant is refused when you do not hold canCreateChildren yourself.`}},required:[`name`]},execute:t=>bCe(t,e)}}function RCe(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop") — any name list_scoops shows you.`},[X7]:i9(`drop`)},required:[`scoop_name`]},execute:t=>xCe(t,e)}}function zCe(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`},[X7]:i9(`mute`)},required:[`scoop_names`]},execute:t=>SCe(t,e)}}function BCe(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`},[X7]:i9(`unmute`)},required:[`scoop_names`]},execute:t=>wCe(t,e)}}function VCe(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops list_scoops shows you (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."},[X7]:i9(`wait on`)},required:[`scoop_names`]},execute:t=>DCe(t,e)}}function HCe(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>kCe(t,e)}}function UCe(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>ACe(t,e)}}function WCe(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:()=>jCe(e)}}function GCe(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=>MCe(t,e)}}function KCe(e){let t=[],n=En(e.scoop);return Cn(e.scoop)||(t.push(NCe(e)),e.onSudoRequest&&t.push(PCe(e))),n.canCreateChildren&&e.onScoopScoop&&t.push(LCe(e)),n.canManageChildren&&(e.onFeedScoop&&t.push(FCe(e)),t.push(ICe(e)),e.onDropScoop&&t.push(RCe(e)),e.onMuteScoops&&t.push(zCe(e)),e.onUnmuteScoops&&t.push(BCe(e)),e.onScheduleScoopWait&&t.push(VCe(e)),e.onSudoResolve&&(t.push(HCe(e)),t.push(UCe(e))),e.onListSudoRequests&&t.push(WCe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(GCe(e))),t}const qCe=r(`scoop-context`);function JCe(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-6uzbOlEb.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function YCe(e){let{scoop:t,unit:n,callbacks:r}=e,i=KCe({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=[...USe(e.gatedFs),ISe(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:yt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){qCe.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i,eCe({requester:t.assistantLabel||t.name,setEnv:(t,n)=>e.shell.setMaskedEnvVar(t,n),getProvider:()=>xSe(iS(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:yt()},s=JCe(e);return e.processManager?Gt(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):Gt(a,void 0,o,s)}const c9=r(`scoop-context`);async function XCe(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();c9.info(`Filesystem ready`,{folder:t.folder}),await xS(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await ySe({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 YCe({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 tS(r,n,()=>i.getGlobalMemory());if(!rS(t))return c9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=aS(t,n),p=cS(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await CS(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>rS(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=Pn(t);return{kind:`ready`,agent:yS({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:uS(dS()??v.level,f),getApiKey:()=>rS(t)??void 0,transformContext:g,streamFn:h,captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:g,getCompactionApiKey:_,effortOverride:v.effortOverride,toolCount:l.length}}const l9=r(`scoop-context`);var ZCe=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=dn(e.messages);return this.createdAt=e.createdAt,l9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){l9.error(`Failed to restore agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`)}return[]}async restoreCanonical(){let e=this.deps.canonical;if(!e)return null;let t=null;try{t=await e.store.load(e.identity.key)}catch(e){return l9.warn(`Canonical conversation read failed; falling back to the legacy session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),null}let n=Tee(t);if(n.length===0)return null;let r=dn(n);return t&&(this.createdAt=t.createdAt),l9.info(`Restored conversation from the canonical work-unit record`,{folder:this.deps.folder,messageCount:r.length,droppedOrphans:n.length-r.length}),r}persistNow(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[];if(t.length===0)return;this.persistCanonical(t);let n=this.deps.store;n&&n.save({id:this.deps.sessionId,messages:t,config:{},createdAt:this.createdAt||Date.now(),updatedAt:Date.now()}).catch(e=>{l9.error(`Failed to save agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}persistCanonical(e){let t=this.deps.canonical;t&&t.store.syncAgentMessages(t.identity,e,{createdAt:this.createdAt||Date.now()}).catch(e=>{l9.error(`Failed to save the canonical conversation record`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}async clear(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null),this.createdAt=0;let e=this.deps.canonical;e&&await e.store.delete(e.identity.key);try{await this.deps.store?.delete(this.deps.sessionId)}catch(e){l9.warn(`Failed to clear the legacy agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})}}schedule(){this.deps.isDisposed()||!this.deps.store&&!this.deps.canonical||this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function QCe(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 $Ce(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function u9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const d9=r(`scoop-context`);var ewe=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;d9.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(d9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:Hx(r)}),!!(t<3&&(await Ux(f9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return Vx(e)?(d9.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return Fs(e)?(d9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Ls(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(!Hx(e)||t>=3)return!1;let r=f9(t);return d9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await Ux(r,n)&&!this.deps.isDisposed()}fail(e,t){zx(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function f9(e){return 1e3*2**(e-1)}function twe(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){d9.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const p9=r(`scoop-context`);var nwe=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=Zn(e),this.owner={kind:jn(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 ZCe({store:r??null,canonical:c?{store:c,identity:{key:Tr(e),workUnitId:e.jid,workspaceId:wr(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:Rn(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 vS({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new Xx({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new Qx({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new _S({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 ewe({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 gSe(this.unit,this.scoop,Tn(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Jn(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 XCe({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,capabilityBroker:this.capabilityBroker,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getTurnGuestGates:()=>this.turnGuestGates,getLickTarget:()=>this.ownLickTarget(),getTmpDir:()=>this.ownTmpDir(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},spawnBashJob:e=>this.bashJobs.spawn(e),onBeforeCompaction:(e,t)=>this.maybeSnapshotBeforeCompaction(e,t)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),p9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);p9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(sS(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),$Ce(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(twe(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=QCe(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:a});this.currentTurnProcess=s,this.runBounds.arm();let c=null;try{if(c=await this.turnRunner.run(i,e,t,o),c&&!this.disposed&&!o.aborted){this.turnRunner.reportExhausted(c);return}!this.disposed&&!o.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(a,s,c,o)}}addTurnGuestGate(e){let t=JSON.stringify(e);this.turnGuestGates.some(e=>JSON.stringify(e)===t)||this.turnGuestGates.push(e)}stop(){u9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.idleCompaction?.cancel(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(e={}){this.sessionGeneration++,this.idleCompaction?.cancel(),this.clearMessages(),await this.sessions.clear(),await this.settleLiveSnapshot(e.discardLiveSnapshot===!0)}idleCompactionEnabled(){return jee(this.scoop)?!0:this.unit.parentId===null&&p(`compact-on-idle`)}armIdleCompaction(){if(!this.idleCompactionEnabled()){this.idleCompaction?.disarm();return}if(this.idleCompaction){this.idleCompaction.arm();return}this.idleCompactionLoading??=this.loadIdleCompaction(),this.idleCompactionLoading.then(e=>{!this.disposed&&this.status===`ready`&&e.arm()})}async loadIdleCompaction(){let[{IdleCompaction:e},{readIdleCompactionSettings:t}]=await Promise.all([import(`./idle-compaction-B9i1duyd.js`),import(`./idle-compaction-settings-1yyApSsQ.js`)]),n=new e({isEnabled:()=>this.idleCompactionEnabled(),getSettings:t,getAgent:()=>this.agent,isDisposed:()=>this.disposed,isBusy:()=>this.isBusy,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),estimateTokens:ree,onCompacted:()=>this.sessions.persistNow(),onDiscarded:e=>this.callbacks.onCompactionStateChange?.(`cancelled`,{trigger:`idle`,roundId:e}),folder:this.scoop.folder});return this.idleCompaction=n,n}async maybeSnapshotBeforeCompaction(e,t){if(!(this.unit.parentId!==null&&!p(`memory-v2`)))return this.snapshotBeforeCompaction(e,t)}async snapshotBeforeCompaction(e,t){if(!this.fs||this.disposed)return;let n=this.sessionGeneration,{scoopSessionsDir:r,snapshotLiveSession:i}=await import(`./live-session-snapshot-CpwRZg6K.js`),a=this.unit.parentId===null,o=await i({vfs:this.fs,cone:{folder:this.scoop.folder,label:this.scoop.assistantLabel},messages:e,trigger:t,...a?{}:{sessionsDir:r(this.scoop.folder,this.scoop.jid)},stillValid:()=>!this.disposed&&n===this.sessionGeneration});return o?{transcriptPath:o.transcriptPath}:void 0}async settleLiveSnapshot(e){if(!(this.unit.parentId!==null||!this.fs))try{let{discardLiveSnapshot:t,finalizeLiveSnapshot:n}=await import(`./live-session-snapshot-CpwRZg6K.js`);e?await t(this.fs,this.scoop.folder):await n(this.fs,this.scoop.folder)}catch(t){p9.warn(`Live snapshot settle failed (archive stays live)`,{folder:this.scoop.folder,discard:e,error:t instanceof Error?t.message:String(t)})}}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return oS(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=pS(this.agent,this.scoop))}async reloadSkills(){this.agent&&await hS(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?dS()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,mS(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.idleCompaction?.cancel(),this.runBounds.disarm(),u9(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){this.disposed||Kx(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||Wx(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const m9=r(`scoop-lifecycle-manager`);var rwe=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 Ix(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))??Tn(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return Dn(t.values(),e)??Tn(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){m9.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof xr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)m9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{m9.debug(`Context already exists`,{jid:e});return}}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Zn(t).policy.filesystem;if(a.kind===`restricted`){let e=Sn(a.mode);if(!e.ok)throw Error(e.error)}let o=a.kind===`full-workspace`?r:new xr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`,{includeMounts:Fn(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 nwe(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore(),this.deps.getCapabilityBroker?.()??void 0);n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{m9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&u.notifyOnComplete!==!1&&this.deps.idleTimers.start(e),m9.info(`Scoop context created`,{jid:e,contextId:i})}async reinitAfterPromote(e){let t=this.units.get(e);if(t?.context){t.disposeContext();try{await this.createTab(e)}catch(n){let r=n instanceof Error?n.message:String(n);m9.warn(`Failed to re-init promoted unit; next prompt will retry`,{jid:e,error:r}),t.disposeContext(),this.markTabError(e,r)}}}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),m9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return m9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(m9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){m9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){m9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),m9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();if(Wn(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=Nn(e.folder,n);r!==e.folder&&(m9.warn(`Scoop folder already taken — registering under a free variant`,{jid:e.jid,requested:e.folder,folder:r}),e.folder=r,e.trigger=`@${r}`,e.assistantLabel=r)}t.set(e.jid,e);try{await this.deps.db.saveScoop(e)}catch(n){throw t.delete(e.jid),n}this.deps.messageRouter.ensureQueue(e.jid),m9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&vx(`spawn`,e.folder)}catch(n){m9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){m9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{m9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(An(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Hn(t):void 0)??cx();n&&Mn(e,n)}async unregister(e){let t=this.deps.getScoops();for(let n of qn(t.values(),e))await this.unregister(n.jid);let n=t.get(e);if(n&&n.parentJid===null&&Tn(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{m9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(Tr(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{m9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&m9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),m9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){m9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;Mn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Mn(n,r),this.getContext(e)?.updateModel(),m9.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return!0}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();m9.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{m9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),m9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Bn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){m9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Zn(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}),vx(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:(t,r)=>{n.onCompactionStateChange?.(e,t,r)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return On(n,t),await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(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:tr(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,Cn(t)?void 0:e):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests(Cn(t)?void 0:e):void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(m9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),vx(`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`),Zn(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){m9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{m9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const h9=r(`scoop-message-router`);var iwe=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if(h9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){h9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);vx(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),h9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);h9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){h9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){h9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(h9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){h9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{h9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`||t.channel===`scoop-notify`||t.channel===`scoop-idle`||t.channel===`scoop-wait`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);h9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);h9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;n.reported||r<3e5||(n.reported=!0,h9.warn(`Busy lick queue may be starved`,{jid:e,error:`Lick queue remained deferred while scoop was busy for 300s`}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r}))}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){h9.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){h9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){h9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(h9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){h9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){h9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=Lr(Xr(Vr(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){h9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${ln(e.content,e.attachments)}`).join(`
|
|
4998
|
-
`),l=s.flatMap(e=>un(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Lr(Xr(Vr(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);h9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{h9.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{h9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),h9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{h9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{h9.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),h9.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const g9=r(`orchestrator`),awe={decision:`deny`};var owe=class{scoops=new Map;workUnits=new Dr(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new tx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Nx({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 jx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Tx({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 px({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=>Gr(e),saveMessage:e=>Rr(e)});lickRegistry=new ix({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 iwe({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=>Rr(e),deleteMessage:e=>Br(e),clearMessagesForScoop:e=>Jr(e),clearAllMessages:()=>Kr(),getMessagesSince:(e,t,n)=>Wr(e,t,n),setState:(e,t)=>Ir(e,t)},isExternalLickChannel:oae});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new rwe({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=>Fr(e),deleteScoop:e=>qr(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 lx(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new mv({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 M_(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new sx(e,t),await this.modelPolicyFile.init(),n(),Zr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await $r(),this.sharedFs=await lx(e=>br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Rg,this.conversationStore=new Tb,this.fsWatcher=new yr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>zn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Wn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Ur(`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 dx({onTaskRun:async(e,t)=>{g9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),g9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);g9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}di(e=>this.getSessionCostsForCommand(e)),fi(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-CI1VrdHF.js`).then(e=>e.t);return e()}),this.unregisterExportService=gv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Vg;try{await yb({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){g9.warn(`Canonical conversation migration failed; staying on the legacy stores`,{error:e instanceof Error?e.message:String(e)})}}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=zn(e)?null:t??null;try{await Fr(e)}catch(t){g9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!An(e));if(e.length===0)return;let t=cx(),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?Hn(n):void 0)??t;if(r){Mn(e,r);try{await Fr(e)}catch(t){g9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Qn.root}/`,r=$n(dee(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,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-ByZDWCge.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:tr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(g9.warn(`Guest approval before SudoManager init — failing closed`),awe)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await Fr(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 Tn(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 Gn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Dn(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await br.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Xb(this.sharedFs).catch(e=>{g9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new mv({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 M_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new sx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),g9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return Gr(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(mi)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&g9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,g9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Vg,t=this.sharedFs;return new zy({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:ib(),snapshotStore:{read:e=>Xy(t,e),write:(e,n)=>Yy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.153.0`})}};const _9=r(`workflow-run-manager`),v9=`/shared/workflow-runs`,y9=1e3;function swe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function cwe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){_9.warn(`observeRun handler threw`,e)}},i=(e,n)=>pwe(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=swe(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),dwe(t,n);let f=i(a.ctx,c),p=fwe(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>_9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${v9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(v9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);_9.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?uwe(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){_9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function lwe(e){let t=cwe(e);return globalThis[f7]=t,_9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function uwe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function dwe(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 fwe(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 pwe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?mwe(n,t,a?.args??[],r):e===`agent`?hwe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function mwe(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>y9&&i.logs.splice(0,i.logs.length-y9),r()}return{stdout:``,stderr:``,exitCode:0}}async function hwe(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 gwe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function _we(e,t,n){let r=vwe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=ywe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function vwe(e){let t=new Map;return b9(t,e.discoveryOrigin),b9(t,e.discoveryUrl),[...t.values()]}function b9(e,t){if(t){x9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);x9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!gwe.has(e)))x9(e,t,1,`substring`)}catch{}}}function x9(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function ywe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=xwe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)bwe(a,e)&&(r+=e.weight*o)}return r}function bwe(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 xwe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Swe=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=w9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name)),t.push({name:C9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===C9)throw new or(`ENOTDIR`,`not a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return S9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new or(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=w9(e);if(t.length===1&&t[0]===C9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new or(`EISDIR`,`is a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new or(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=w9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===C9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new or(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new or(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new or(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new or(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:E9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:D9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
4998
|
+
`),l=s.flatMap(e=>un(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=Lr(Xr(Vr(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer),p=new Set,m=[];for(let e of s){if(!e.guestGate)continue;let t=JSON.stringify(e.guestGate);p.has(t)||(p.add(t),m.push(e.guestGate))}await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f,...m.length>0?{guestGates:m}:{}})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);h9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t,n={}){this.cancelDebounce(e),t&&await t.clearSession(n).catch(t=>{h9.warn(`Failed to clear the durable conversation for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.clearMessagesForScoop(e).catch(t=>{h9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),h9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{h9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})}),await Promise.all([...this.deps.getContexts().values()].map(e=>e.clearSession().catch(e=>{h9.warn(`Failed to clear a durable conversation`,{error:e instanceof Error?e.message:String(e)})}))),this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),h9.info(`All messages cleared`)}getQueuedMessageIds(e){return(this.messageQueues.get(e)??[]).map(e=>e.id)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const g9=r(`orchestrator`),awe={decision:`deny`};var owe=class{scoops=new Map;workUnits=new Dr(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new tx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;capabilityBroker=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Nx({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 jx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Tx({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 px({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=>Gr(e),saveMessage:e=>Rr(e)});lickRegistry=new ix({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 iwe({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=>Rr(e),deleteMessage:e=>Br(e),clearMessagesForScoop:e=>Jr(e),clearAllMessages:()=>Kr(),getMessagesSince:(e,t,n)=>Wr(e,t,n),setState:(e,t)=>Ir(e,t)},isExternalLickChannel:oae});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new rwe({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=>Fr(e),deleteScoop:e=>qr(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 lx(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new mv({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 M_(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new sx(e,t),await this.modelPolicyFile.init(),n(),Zr()),n,{stagePrefix:`orchestrator-init`})}async init(e){await $r(),this.sharedFs=await lx(e=>br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new Rg,this.conversationStore=new Tb,this.fsWatcher=new yr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher;let t=await this.initPolicyLayerAndLoadRecords(this.sharedFs,this.fsWatcher,e),n=Object.values(t).find(e=>zn(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Wn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Ur(`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 dx({onTaskRun:async(e,t)=>{g9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),g9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);g9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}di(e=>this.getSessionCostsForCommand(e)),fi(async()=>{let{refreshBudgetWindow:e}=await import(`./budget-usage-source-DVW8NROx.js`).then(e=>e.t);return e()}),this.unregisterExportService=gv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Vg;try{await yb({store:t,units:[...this.scoops.values()],loadAgentSession:async e=>{let t=await this.sessionStore?.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},loadChatSession:async e=>{let t=await n.load(e);return t?{messages:t.messages,createdAt:t.createdAt}:null},onProgress:e})}catch(e){g9.warn(`Canonical conversation migration failed; staying on the legacy stores`,{error:e instanceof Error?e.message:String(e)})}}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=zn(e)?null:t??null;try{await Fr(e)}catch(t){g9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!An(e));if(e.length===0)return;let t=cx(),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?Hn(n):void 0)??t;if(r){Mn(e,r);try{await Fr(e)}catch(t){g9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Qn.root}/`,r=$n(dee(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t,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-Pzx9_4nE.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:tr,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(g9.warn(`Guest approval before SudoManager init — failing closed`),awe)}})}async enqueueDirectedApproval(e,t){return this.approveDirectedOrUser({...t,approver:e})}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t,n){return this.approvalRouter.resolveSudoRequestAndPersist(e,t,n)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t,n){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t,n)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(e){return this.approvalRouter.listPendingSudoRequests(e)}registerScoop(e){return this.lifecycle.register(e)}async persistScoop(e){this.scoops.set(e.jid,e),await Fr(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 Tn(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 Gn(this.scoops.values(),t)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return Dn(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await br.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Xb(this.sharedFs).catch(e=>{g9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new mv({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 M_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new sx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),g9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e,t={}){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e),t)}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}getQueuedMessageIds(e){return this.messageRouter.getQueuedMessageIds(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return Gr(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(mi)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&g9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,g9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Vg,t=this.sharedFs;return new zy({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:ib(),snapshotStore:{read:e=>Xy(t,e),write:(e,n)=>Yy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.154.0`})}};const _9=r(`workflow-run-manager`),v9=`/shared/workflow-runs`,y9=1e3;function swe(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function cwe(e){let t=new Map,n=new Map,r=e=>{let r=t.get(e);if(r)for(let t of n.get(e)??[])try{t(r)}catch(e){_9.warn(`observeRun handler threw`,e)}},i=(e,n)=>pwe(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=swe(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),dwe(t,n);let f=i(a.ctx,c),p=fwe(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>_9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${v9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(v9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);_9.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=u,s.preview=i===`done`?uwe(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:a,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){_9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function lwe(e){let t=cwe(e);return globalThis[f7]=t,_9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function uwe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function dwe(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 fwe(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 pwe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?mwe(n,t,a?.args??[],r):e===`agent`?hwe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function mwe(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>y9&&i.logs.splice(0,i.logs.length-y9),r()}return{stdout:``,stderr:``,exitCode:0}}async function hwe(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 gwe=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function _we(e,t,n){let r=vwe(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=ywe(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function vwe(e){let t=new Map;return b9(t,e.discoveryOrigin),b9(t,e.discoveryUrl),[...t.values()]}function b9(e,t){if(t){x9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);x9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!gwe.has(e)))x9(e,t,1,`substring`)}catch{}}}function x9(e,t,n,r){if(t.length===0)return;let i=`${r}:${t}`,a=e.get(i);(!a||n>a.weight)&&e.set(i,{text:t,weight:n,match:r})}function ywe(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=xwe(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)bwe(a,e)&&(r+=e.weight*o)}return r}function bwe(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 xwe(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Swe=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=w9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name)),t.push({name:C9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===C9)throw new or(`ENOTDIR`,`not a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return S9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new or(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=w9(e);if(t.length===1&&t[0]===C9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new or(`EISDIR`,`is a directory`,e);let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new or(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=w9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===C9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=T9(t[0]);if(n===null||!this.pidExists(n))throw new or(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!S9.includes(r))throw new or(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new or(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new or(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new or(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new or(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderTable(){let e={stats:this.pm.stats(),processes:this.pm.list().map(e=>({pid:e.pid,ppid:e.ppid,kind:e.kind,state:E9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:D9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
4999
4999
|
`}renderProcFile(e,t){if(e===1)return Dwe(t);let n=this.pm.get(e);switch(t){case`status`:return Cwe(n);case`cmdline`:return wwe(n);case`cwd`:return Twe(n);case`stat`:return Ewe(n)}}};const S9=[`status`,`cmdline`,`cwd`,`stat`],C9=`table`;function w9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function T9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Cwe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${E9(e.status)} (${e.status})`,`Owner:\t${D9(e)}`,`StartedAt:\t${new Date(e.startedAt).toISOString()}`];return e.finishedAt!==null&&t.push(`FinishedAt:\t${new Date(e.finishedAt).toISOString()}`),e.terminatedBy!==null&&t.push(`TerminatedBy:\t${e.terminatedBy}`),e.exitCode!==null&&t.push(`ExitCode:\t${e.exitCode}`),t.push(`Cmdline:\t${e.argv.join(` `)}`),t.join(`
|
|
5000
5000
|
`)+`
|
|
5001
5001
|
`}function wwe(e){return e.argv.join(`\0`)+`\0`}function Twe(e){return e.cwd+`
|
|
@@ -5004,7 +5004,7 @@ pass --wait to block and print the full result.`,kxe=new Set([`list`,`status`,`s
|
|
|
5004
5004
|
`)+`
|
|
5005
5005
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5006
5006
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5007
|
-
`}}function Owe(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(AU(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(!TU(n.token))return;let a=i.get(n.id);if(a){r({type:jU,id:n.id}),a.result&&r({type:MU,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:jU,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:MU,id:n.id,...e})};(IU(n)?zU(n):kU(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function O9(){return globalThis}function kwe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Awe(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function jwe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Mwe(e,t)}function Mwe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Tn(r),a=e.type===`discovery`&&!e.targetScoop?_we(e,i.filter(A_),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?fc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!A_(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let s=Jg(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=kwe(e),l=Awe(e),u=e.type,d={id:`${u}-${l}-${Date.now()}`,chatJid:o.jid,senderId:u,senderName:`${u}:${c}`,content:s.content,timestamp:e.timestamp,fromAssistant:!1,channel:u,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(d).catch(e=>{n.warn(`Lick message routing failed`,{channel:u,eventName:c,error:String(e)})})}async function Nwe(e,t,n,r,i){let a=new _a,o=new owe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=qt(),c=i.capabilityBroker??L_(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),ur(c),O9().__slicc_pm=a,iJ(oJ()),O9().__slicc_browser=t,await n.bind(o,t);let l=Mr(()=>n.emitTrayRuntimeStatus()),u=Oae(()=>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 Pwe(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-B5aRQX4l.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source-
|
|
5008
|
-
`,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 Rwe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-DqmithfF.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BxfjZHzO.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function zwe(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 Hae(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})},{...Bwe(t),isOwnTab:Bae(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Bwe(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:()=>Uae()}}function Vwe(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-szxkUpiN.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-0jMTi9rV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function Hwe(){ti(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-BXADtDDx.js`);return e()})}function Uwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BXADtDDx.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 Wwe(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 Gwe(e){return e===`node-rest`}function Kwe(e,t,n,r){import(`./gelatiere-unit-Dem3bPJm.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!p(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-CcLPnD5F.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function qwe(e,t){if(!e)return()=>{};import(`./memory-curation-seam-B1zdL89W.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return p(`memory-v2`)&&import(`./memory-health-MhSOmzAf.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function Jwe(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}lee(e,t,e.getSessionStore())}async function Ywe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Hwe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Nwe(t,n,r,i,e);if(s(`orchestrator-ready`),Jwe(l,f,o),f)try{await f.mountInternal(`/proc`,new Swe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Pwe(l,e,o);s(`lick-manager-ready`),f&&Iwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),O9().__slicc_lickManager=m,Kwe(l,m,f,o);let h=qwe(f,o),{wsBridge:g,wsRegistry:_}=await Lwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});O9().__slicc_wsSubscribers=_;let v=Gwe(p.adapter)?await Rwe(m,o,e.localLickWsUrl??null,f):null,y=zwe(n,m,o,e.appPageUrl);f&&Vwe(f,m,o),a||await Fwe(l),s(`cone-bootstrapped`),f&&Uwe(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await Wwe(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Owe({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 Xwe({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 Xwe(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)}Zwe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Zwe(e){let t=O9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,iJ(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[f7]}const k9=`x-bypass-llm-proxy`;function Qwe(e,t,n){return t?(r,i)=>{if(!$we(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(k9)||a.set(k9,`1`),e(r,{...i,headers:a})}:e}function $we(e,t,n){if(tTe(e,t))return!0;let r=n?.()??null;return r?eTe(e,r,t):!1}function eTe(e,t,n){let r=A9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function tTe(e,t){let n=A9(e);try{return new URL(n,t).origin===t}catch{return!0}}function A9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function nTe(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 rTe=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(!iTe(e)||e.source!==`panel`)return;let t=e.payload;aTe(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=qa(y(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?j9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,j9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function iTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function j9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function aTe(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 oTe=class extends A7{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function sTe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new rTe({transport:t,processManager:i,createShell:(a,o)=>new oTe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Ar},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function cTe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function lTe(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 uTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function dTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function M9(e){return cTe(e)||lTe(e)||uTe(e)||dTe(e)}function N9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return fTe(e);if(typeof e==`object`)return pTe(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function P9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return L9(e)??R9(e);let t=N9(e);if(t!==void 0)return F9(t)}function F9(e){let t=e.trim();if(!t)return e;let n=I9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=I9(t.slice(r,i+1));if(e)return e}return e}function fTe(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function pTe(e){let t=L9(e),n=R9(e);return n&&t?`${n}: ${t}`:t??n}function I9(e){if(e.startsWith(`{`))try{return L9(JSON.parse(e))}catch{return}}function L9(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function R9(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let z9=null,B9=!1;function mTe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function hTe(e){return mTe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function gTe(e={}){if(!B9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){sSe(_Te),_x(vTe),Rx(V9);try{let t=hTe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(z9=(await import(`./rum-worker-CwmNSpjO.js`)).default,U9(self)):t===`extension`?(z9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&U9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),STe(),bTe(),z9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),B9=!0,z9&&z9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function _Te(e){z9?.(`fill`,{source:e})}function V9(e,t){let n=H9(t);n!==null&&z9?.(`error`,{source:e,target:n})}function vTe(e,t,n){if(e===`error`){let e=H9(n);if(e===null)return;z9?.(`error`,{source:`scoop:${t}`,target:e});return}z9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function yTe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function H9(e){let t=N9(e);if(t===void 0)return e==null?void 0:null;if(M9(t))return null;let n=P9(e)??F9(t);return M9(n)?null:G9(n)}function U9(e){e.addEventListener(`error`,e=>{let t=e;V9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{V9(`js`,e.reason)})}function W9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function bTe(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0))}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5007
|
+
`}}function Owe(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(AU(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(!TU(n.token))return;let a=i.get(n.id);if(a){r({type:jU,id:n.id}),a.result&&r({type:MU,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:jU,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:MU,id:n.id,...e})};(IU(n)?zU(n):kU(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function O9(){return globalThis}function kwe(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Awe(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function jwe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Mwe(e,t)}function Mwe(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=Tn(r),a=e.type===`discovery`&&!e.targetScoop?_we(e,i.filter(A_),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?fc(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!A_(o)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:o.folder});return}e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let s=Jg(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=kwe(e),l=Awe(e),u=e.type,d={id:`${u}-${l}-${Date.now()}`,chatJid:o.jid,senderId:u,senderName:`${u}:${c}`,content:s.content,timestamp:e.timestamp,fromAssistant:!1,channel:u,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(d).catch(e=>{n.warn(`Lick message routing failed`,{channel:u,eventName:c,error:String(e)})})}async function Nwe(e,t,n,r,i){let a=new _a,o=new owe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a);let s=qt(),c=i.capabilityBroker??L_(s,{...i.pageGestures?{pageGestures:i.pageGestures}:{}});o.setCapabilityBroker(c),ur(c),O9().__slicc_pm=a,iJ(oJ()),O9().__slicc_browser=t,await n.bind(o,t);let l=Mr(()=>n.emitTrayRuntimeStatus()),u=Oae(()=>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 Pwe(e,t,n){let{registerSessionBudgetProvider:r,registerSessionCostsProvider:i}=await import(`./cost-command-B5aRQX4l.js`).then(e=>e.t);i(t=>e.getSessionCostsForCommand(t));let{refreshBudgetWindow:a}=await import(`./budget-usage-source-DVW8NROx.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??jwe,l={orchestrator:e,lickManager:s,log:n};return s.setEventHandler(e=>c(e,l)),s}async function Fwe(e){let t=e.getScoops();Tn(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 Iwe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;lwe({sharedFs:i,getStartingRoot:e=>{let n=Tn(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)=>cJ(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p7().slice(10,22),splitResult:(e,t)=>m7(e,t)})}async function Lwe(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))+`
|
|
5008
|
+
`,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 Rwe(e,t,n,r){try{let{startLickWsBridge:i}=await import(`./lick-ws-bridge-DqmithfF.js`),{HostFsMountBackend:a}=await import(`./backend-hostfs-BxfjZHzO.js`);return i(e,{locationHref:self.location.href,lickWsUrl:n??null,onHostfsInvalidate:e=>{if(!r)return;let n=r.getMountBackend(e.mount);if(!(n instanceof a)){t.debug?.(`hostfs_invalidate for unknown/non-hostfs mount`,{mount:e.mount});return}n.applyHostInvalidation(e.paths).catch(n=>{t.warn(`hostfs_invalidate apply failed`,{mount:e.mount,error:n instanceof Error?n.message:String(n)})})}}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function zwe(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 Hae(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})},{...Bwe(t),isOwnTab:Bae(()=>r??null)});return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Bwe(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:()=>Uae()}}function Vwe(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-Wt3z_gJ-.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-0jMTi9rV.js`),l=await s(e,n),u=await r(),d=c(u,l);for(let e of o(u,l))i(e.targetPath).catch(t=>{n.warn(`failed to purge host-owned mount row`,{path:e.targetPath,error:t instanceof Error?t.message:String(t)})});if(d.length===0)return;let{needsRecovery:f}=await a(d,e,n);if(f.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:f}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function Hwe(){ti(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-dJipOZ6Y.js`);return e()})}function Uwe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-dJipOZ6Y.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 Wwe(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 Gwe(e){return e===`node-rest`}function Kwe(e,t,n,r){import(`./gelatiere-unit-Dem3bPJm.js`).then(async r=>{let i=r.createGelatiereSeam(e,t);if(r.publishGelatiereSeam(i),!n||!p(`memory-v2`)){await r.haltGelatiere(i);return}let{loadGelatiereConfig:a}=await import(`./gelatiere-store-CcLPnD5F.js`),o=await a(n);await r.bootGelatiere(i,o.nightly,o.allowedCommands)}).catch(e=>r.warn(`gelatiere seam failed to publish`,e))}function qwe(e,t){if(!e)return()=>{};import(`./memory-curation-seam-bWfYQeB0.js`).then(t=>t.publishMemorySeam(t.createMemorySeam(e))).catch(e=>t.warn(`memory seam failed to publish`,e));let n=!1,r=null;return p(`memory-v2`)&&import(`./memory-health-MhSOmzAf.js`).then(i=>{n||(r=i.scheduleMemoryHealthChecks(e,{log:t}))}).catch(e=>t.warn(`memory health check failed to schedule`,e)),()=>{n=!0,r?.()}}function Jwe(e,t,n){if(!t){n.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`);return}lee(e,t,e.getSessionStore())}async function Ywe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Hwe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f,capabilityBroker:p}=await Nwe(t,n,r,i,e);if(s(`orchestrator-ready`),Jwe(l,f,o),f)try{await f.mountInternal(`/proc`,new Swe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let m=await Pwe(l,e,o);s(`lick-manager-ready`),f&&Iwe({orchestrator:l,processManager:c,lickManager:m,sharedFs:f}),O9().__slicc_lickManager=m,Kwe(l,m,f,o);let h=qwe(f,o),{wsBridge:g,wsRegistry:_}=await Lwe({browser:n,lickManager:m,orchestrator:l,sharedFs:f,log:o});O9().__slicc_wsSubscribers=_;let v=Gwe(p.adapter)?await Rwe(m,o,e.localLickWsUrl??null,f):null,y=zwe(n,m,o,e.appPageUrl);f&&Vwe(f,m,o),a||await Fwe(l),s(`cone-bootstrapped`),f&&Uwe(m,o);let b=null,x=null;f&&({bshWatchdogStop:b,scriptCatalogDispose:x}=await Wwe(f,n,o));let S=null;f&&e.syncFsChannelNonce&&(S=Owe({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 Xwe({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 Xwe(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)}Zwe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Zwe(e){let t=O9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,iJ(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[f7]}const k9=`x-bypass-llm-proxy`;function Qwe(e,t,n){return t?(r,i)=>{if(!$we(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(k9)||a.set(k9,`1`),e(r,{...i,headers:a})}:e}function $we(e,t,n){if(tTe(e,t))return!0;let r=n?.()??null;return r?eTe(e,r,t):!1}function eTe(e,t,n){let r=A9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function tTe(e,t){let n=A9(e);try{return new URL(n,t).origin===t}catch{return!0}}function A9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function nTe(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 rTe=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(!iTe(e)||e.source!==`panel`)return;let t=e.payload;aTe(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=qa(y(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?j9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,j9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function iTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function j9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function aTe(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 oTe=class extends A7{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function sTe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new rTe({transport:t,processManager:i,createShell:(a,o)=>new oTe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??(()=>!1),getLeaderStatus:e.webhook?.getLeaderStatus??Ar},crontask:e.crontask,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function cTe(e){return typeof e==`string`&&e.startsWith(`No API key configured`)}function lTe(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 uTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`please log in again`)}function dTe(e){return typeof e!=`string`||!e?!1:e.toLowerCase().includes(`quota_exceeded`)}function M9(e){return cTe(e)||lTe(e)||uTe(e)||dTe(e)}function N9(e){if(e!=null){if(typeof e==`string`)return e;if(e instanceof Error)return fTe(e);if(typeof e==`object`)return pTe(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e)}}function P9(e){if(typeof e==`object`&&e&&!(e instanceof Error))return L9(e)??R9(e);let t=N9(e);if(t!==void 0)return F9(t)}function F9(e){let t=e.trim();if(!t)return e;let n=I9(t);if(n)return n;let r=t.indexOf(`{`),i=t.lastIndexOf(`}`);if(r>0&&i>r){let e=I9(t.slice(r,i+1));if(e)return e}return e}function fTe(e){let t=e.name&&e.name!==`Error`?e.name:``,n=e.message||``;return t&&n?`${t}: ${n}`:n||t||`Error`}function pTe(e){let t=L9(e),n=R9(e);return n&&t?`${n}: ${t}`:t??n}function I9(e){if(e.startsWith(`{`))try{return L9(JSON.parse(e))}catch{return}}function L9(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.message==`string`&&t.message.length>0)return t.message;if(typeof t.error==`string`&&t.error.length>0)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`&&e.message.length>0)return e.message}}function R9(e){if(!e||typeof e!=`object`)return;let t=e;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.type==`string`&&e.type.length>0)return e.type}if(typeof t.type==`string`&&t.type.length>0&&t.type!==`error`)return t.type}let z9=null,B9=!1;function mTe(){return typeof window>`u`||typeof document>`u`||document?.documentElement===void 0||typeof localStorage?.getItem!=`function`}function hTe(e){return mTe()?`standalone-worker`:e?`extension`:typeof document<`u`&&document.documentElement?.dataset?.electronOverlay?`electron`:`cli`}async function gTe(e={}){if(!B9&&!(typeof localStorage<`u`&&typeof localStorage?.getItem==`function`&&localStorage.getItem(`telemetry-disabled`)===`true`)){sSe(_Te),_x(vTe),Rx(V9);try{let t=hTe(e.isExtensionRealm??!1);t!==`standalone-worker`&&typeof window<`u`?window.RUM_GENERATION=`slicc-${t}`:globalThis.RUM_GENERATION=`slicc-${t}`,t===`standalone-worker`?(z9=(await import(`./rum-worker-CwmNSpjO.js`)).default,U9(self)):t===`extension`?(z9=(await import(`./rum-DW84CvBs.js`)).default,typeof window<`u`&&U9(window)):(typeof window<`u`&&(window.SAMPLE_PAGEVIEWS_AT_RATE=`high`),STe(),bTe(),z9=(await import(`./src-Cj-AoUM3.js`)).sampleRUM),B9=!0,z9&&z9(`navigate`,{source:typeof document<`u`?document.referrer:``,target:t})}catch{}}}function _Te(e){z9?.(`fill`,{source:e})}function V9(e,t){let n=H9(t);n!==null&&z9?.(`error`,{source:e,target:n})}function vTe(e,t,n){if(e===`error`){let e=H9(n);if(e===null)return;z9?.(`error`,{source:`scoop:${t}`,target:e});return}z9?.(e===`spawn`?`enter`:e===`feed`?`convert`:`leave`,{source:t,target:`scoop-${e}`})}function yTe(e){return e.includes(`@vite/client`)||e.includes(`@vite/env`)||e.includes(`[vite]`)||/https?:\/\/localhost:\d+\/@vite\//.test(e)||/\/__vite_ping/.test(e)}function H9(e){let t=N9(e);if(t===void 0)return e==null?void 0:null;if(M9(t))return null;let n=P9(e)??F9(t);return M9(n)?null:G9(n)}function U9(e){e.addEventListener(`error`,e=>{let t=e;V9(`js`,t.error??t.message??``)}),e.addEventListener(`unhandledrejection`,e=>{V9(`js`,e.reason)})}function W9(e){return typeof e==`object`&&!!e&&!(e instanceof Error)}function bTe(){typeof window>`u`||(window.addEventListener(`error`,e=>{let t=e.error;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0),window.addEventListener(`unhandledrejection`,e=>{let t=e.reason;W9(t)&&(V9(`js`,t),e.stopImmediatePropagation())},!0))}function G9(e){let t=e??``;if(t.includes(`@vite/`)||t.includes(`[vite]`)||t.includes(`__vite_ping`)){let e=t.split(`
|
|
5009
5009
|
`).filter(e=>!yTe(e)).join(`
|
|
5010
|
-
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const K9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function q9(e){let t=typeof e==`string`?e:P9(e)??N9(e);if(typeof t!=`string`)return{kind:`absent`};let n=F9(t);if(n===`[object Object]`)return{kind:`noise`};let r=G9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function xTe(e){let t=q9(e.source),n=q9(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i||n.kind===`noise`&&e.source===`undefined error`)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function STe(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[K9])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=xTe(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[K9]=!0,navigator.sendBeacon=n}function CTe(e){let t=new wTe(e);return t.start(),{stop:()=>t.dispose()}}var wTe=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(!TTe(e)||e.source!==`panel`)return;let t=e.payload;if(ETe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(DTe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(OTe(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 or(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async 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 or(`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 or(`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(kTe(e.type),e.requestId,new or(`EACCES`,`vfs-rpc-host has no writable backend wired`),ATe(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new or(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new or(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new or(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function TTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ETe(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 DTe(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 OTe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function kTe(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 ATe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof or?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function jTe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Qwe(e.bind(globalThis),t,MTe)}function MTe(){let e=Te();if(!e)return null;try{return new URL(e).origin}catch{return null}}function NTe(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 PTe=nTe(e=>LTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&PTe.handle(e.data)});function FTe(e){let t=nte(e.pageBuildId,`6.153.0-mu1blc92`);return()=>{t&&V9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.153.0-mu1blc92`)}}function ITe(e){jTe(),M(e.localApiBaseUrl??null),N(e.bridgeToken??null),Qq(e.syncFsBridgeEnabled??!1),Yo(e.pageLoadedAt??null),Ee(e.extensionDelegateId??null),NTe(e.localStorageSeed??{}),e.flagFloat&&Yee(e.flagFloat)}async function LTe(e){ete(e.instanceId);let t=FTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{ITe(e),gTe().then(t).catch(()=>{}),await g(),n(`providers-registered`);let r=uc(e.kernelPort),i=new m_(r),a=m_.createCallbacks(i),o=new dc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Kee(o);Y9=await Ywe({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of Zo)d.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,s.setTrayTargetProvider(Jee(u));let p=await zTe({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){RTe(e.kernelPort,t)}}function RTe(e,t){tte(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 zTe(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=sTe({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=CTe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await BTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function BTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-uGHvkmNC.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-B57RqgUb.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())});
|
|
5010
|
+
`).trim();return e?e.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`):null}return t.slice(0,200).replace(/(\/[a-z]+)(?:\/[^\s/]+)+/gi,`$1/.../`)}const K9=Symbol.for(`slicc.telemetry.sendBeacon.wrapped`);function q9(e){let t=typeof e==`string`?e:P9(e)??N9(e);if(typeof t!=`string`)return{kind:`absent`};let n=F9(t);if(n===`[object Object]`)return{kind:`noise`};let r=G9(n);return r===null?{kind:`noise`}:{kind:`kept`,value:r,mutated:r!==e}}function xTe(e){let t=q9(e.source),n=q9(e.target),r=t.kind!==`kept`,i=n.kind!==`kept`;if((t.kind!==`absent`||n.kind!==`absent`)&&r&&i||n.kind===`noise`&&e.source===`undefined error`)return!0;let a=!1;return t.kind===`kept`?t.mutated&&(e.source=t.value,a=!0):t.kind===`noise`&&(e.source=``,a=!0),n.kind===`kept`?n.mutated&&(e.target=n.value,a=!0):n.kind===`noise`&&(e.target=``,a=!0),a?JSON.stringify(e):null}function STe(){if(typeof navigator>`u`||typeof navigator.sendBeacon!=`function`)return;let e=navigator.sendBeacon;if(e[K9])return;let t=e.bind(navigator),n=((e,n)=>{try{let r=typeof n==`string`?n:n instanceof ArrayBuffer?new TextDecoder().decode(n):null;if(r&&r.length>0&&r.charCodeAt(0)===123){let n=JSON.parse(r);if(n?.checkpoint===`error`){let r=xTe(n);if(r===!0)return!0;if(r!==null)return t(e,r)}}}catch{}return t(e,n)});n[K9]=!0,navigator.sendBeacon=n}function CTe(e){let t=new wTe(e);return t.start(),{stop:()=>t.dispose()}}var wTe=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(!TTe(e)||e.source!==`panel`)return;let t=e.payload;if(ETe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(DTe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(OTe(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 or(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async 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 or(`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 or(`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(kTe(e.type),e.requestId,new or(`EACCES`,`vfs-rpc-host has no writable backend wired`),ATe(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new or(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new or(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new or(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function TTe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ETe(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 DTe(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 OTe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function kTe(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 ATe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof or?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function jTe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Qwe(e.bind(globalThis),t,MTe)}function MTe(){let e=Te();if(!e)return null;try{return new URL(e).origin}catch{return null}}function NTe(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 PTe=nTe(e=>LTe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&PTe.handle(e.data)});function FTe(e){let t=nte(e.pageBuildId,`6.154.0-mu1j040x`);return()=>{t&&V9(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.154.0-mu1j040x`)}}function ITe(e){jTe(),M(e.localApiBaseUrl??null),N(e.bridgeToken??null),Qq(e.syncFsBridgeEnabled??!1),Yo(e.pageLoadedAt??null),Ee(e.extensionDelegateId??null),NTe(e.localStorageSeed??{}),e.flagFloat&&Yee(e.flagFloat)}async function LTe(e){ete(e.instanceId);let t=FTe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{ITe(e),gTe().then(t).catch(()=>{}),await g(),n(`providers-registered`);let r=uc(e.kernelPort),i=new m_(r),a=m_.createCallbacks(i),o=new dc(e.cdpPort);await o.connect(),n(`cdp-connected`);let s=new Kee(o);Y9=await Ywe({container:{},browser:s,bridge:i,callbacks:a,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,appPageUrl:e.appPageUrl??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-Bur-XBNy.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let d=Y9.sharedFs?.getWatcher();if(d){let e=null,t=new Set;for(let n of Zo)d.watch(n,e=>e.endsWith(`.shtml`),n=>{for(let e of n){let n=e.path.split(`/`).pop()?.replace(/\.shtml$/,``);n&&t.add(n)}e||=setTimeout(()=>{e=null;for(let e of t)l.reload(e).catch(()=>{});t.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,s.setTrayTargetProvider(Jee(u));let p=await zTe({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){RTe(e.kernelPort,t)}}function RTe(e,t){tte(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 zTe(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=sTe({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=CTe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),a=await BTe(t,e.instanceId);return{stopTerminalHost:r.stop,stopVfsRpcHost:i.stop,stopSpeechAssetsResponder:a}}async function BTe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-uGHvkmNC.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-B57RqgUb.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())});
|