sliccy 6.110.12 → 6.110.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/.vite/manifest.json +144 -144
- package/dist/ui/assets/{account-store-JfqGLwpx.js → account-store-B5g-mrn8.js} +1 -1
- package/dist/ui/assets/{account-store-B4f1TkzQ.js → account-store-mFC76tgv.js} +1 -1
- package/dist/ui/assets/{adobe-BG0h31bK.js → adobe-BCBLeEqn.js} +1 -1
- package/dist/ui/assets/{adobe-Bz4TU9A0.js → adobe-DN_cMZlf.js} +1 -1
- package/dist/ui/assets/{agent-bridge-CuRwAl_F.js → agent-bridge-DJ2Gh9VA.js} +1 -1
- package/dist/ui/assets/{agent-panels-C-yTo1Cf.js → agent-panels-SjLPDAhx.js} +1 -1
- package/dist/ui/assets/{apply-layout-Cwjdhbay.js → apply-layout-DegnOb_8.js} +1 -1
- package/dist/ui/assets/{apps-CBx42rH9.js → apps-CeTlBebf.js} +1 -1
- package/dist/ui/assets/{azure-openai-CvYv7foL.js → azure-openai-CbsjCnKF.js} +1 -1
- package/dist/ui/assets/{azure-openai-IHA9P8r4.js → azure-openai-Co7qiHsD.js} +1 -1
- package/dist/ui/assets/{cerebras-zwsRFQcw.js → cerebras-CHy7N-5g.js} +1 -1
- package/dist/ui/assets/{cerebras-C-G9dGIN.js → cerebras-CnIp8GQk.js} +1 -1
- package/dist/ui/assets/{connect-surface-DfgyQ6M7.js → connect-surface-Hu5fOtLV.js} +1 -1
- package/dist/ui/assets/{core-BVWxlTTk.js → core-CGasZgKz.js} +3 -3
- package/dist/ui/assets/{directed-approval-DeUsUYBD.js → directed-approval-CRALKPfL.js} +1 -1
- package/dist/ui/assets/{fs-DBHB4fgS.js → fs-BhUjB1cK.js} +1 -1
- package/dist/ui/assets/{fs-DO7Pn7WW.js → fs-CSRyHRw6.js} +2 -2
- package/dist/ui/assets/{github-DthV99LD.js → github-CWYdKkWk.js} +1 -1
- package/dist/ui/assets/{github-CXGHIZVB.js → github-CaubYdfd.js} +2 -2
- package/dist/ui/assets/{github-copilot-Dsa9eVh5.js → github-copilot-BAWQ9UfS.js} +1 -1
- package/dist/ui/assets/{github-copilot-BdjkPAt8.js → github-copilot-Ygk85cjt.js} +1 -1
- package/dist/ui/assets/{github-install-Co8RGcCz.js → github-install-C_CLyb3u.js} +1 -1
- package/dist/ui/assets/{github-zip-Cp0IybNw.js → github-zip-CKXdHtbK.js} +1 -1
- package/dist/ui/assets/{guest-tool-gate-MzqLI9n7.js → guest-tool-gate-DTA3P3jk.js} +1 -1
- package/dist/ui/assets/icons-BJsliYCh.js +1 -0
- package/dist/ui/assets/{js-realm-worker-C11HEtiw.js → js-realm-worker-B8Mm9E9s.js} +1 -1
- package/dist/ui/assets/{kernel-worker-BP7AbN0g.js → kernel-worker-BBWsqNvT.js} +28 -28
- package/dist/ui/assets/{local-llm-CWEg0rcm.js → local-llm-CBszF_hu.js} +1 -1
- package/dist/ui/assets/{local-llm-MS9lnpet.js → local-llm-DiTdUVxp.js} +1 -1
- package/dist/ui/assets/{main-DDf8pkef.js → main-DzWg1TK_.js} +3 -3
- package/dist/ui/assets/{mount-BVsAhg7N.js → mount-4B-1d5oh.js} +2 -2
- package/dist/ui/assets/{mount-DeYTNAtM.js → mount-CY0WMJLG.js} +1 -1
- package/dist/ui/assets/{mount-recovery-C-JrPN0s.js → mount-recovery-DBMLMXSG.js} +1 -1
- package/dist/ui/assets/{new-session-B3XnJuqv.js → new-session-jeNmXk7P.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-Bk9dDOws.js → oauth-bootstrap-8ihF-R_z.js} +2 -2
- package/dist/ui/assets/{openai-codex-Cttg7uJd.js → openai-codex-BzNYKmfn.js} +1 -1
- package/dist/ui/assets/{openai-codex-rUO7vr1U.js → openai-codex-lPthoW8r.js} +1 -1
- package/dist/ui/assets/{openrouter-Ciu6vAC3.js → openrouter-BknXSW5c.js} +1 -1
- package/dist/ui/assets/{openrouter-H9gP72-I.js → openrouter-mwt9jwZa.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-D5iIE6cP.js → openrouter-oauth-B65Wk580.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-CH1L0i5l.js → openrouter-oauth-BXgZzA3Q.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-Ba_8QBpT.js → panel-rpc-handlers-NEPkzdP3.js} +2 -2
- package/dist/ui/assets/{panelize-shell-CRWRRDY-.js → panelize-shell-C8nHDKSj.js} +1 -1
- package/dist/ui/assets/{provider-NdjBqWJ5.js → provider-BD2eMVRi.js} +2 -2
- package/dist/ui/assets/{provider-DZdn3I7g.js → provider-l9BFMaHE.js} +1 -1
- package/dist/ui/assets/{provider-settings-VeKZEiaM.js → provider-settings-8XzaJ7Uj.js} +1 -1
- package/dist/ui/assets/{provider-settings-Bzx7Hz1h.js → provider-settings-CsTcfP8K.js} +1 -1
- package/dist/ui/assets/provider-store-access-DO9H0PId.js +1 -0
- package/dist/ui/assets/{provider-store-access-BmqtHWK-.js → provider-store-access-DdMRpexA.js} +2 -2
- package/dist/ui/assets/{providers-BPYoyMTa.js → providers-Bybk43BU.js} +1 -1
- package/dist/ui/assets/{providers-BTiNdb0r.js → providers-CGzsfbUR.js} +2 -2
- package/dist/ui/assets/{quick-llm-D-0thqIh.js → quick-llm-BjHgHVhH.js} +1 -1
- package/dist/ui/assets/{recovery-screen-m5rTUbFa.js → recovery-screen-J3JWTpgF.js} +1 -1
- package/dist/ui/assets/{redirect-uri-DC3PdAtX.js → redirect-uri-UNLwkF71.js} +1 -1
- package/dist/ui/assets/{run-BQU0xqGp.js → run-BvngdJSx.js} +1 -1
- package/dist/ui/assets/{session-freezer-DrAZJ5E8.js → session-freezer-Dp8tR_wX.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-CzuJ2Tg_.js → setup-feature-flags-remote-4vmTEIMx.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-Dx27VBt_.js → setup-standalone-prelude-4rQCXLGL.js} +1 -1
- package/dist/ui/assets/{setup-sudo-CzZlm0VE.js → setup-sudo-D-pI9Wj_.js} +2 -2
- package/dist/ui/assets/{skills-DvboiQ8x.js → skills-DFSM0Mzw.js} +1 -1
- package/dist/ui/assets/slicc-version-DamSgLEW.js +1 -0
- package/dist/ui/assets/{state-CinEep0w.js → state-Bxe7U2uR.js} +1 -1
- package/dist/ui/assets/{store-Bd-S5pB-.js → store-BwjB3mN4.js} +1 -1
- package/dist/ui/assets/{store-Dja6bYOS.js → store-DgTQh3uY.js} +1 -1
- package/dist/ui/assets/{sudo-DaziFK_O.js → sudo-B1uN4VjQ.js} +1 -1
- package/dist/ui/assets/{sync-dialog-ACgl0n-p.js → sync-dialog-Dc1-z8ys.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-d83JrIre.js → upgrade-detection-Dm6JI5c7.js} +1 -1
- package/dist/ui/assets/{wc-attach-Ddg-AFpA.js → wc-attach-2iyRKvmt.js} +2 -2
- package/dist/ui/assets/{wc-extension-DaLJ8MK5.js → wc-extension-DvH_frrB.js} +2 -2
- package/dist/ui/assets/{wc-float-label-DFKw-L8x.js → wc-float-label-CPaEzWWM.js} +1 -1
- package/dist/ui/assets/{wc-floatbar-online-ClCS1sKy.js → wc-floatbar-online-GqMjLIby.js} +1 -1
- package/dist/ui/assets/{wc-follower-CcRLAOwf.js → wc-follower-3cX8fmJu.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-DN3SywTT.js → wc-follower-oauth-B_i4VloV.js} +1 -1
- package/dist/ui/assets/{wc-live-DWITCUer.js → wc-live-M5a3sBeq.js} +4 -4
- package/dist/ui/assets/{wc-nav-DCvL8tCQ.js → wc-nav-CHWKuXtU.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CAB4TQKL.js → wc-onboarding-BKIUSDvB.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-QhAINQdh.js → wc-placeholder-bZ8QbN6-.js} +2 -2
- package/dist/ui/assets/{wc-settings-C9KYDbqg.js → wc-settings-CBxN34VQ.js} +2 -2
- package/dist/ui/assets/{wc-shell-BQha7IeK.js → wc-shell-Cdl88M0O.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-B002nt0y.js → wc-shortcut-config-kW-FDTbf.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-D50_-OOl.js → wc-sprinkles-CZHZhfaV.js} +2 -2
- package/dist/ui/assets/{wc-tray-Bj2fhjCA.js → wc-tray-XaKABUZZ.js} +4 -4
- package/dist/ui/assets/{xai-grok-bqBopgqi.js → xai-grok-D0_yKThq.js} +1 -1
- package/dist/ui/assets/{xai-grok-B__xNVnH.js → xai-grok-ktVvnBiV.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/lucide-icons.js +180 -179
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +2 -2
- package/dist/ui/assets/icons-ZLR7gmJ4.js +0 -1
- package/dist/ui/assets/provider-store-access-Dhsrpl15.js +0 -1
- package/dist/ui/assets/slicc-version-DWDKasUe.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{n as i,r as a,t as o}from"./panel-rpc-BPwAqRch.js";import{a as s,t as c}from"./providers-BPYoyMTa.js";import{r as l,t as u}from"./base64-DzRgusa4.js";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./src-CcFD5QfS.js";import{i as _,r as v,t as y}from"./proxied-fetch-BduXImRw.js";import{_ as b,b as x,d as S,f as C,h as w,i as T,l as E,m as D,p as ee,r as te,u as ne,v as re,y as O}from"./account-store-JfqGLwpx.js";import{t as ie}from"./runtime-env-DadgceZk.js";import{r as ae}from"./binary-cache-bSOhqXB1.js";import{n as oe,r as se,t as ce}from"./fetch-body-DDu_AU5I.js";import{a as le,i as ue,n as de,o as fe,r as pe,s as k,t as me}from"./api-endpoint-C00IT5T9.js";import{a as he,i as ge,n as _e,t as ve}from"./path-utils-DNJG-zQf.js";import{a as ye,i as be,n as xe,r as Se,t as A}from"./agent-bridge-CuRwAl_F.js";import{$ as j,A as Ce,At as we,B as M,Bt as Te,C as N,Ct as Ee,D as P,Dt as F,E as De,Et as Oe,F as ke,Ft as Ae,G as I,Gt as je,H as Me,Ht as Ne,I as Pe,It as L,J as Fe,K as Ie,L as Le,Lt as Re,M as ze,Mt as Be,N as Ve,Nt as He,O as Ue,Ot as We,P as Ge,Pt as Ke,Q as qe,R as eee,Rt as Je,S as Ye,St as Xe,T as Ze,Tt as R,U as Qe,Ut as $e,V as et,Vt as tt,W as nt,Wt as rt,X as it,Y as at,Z as ot,_ as st,_t as ct,a as lt,at as ut,b as dt,bt as z,c as ft,ct as tee,d as pt,dt as mt,et as ht,f as gt,ft as _t,g as vt,gt as yt,h as bt,ht as xt,i as St,it as nee,j as Ct,jt as wt,k as Tt,kt as Et,l as Dt,lt as Ot,m as kt,mt as At,nt as jt,o as Mt,ot as Nt,p as Pt,pt as Ft,q as It,rt as Lt,s as Rt,st as zt,t as Bt,tt as Vt,u as Ht,ut as Ut,v as Wt,vt as Gt,w as Kt,wt as qt,x as Jt,xt as Yt,y as Xt,yt as B,z as Zt,zt as Qt}from"./core-BVWxlTTk.js";import{a as $t}from"./models-4WTk3EBD.js";import{o as en,t as tn}from"./compat-Dujkqs4W.js";import{t as nn}from"./__vite-browser-external-5eBdwsFd.js";import{n as rn,t as ree}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as an}from"./image-markers-D3wDAnBQ.js";import{C as on,D as sn,E as cn,O as ln,S as un,T as dn,_ as fn,a as pn,b as mn,c as hn,d as gn,f as _n,g as vn,h as yn,i as bn,k as xn,l as Sn,m as Cn,n as wn,o as Tn,p as En,r as Dn,s as On,t as kn,u as An,v as jn,w as Mn,x as Nn,y as Pn}from"./descriptor-Bh6C6cqu.js";import{a as Fn,c as In,i as Ln,l as Rn,o as zn,r as iee,s as aee,u as oee}from"./agent-message-to-chat-CjWIKGH-.js";import{n as Bn,t as Vn}from"./thinking-level-5x0UAu9N.js";import{t as Hn}from"./types-idfTVsM8.js";import{i as Un}from"./mount-index-BCzDM4LQ.js";import{a as see,i as cee,n as lee,o as Wn,r as Gn,s as Kn}from"./mount-DeYTNAtM.js";import{o as qn}from"./mount-table-store-DrF_Ifaz.js";import{t as Jn}from"./remote-cache-JAv9sQH_.js";import{r as Yn,t as Xn}from"./mount-recovery-C-JrPN0s.js";import{a as Zn,c as Qn,i as $n,n as er,o as tr,r as nr,s as rr}from"./lick-urls-CLl4eksX.js";import"./runtime-env-DVGQx9p3.js";import{C as ir,D as ar,E as or,S as sr,_ as cr,a as lr,b as ur,d as dr,g as fr,h as pr,m as mr,n as hr,o as gr,r as _r,s as vr,t as yr,u as br,w as xr,y as Sr}from"./db-DSIYsBgP.js";import{i as Cr,n as wr,r as Tr,t as Er}from"./tray-url-config-Cx0gvYq6.js";import"./tray-runtime-config-CjsIUSv2.js";import{n as Dr,r as Or,t as kr}from"./slicc-version-DWDKasUe.js";import{a as Ar,c as jr,i as Mr,l as Nr,o as Pr,r as Fr,s as Ir,t as Lr,u as Rr}from"./lick-manager-y-5bIVRR.js";import{i as zr,n as Br,r as Vr}from"./fs-DBHB4fgS.js";import{a as V,c as Hr,i as Ur,l as Wr,n as Gr,o as Kr,r as qr,s as H,u as Jr}from"./cost-command-DNKXuXCE.js";import{n as Yr,r as Xr,t as Zr}from"./subcommand-help-CgO7wRS5.js";import{a as Qr,c as $r,d as uee,f as ei,h as ti,i as dee,l as ni,m as ri,n as ii,o as fee,p as ai,r as oi,s as pee,u as mee}from"./sudoers-KgJRnN4b.js";import{a as si,i as hee,n as gee,o as _ee,r as ci,s as vee}from"./skills-DvboiQ8x.js";import{n as yee,t as bee}from"./llm-session-id-BZyXP_j2.js";import{n as xee,r as See}from"./frozen-archive-format-CLzdz05B.js";import{r as li,t as ui}from"./key-vY4yxo3l.js";import{n as di,r as fi}from"./derive-D0xHQ8be.js";import{i as pi,r as mi}from"./browser-2rCVqcqy.js";import{a as hi,i as gi,n as _i,r as vi,t as yi}from"./telemetry-BwapcULJ.js";import{n as bi,t as xi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{_ as Si,a as Ci,b as wi,c as Ti,d as Ei,f as Di,g as U,h as Oi,i as ki,l as Ai,m as ji,n as Mi,o as Ni,p as Pi,r as Fi,s as Ii,t as Li,u as Ri,v as zi,y as Bi}from"./state-CinEep0w.js";import{a as Vi,i as Hi,r as Ui,t as Wi}from"./git-config-Bdgu8kD2.js";import{a as Gi,c as Ki,i as qi,o as Ji,r as Yi,s as Xi,t as Zi}from"./script-catalog-Bt94D0RP.js";import{t as Qi}from"./process-manager-BkhAohXT.js";import{F as $i,I as ea,M as ta,P as na,S as ra,_ as ia,a as aa,b as oa,c as sa,d as ca,f as la,g as ua,h as da,i as fa,j as pa,l as ma,m as ha,n as ga,o as _a,p as va,r as ya,s as ba,t as xa,u as Sa,v as Ca,w as wa,x as Ta,y as Ea}from"./shared-CPVZc-MN.js";import{n as Da,t as Oa}from"./esbuild-wasm-Dl3vgXvq.js";import{n as ka,t as Aa}from"./wasm-compiler-Ct7QZURL.js";import{n as ja,r as Ma,t as Na}from"./just-bash-compat-_TMo8UnL.js";import{t as Pa}from"./html-B_Hg2WOy.js";import{_ as Fa,a as Ia,c as La,f as Ra,g as za,h as Ba,l as Va,m as Ha,n as Ua,p as Wa,r as Ga,u as Ka,v as qa,y as Ja}from"./github-zip-Cp0IybNw.js";import{a as Ya,c as Xa,d as Za,f as Qa,i as $a,l as eo,n as to,o as no,p as ro,r as io,s as ao,u as oo}from"./github-install-Co8RGcCz.js";import{n as so,t as co}from"./magick-wasm-266b8ntc.js";import{i as lo,n as uo,r as fo,t as po}from"./pdf-raster-BWk6ezTX.js";import{t as mo}from"./permissions-surface-registry-BqPdUk9w.js";import{a as ho,c as go,d as _o,f as vo,i as yo,l as bo,n as xo,o as So,p as Co,r as wo,s as To,t as Eo,u as Do}from"./installer-VcJEC2uC.js";import{t as Oo}from"./local-llm-CWEg0rcm.js";import{t as ko}from"./client-Beg9O208.js";import{t as Ao}from"./redirect-uri-DC3PdAtX.js";var jo=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 Mo(e,t,n){return new Promise((r,i)=>{let a=null,o=!1,s=setTimeout(()=>{o=!0,a?.(),i(Error(n))},t);a=e(e=>{clearTimeout(s),o=!0,a?.(),r(e)}),o&&a()})}const No=r(`cdp`);var Cee=class{ws=null;nextId=1;_superseded=!1;pending=new jo;listeners=new Map;_state=`disconnected`;get state(){return this._state}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,No.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(No.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(),No.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),No.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 Mo(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;No.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(No.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;No.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){let t=e===4001;t?(this._superseded=!0,No.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):No.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}};const Po=r(`har-recorder`);var wee=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n){let r=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client.send(`Network.enable`,{},t),await this.client.send(`Page.enable`,{},t);let i=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,a={id:r,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:i,snapshotCount:0};return this.recordings.set(r,a),this.setupEventListeners(a),await this.ensureDir(`/recordings/${r}`),Po.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}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=>{Po.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=>{Po.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 Tee(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Po.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 Po.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)),Po.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 Po.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 Tee(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){Po.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Po.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Fo=`(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{n as i,r as a,t as o}from"./panel-rpc-BPwAqRch.js";import{a as s,t as c}from"./providers-Bybk43BU.js";import{r as l,t as u}from"./base64-DzRgusa4.js";import{a as d,i as f,n as p,r as m,s as h,t as g}from"./src-CcFD5QfS.js";import{i as _,r as v,t as y}from"./proxied-fetch-BduXImRw.js";import{_ as b,b as x,d as S,f as C,h as w,i as T,l as E,m as D,p as ee,r as te,u as ne,v as re,y as O}from"./account-store-B5g-mrn8.js";import{t as ie}from"./runtime-env-DadgceZk.js";import{r as ae}from"./binary-cache-bSOhqXB1.js";import{n as oe,r as se,t as ce}from"./fetch-body-DDu_AU5I.js";import{a as le,i as ue,n as de,o as fe,r as pe,s as k,t as me}from"./api-endpoint-C00IT5T9.js";import{a as he,i as ge,n as _e,t as ve}from"./path-utils-DNJG-zQf.js";import{a as ye,i as be,n as xe,r as Se,t as A}from"./agent-bridge-DJ2Gh9VA.js";import{$ as j,A as Ce,At as we,B as M,Bt as Te,C as N,Ct as Ee,D as P,Dt as F,E as De,Et as Oe,F as ke,Ft as Ae,G as I,Gt as je,H as Me,Ht as Ne,I as Pe,It as L,J as Fe,K as Ie,L as Le,Lt as Re,M as ze,Mt as Be,N as Ve,Nt as He,O as Ue,Ot as We,P as Ge,Pt as Ke,Q as qe,R as eee,Rt as Je,S as Ye,St as Xe,T as Ze,Tt as R,U as Qe,Ut as $e,V as et,Vt as tt,W as nt,Wt as rt,X as it,Y as at,Z as ot,_ as st,_t as ct,a as lt,at as ut,b as dt,bt as z,c as ft,ct as tee,d as pt,dt as mt,et as ht,f as gt,ft as _t,g as vt,gt as yt,h as bt,ht as xt,i as St,it as nee,j as Ct,jt as wt,k as Tt,kt as Et,l as Dt,lt as Ot,m as kt,mt as At,nt as jt,o as Mt,ot as Nt,p as Pt,pt as Ft,q as It,rt as Lt,s as Rt,st as zt,t as Bt,tt as Vt,u as Ht,ut as Ut,v as Wt,vt as Gt,w as Kt,wt as qt,x as Jt,xt as Yt,y as Xt,yt as B,z as Zt,zt as Qt}from"./core-CGasZgKz.js";import{a as $t}from"./models-4WTk3EBD.js";import{o as en,t as tn}from"./compat-Dujkqs4W.js";import{t as nn}from"./__vite-browser-external-5eBdwsFd.js";import{n as rn,t as ree}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as an}from"./image-markers-D3wDAnBQ.js";import{C as on,D as sn,E as cn,O as ln,S as un,T as dn,_ as fn,a as pn,b as mn,c as hn,d as gn,f as _n,g as vn,h as yn,i as bn,k as xn,l as Sn,m as Cn,n as wn,o as Tn,p as En,r as Dn,s as On,t as kn,u as An,v as jn,w as Mn,x as Nn,y as Pn}from"./descriptor-Bh6C6cqu.js";import{a as Fn,c as In,i as Ln,l as Rn,o as zn,r as iee,s as aee,u as oee}from"./agent-message-to-chat-CjWIKGH-.js";import{n as Bn,t as Vn}from"./thinking-level-5x0UAu9N.js";import{t as Hn}from"./types-idfTVsM8.js";import{i as Un}from"./mount-index-BCzDM4LQ.js";import{a as see,i as cee,n as lee,o as Wn,r as Gn,s as Kn}from"./mount-CY0WMJLG.js";import{o as qn}from"./mount-table-store-DrF_Ifaz.js";import{t as Jn}from"./remote-cache-JAv9sQH_.js";import{r as Yn,t as Xn}from"./mount-recovery-DBMLMXSG.js";import{a as Zn,c as Qn,i as $n,n as er,o as tr,r as nr,s as rr}from"./lick-urls-CLl4eksX.js";import"./runtime-env-DVGQx9p3.js";import{C as ir,D as ar,E as or,S as sr,_ as cr,a as lr,b as ur,d as dr,g as fr,h as pr,m as mr,n as hr,o as gr,r as _r,s as vr,t as yr,u as br,w as xr,y as Sr}from"./db-DSIYsBgP.js";import{i as Cr,n as wr,r as Tr,t as Er}from"./tray-url-config-Cx0gvYq6.js";import"./tray-runtime-config-CjsIUSv2.js";import{n as Dr,r as Or,t as kr}from"./slicc-version-DamSgLEW.js";import{a as Ar,c as jr,i as Mr,l as Nr,o as Pr,r as Fr,s as Ir,t as Lr,u as Rr}from"./lick-manager-y-5bIVRR.js";import{i as zr,n as Br,r as Vr}from"./fs-BhUjB1cK.js";import{a as V,c as Hr,i as Ur,l as Wr,n as Gr,o as Kr,r as qr,s as H,u as Jr}from"./cost-command-DNKXuXCE.js";import{n as Yr,r as Xr,t as Zr}from"./subcommand-help-CgO7wRS5.js";import{a as Qr,c as $r,d as uee,f as ei,h as ti,i as dee,l as ni,m as ri,n as ii,o as fee,p as ai,r as oi,s as pee,u as mee}from"./sudoers-KgJRnN4b.js";import{a as si,i as hee,n as gee,o as _ee,r as ci,s as vee}from"./skills-DFSM0Mzw.js";import{n as yee,t as bee}from"./llm-session-id-BZyXP_j2.js";import{n as xee,r as See}from"./frozen-archive-format-CLzdz05B.js";import{r as li,t as ui}from"./key-vY4yxo3l.js";import{n as di,r as fi}from"./derive-D0xHQ8be.js";import{i as pi,r as mi}from"./browser-2rCVqcqy.js";import{a as hi,i as gi,n as _i,r as vi,t as yi}from"./telemetry-BwapcULJ.js";import{n as bi,t as xi}from"./safe-buffer-OLJ0qaLt.js";import"./global-db-DJXlpNui.js";import{_ as Si,a as Ci,b as wi,c as Ti,d as Ei,f as Di,g as U,h as Oi,i as ki,l as Ai,m as ji,n as Mi,o as Ni,p as Pi,r as Fi,s as Ii,t as Li,u as Ri,v as zi,y as Bi}from"./state-Bxe7U2uR.js";import{a as Vi,i as Hi,r as Ui,t as Wi}from"./git-config-Bdgu8kD2.js";import{a as Gi,c as Ki,i as qi,o as Ji,r as Yi,s as Xi,t as Zi}from"./script-catalog-Bt94D0RP.js";import{t as Qi}from"./process-manager-BkhAohXT.js";import{F as $i,I as ea,M as ta,P as na,S as ra,_ as ia,a as aa,b as oa,c as sa,d as ca,f as la,g as ua,h as da,i as fa,j as pa,l as ma,m as ha,n as ga,o as _a,p as va,r as ya,s as ba,t as xa,u as Sa,v as Ca,w as wa,x as Ta,y as Ea}from"./shared-CPVZc-MN.js";import{n as Da,t as Oa}from"./esbuild-wasm-Dl3vgXvq.js";import{n as ka,t as Aa}from"./wasm-compiler-Ct7QZURL.js";import{n as ja,r as Ma,t as Na}from"./just-bash-compat-_TMo8UnL.js";import{t as Pa}from"./html-B_Hg2WOy.js";import{_ as Fa,a as Ia,c as La,f as Ra,g as za,h as Ba,l as Va,m as Ha,n as Ua,p as Wa,r as Ga,u as Ka,v as qa,y as Ja}from"./github-zip-CKXdHtbK.js";import{a as Ya,c as Xa,d as Za,f as Qa,i as $a,l as eo,n as to,o as no,p as ro,r as io,s as ao,u as oo}from"./github-install-C_CLyb3u.js";import{n as so,t as co}from"./magick-wasm-266b8ntc.js";import{i as lo,n as uo,r as fo,t as po}from"./pdf-raster-BWk6ezTX.js";import{t as mo}from"./permissions-surface-registry-BqPdUk9w.js";import{a as ho,c as go,d as _o,f as vo,i as yo,l as bo,n as xo,o as So,p as Co,r as wo,s as To,t as Eo,u as Do}from"./installer-VcJEC2uC.js";import{t as Oo}from"./local-llm-CBszF_hu.js";import{t as ko}from"./client-Beg9O208.js";import{t as Ao}from"./redirect-uri-UNLwkF71.js";var jo=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 Mo(e,t,n){return new Promise((r,i)=>{let a=null,o=!1,s=setTimeout(()=>{o=!0,a?.(),i(Error(n))},t);a=e(e=>{clearTimeout(s),o=!0,a?.(),r(e)}),o&&a()})}const No=r(`cdp`);var Cee=class{ws=null;nextId=1;_superseded=!1;pending=new jo;listeners=new Map;_state=`disconnected`;get state(){return this._state}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,No.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(No.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(),No.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),No.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 Mo(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;No.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(No.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;No.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){let t=e===4001;t?(this._superseded=!0,No.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):No.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}};const Po=r(`har-recorder`);var wee=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n){let r=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.client.send(`Network.enable`,{},t),await this.client.send(`Page.enable`,{},t);let i=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,a={id:r,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:i,snapshotCount:0};return this.recordings.set(r,a),this.setupEventListeners(a),await this.ensureDir(`/recordings/${r}`),Po.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}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=>{Po.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=>{Po.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 Tee(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Po.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 Po.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)),Po.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 Po.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 Tee(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){Po.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Po.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Fo=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -1643,7 +1643,7 @@ except BaseException:
|
|
|
1643
1643
|
`)}}function hz(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=_z(e.stdin??``,o),c=az(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:ea},version:`v${ea}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new fz(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var gz=class extends gP.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 fz){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 _z(e,t){return new gz(e,t)}function vz(e){if(e===``)return[];let t=e.split(`
|
|
1644
1644
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function yz(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function bz(e){return new TextDecoder(`utf-8`).decode(yN(e))}function xz(e){if(e&&typeof e.write==`function`)return e}var Sz=class extends uP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=vz(bz(yz(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 fz&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function Cz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=xz(e.output)}else r=t,i=xz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new Sz(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:Sz,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var wz=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`?`: ${Tz(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 Tz(e){try{return JSON.stringify(e)}catch{return String(e)}}function Ez(e){return new Promise(t=>setTimeout(t,e))}function Dz(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 Oz(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?Dz(r,n):r}function kz(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 Az(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function jz(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 Mz(e){if(Az(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 Nz(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 Pz(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t.toLowerCase())}async function Fz(e,t,n){let r=await t(n);r&&!Pz(e,`authorization`)&&(e.Authorization=`Bearer ${r}`)}function Iz(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 Lz(e,t){return{body:t,headers:Object.fromEntries(e.headers.entries()),status:e.status}}async function Rz(e,t){let n=await Mz(e);return t?Lz(e,n):n}async function zz(e,t){let n=await Mz(e).catch(()=>null);throw new wz(e.status,e.statusText,t,n)}function Bz(e,t){let n=jz(e.headers.get(`retry-after`));return n===null?500*2**t:n}async function Vz(e,t,n,r){let i=null;for(let a=0;a<e.maxAttempts;a++){let{signal:o,clearTimeout:s}=Iz(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 Rz(l,r.raw);if(!(a+1<e.maxAttempts&&e.retryOn.has(l.status)))return zz(l,t);await e.sleep(Bz(l,a))}if(i)return zz(i,t);throw Error(`http: no attempts made for ${n.method??`GET`} ${t}`)}function Hz(e){let t=e.sleep??Ez;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=Oz(n.baseUrl,o,s.params),l=kz(n.headers,s.headers);n.token&&await Fz(l,n.token,{method:a,path:o,url:c});let u=Nz(s.body,l),d={method:a,headers:l};return u!==void 0&&(d.body=u),Vz({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 Uz(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 Wz(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`,Uz(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 Gz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Wz(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 Kz(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 qz(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=Kz(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 Jz(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(e?.body!==void 0&&e?.body!==null&&e?.body!==``){let t=await Yz(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 Yz(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:Xz(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:Xz(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:Xz(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),defaultContentType:`application/octet-stream`};throw typeof FormData<`u`&&e instanceof FormData?Error(`node fetch shim: FormData request bodies are not supported (post raw application/x-www-form-urlencoded with URLSearchParams instead)`):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, or URLSearchParams`)}function Xz(e){let t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode(...e.subarray(n,n+32768)));return t.join(``)}function Zz(e){return{findTab:t=>e.call(`browser`,`findTab`,[$z(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,eB(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Kz(t),Qz(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Kz(t),Qz(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Kz(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Kz(t),n]),fetch:(t,n,r={})=>zi(n,r).then(n=>e.call(`browser`,`evalAsync`,[Kz(t),n])),websocket:qz(e)}}function Qz(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 $z(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 eB(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function tB(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function nB(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:tB(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function rB(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 iB(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function aB(e){return e==null?[]:Array.isArray(e)?e:[e]}function oB(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:iB(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,rB(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,rB(r)]),receiveFeatureReport:async t=>iB((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 sB(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>oB(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[aB(t)]))[0];if(!n)throw Error(`No device selected.`);return oB(e,n)}}}function cB(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 lB=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 };`)}},uB=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=cB(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 lB(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 lB(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?.())}},dB=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 uB(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()}},fB=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 uB(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 dB(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 pB(e){let t=async t=>new fB(e),n=async(t,n)=>new fB(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const mB=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`]),hB={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 gB(e,t){let n=hB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function _B(e){return{...e,time:uz,fmt:XN,pool:oz}}function vB(e,t){return e?.startsWith(`/`)?dz(e):t}function yB(e){return e.includes(`require`)||e.includes(`import`)}async function bB(e,t,n,r){return yB(t)?e.call(`module`,`buildGraph`,[t,vB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function xB(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 SB(e){return{playwright:pB(e)}}function CB(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c,nodeOsModule:l=cF}=e,u=new Map(t.files.map(e=>[e.path,e.cjsSource])),d=new Map(t.files.map(e=>[e.path,e.kind])),f=new Map,p=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:EB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=wB(t,n,r,i,l,c);if(a.hit)return a;if(mB.has(t))throw gB(e,t);if($i.has(t))throw OB(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},m=(e,n)=>{let r=p(n);if(r.hit)return r.value;let i=e?.[n];if(i)return h(i);throw n in t.errors?Error(t.errors[n]):TB(n)};function h(e){let n=f.get(e);if(n)return n.exports;let i=u.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};f.set(e,o);let s=n=>m(t.edges[e],n),c=dz(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,c,e,r,a,globalThis.Buffer,globalThis),d.get(e)===`cjs`&&xB(o.exports),o.exports}return{require:e=>m(t.entryMap,e)}}function wB(e,t,n,r,i,a){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:yF}:e===`crypto`?{hit:!0,value:rF}:e===`child_process`?{hit:!0,value:r}:e===`process`?{hit:!0,value:n}:e===`buffer`?{hit:!0,value:{Buffer:globalThis.Buffer}}:e===`assert`?{hit:!0,value:cP}:e===`assert/strict`?{hit:!0,value:sP}:e===`util`?{hit:!0,value:MP}:e===`events`?{hit:!0,value:dP}:e===`os`?{hit:!0,value:i}:e===`tty`?{hit:!0,value:bF}:e===`stream`?{hit:!0,value:gP}:e===`url`?{hit:!0,value:CF}:e===`zlib`?{hit:!0,value:rz}:e===`readline`&&a?{hit:!0,value:a}:e===`readline/promises`&&a?{hit:!0,value:a.promises}:{hit:!1}}function TB(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 EB(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 DB={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function OB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${DB[t]||``}`)}async function kB(e,t,n,r){let i=Object.keys(t),a=i.map(e=>t[e]),o=Object.getPrototypeOf(async function(){}).constructor,s=new o(...i,`${r?`"use strict";
|
|
1645
1645
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof fz?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function AB(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?rB(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,rB(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function jB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>AB(e,t)),request:async t=>AB(e,await e.call(`serial`,`request`,[aB(t)]))}}function MB(e,t){let n=t.handle,r=e=>({status:e.status,data:iB(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),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,rB(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,rB(r)])}}function NB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>MB(e,t)),request:async t=>MB(e,await e.call(`usb`,`request`,[aB(t)]))}}function PB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function FB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function IB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function LB(e){let t=PB(e.argv[1]??``),n=IB(t,`references`),r=IB(t,`assets`),i=IB(t,`.config`);async function a(){let t;try{t=await e.fs.exists(i)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(i)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let a;try{a=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${i}: ${t}`)}if(a&&typeof a==`object`&&!Array.isArray(a))return a;throw Error(`skill.config(): ${i} must contain a JSON object`)}async function o(t){let n=await a();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(i,JSON.stringify(r,null,2)+`
|
|
1646
|
-
`),r}async function s(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${FB(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,refs:n,assets:r,config:o,token:s})}const RB=new Map,zB=new Map;function BB(e){let t=crypto.randomUUID();return RB.set(t,e),t}function VB(e){return RB.get(e)??null}function HB(e,t){if(!RB.has(e))return t.abort(),()=>{};let n=zB.get(e);return n||(n=new Set,zB.set(e,n)),n.add(t),()=>{let n=zB.get(e);n&&(n.delete(t),n.size===0&&zB.delete(e))}}function UB(e){RB.delete(e);let t=zB.get(e);if(t){zB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function WB(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 GB(e){let t=VB(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 WB(e)}}function KB(e){return`slicc-sync-fs-`+e}const qB=`sync-fs-ack`,JB=`sync-fs-res`,YB=6e5,XB=5e3,ZB=`exec`;function QB(e){return e.channel===ZB}function $B(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 eV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,YB)}async function tV(e){let t=VB(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=$B(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()},eV(e.timeoutMs,YB)),o=HB(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`}:WB(e)}finally{clearTimeout(a),o()}}function nV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function rV(e){let t=aV(e);if(oV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw nV(`EIO`,e.label);sV(t,e.label)}function iV(e){let t=rV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw nV(`EIO`,e.label)}}function aV(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 nV(`EIO`,e.label)}return t}function oV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function sV(e,t){throw nV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function cV(e){return(t,n,r)=>{let i=iV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:ZB})),timeoutMs:n+XB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw nV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function lV(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 uV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??cV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&lV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=eV(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 dV(e,t){return nV(e,`sync-fs bridge, '${t}'`)}function fV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function pV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:fV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return rV(r(`GET`,e))},writeFile(e,t){rV(r(`POST`,e,t))},stat(e){let t=iV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw dV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=iV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw dV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=iV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw dV(`EIO`,e);return t},exists(e){let t=iV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw dV(`EIO`,e);return t},mkdir(e){rV(r(`POST`,e,void 0,`mkdir`))},rm(e){rV(r(`POST`,e,void 0,`rm`))}}}const mV=new TextEncoder,hV=new TextDecoder;function gV(e){if(!e.ok)return{status:4,payload:mV.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:mV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function _V(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(hV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(hV.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 vV(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 yV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function bV(e,t,n={}){let{header:r,window:i}=vV(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 nV(`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 nV(`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 nV(`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 nV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return _V(f,d)}}}function xV(e,t){return nV(e,`sync-sab bridge, '${t}'`)}function SV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function CV(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 xV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw xV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw xV(`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(!SV(t))throw xV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!SV(t))throw xV(`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 xV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw xV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function wV(e){return(t,n,r)=>{let i=e.call({...t,channel:ZB},n+XB,r);if(!i.ok)throw nV(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 nV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function TV(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 _N(r)}function EV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function DV(e,t){return t?CV(t):e.syncFsToken?pV(e.syncFsToken):void 0}function OV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return bV(e.syncSab,t)}function kV(e,t,n,r,i){let a=OV(e,t),o=DV(e,a);if(Object.assign(r,LN(n,e.cwd,o,i)),e.syncFsToken)return uV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:wV(a)}:{}})}function AV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Dr().version,writable:!1,enumerable:!1,configurable:!1})}function jV(e,t,n){let r=BN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:RN({writeStdout:t,writeStderr:n,exit:e=>{throw new fz(e)},color:r})}}function MV(e,t,n){return{readStdinBytes:()=>yN(e.stdin??``),writeStdout:t,writeStderr:n}}function NV(e){return{usbBridge:NB(e),serialBridge:jB(e),hidBridge:sB(e)}}async function PV(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=mz(i,a),s=hz(e,i,a),{colorApi:c,cliApi:l}=jV(!!e.env?.NO_COLOR,i,a),u=new OM(t),d=MV(e,i,a),f=jN(u,C,d),p=await TV(u,e.cwd,EV(e,a)),m=kV(e,t,p,f,d),h=nB(u,p,e.cwd,a),g=Gz(h,{cwd:e.cwd}),_=LB({argv:e.argv,fs:f,exec:h}),v=Zz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=NV(u),S=Hz({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await u.call(`fetch`,`request`,[n,await Jz(t,e)]),i=r.body.byteLength===0?null:r.body.buffer.slice(r.body.byteOffset,r.body.byteOffset+r.body.byteLength),a=new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers});return Object.defineProperty(a,"url",{value:r.url||n}),a}let w=_B({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=dz(T),D=await bB(u,e.code,e.cwd,T),ee=CB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:VP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:SB(u),nodeReadline:Cz({output:{write:i},onExit:s.recordExit}),nodeOsModule:sF(e.env)}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0,re=D.entrySource??e.code,O=globalThis;AV(),O.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ie=await kB(re,{process:s.processShim,console:o,require:ee,module:te,exports:te.exports,fetch:C,__dirname:E,__filename:T},a,ne);await FV(u,p,a),s.getDidCallProcessExit()?ie=s.getExitCode():await IV(u),delete O.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ie})}async function FV(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r])}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 IV(e){let t=Date.now()+1e3,n=0;do await new Promise(e=>setTimeout(e,0)),n++;while(e.pendingCount>0&&n<50&&Date.now()<t)}function LV(){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 RV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=LV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&PV(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 zV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=LV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&zM(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 BV=RV(),VV=zV();function HV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?WV():VV({kind:e,ctx:t}):typeof Worker<`u`?UV():BV({kind:e,ctx:t})}function UV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return GV(new Worker(new URL(`/assets/js-realm-worker-C11HEtiw.js`,``+import.meta.url),{type:`module`}))}function WV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return GV(new Worker(new URL(`/assets/py-realm-worker-D1gqcTkl.js`,``+import.meta.url),{type:`module`}))}function GV(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 KV(){if(va())return decodeURIComponent(ua(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function qV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function JV(e){return e instanceof Error?e.message:String(e)}function YV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function XV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:YV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function ZV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:YV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const QV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,$V=/\bimport\s*\.\s*meta\b/g;function eH(e,t){let n=JSON.stringify(t);return e.replace(QV,n).replace($V,`({ url: ${n} })`)}async function tH(e,t,n,r){let i=await e();return i.transpileModule(eH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function nH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Da(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ca(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ta(e))return e;let a=qV(t),o;try{return await XV(n,e,t,a)}catch(e){o=e}try{return await tH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${JV(o)}; typescript fallback: ${JV(e)}`)}}}function rH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Da(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ca(t));return async({source:e,filename:t})=>{if(!Ta(e)&&!oa(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?qV(t):void 0,o=i?t:`[eval].js`,s;try{return await ZV(n,e,t,a)}catch(e){s=e}try{return await tH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${JV(s)}; typescript fallback: ${JV(e)}`)}}}function iH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1646
|
+
`),r}async function s(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${FB(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,refs:n,assets:r,config:o,token:s})}const RB=new Map,zB=new Map;function BB(e){let t=crypto.randomUUID();return RB.set(t,e),t}function VB(e){return RB.get(e)??null}function HB(e,t){if(!RB.has(e))return t.abort(),()=>{};let n=zB.get(e);return n||(n=new Set,zB.set(e,n)),n.add(t),()=>{let n=zB.get(e);n&&(n.delete(t),n.size===0&&zB.delete(e))}}function UB(e){RB.delete(e);let t=zB.get(e);if(t){zB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function WB(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 GB(e){let t=VB(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 WB(e)}}function KB(e){return`slicc-sync-fs-`+e}const qB=`sync-fs-ack`,JB=`sync-fs-res`,YB=6e5,XB=5e3,ZB=`exec`;function QB(e){return e.channel===ZB}function $B(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 eV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,YB)}async function tV(e){let t=VB(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=$B(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()},eV(e.timeoutMs,YB)),o=HB(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`}:WB(e)}finally{clearTimeout(a),o()}}function nV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function rV(e){let t=aV(e);if(oV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw nV(`EIO`,e.label);sV(t,e.label)}function iV(e){let t=rV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw nV(`EIO`,e.label)}}function aV(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 nV(`EIO`,e.label)}return t}function oV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function sV(e,t){throw nV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function cV(e){return(t,n,r)=>{let i=iV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:ZB})),timeoutMs:n+XB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw nV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function lV(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 uV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??cV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&lV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=eV(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 dV(e,t){return nV(e,`sync-fs bridge, '${t}'`)}function fV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function pV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:fV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return rV(r(`GET`,e))},writeFile(e,t){rV(r(`POST`,e,t))},stat(e){let t=iV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw dV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=iV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw dV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=iV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw dV(`EIO`,e);return t},exists(e){let t=iV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw dV(`EIO`,e);return t},mkdir(e){rV(r(`POST`,e,void 0,`mkdir`))},rm(e){rV(r(`POST`,e,void 0,`rm`))}}}const mV=new TextEncoder,hV=new TextDecoder;function gV(e){if(!e.ok)return{status:4,payload:mV.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:mV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function _V(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(hV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(hV.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 vV(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 yV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function bV(e,t,n={}){let{header:r,window:i}=vV(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 nV(`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 nV(`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 nV(`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 nV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return _V(f,d)}}}function xV(e,t){return nV(e,`sync-sab bridge, '${t}'`)}function SV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function CV(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 xV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw xV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw xV(`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(!SV(t))throw xV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!SV(t))throw xV(`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 xV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw xV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function wV(e){return(t,n,r)=>{let i=e.call({...t,channel:ZB},n+XB,r);if(!i.ok)throw nV(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 nV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function TV(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 _N(r)}function EV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function DV(e,t){return t?CV(t):e.syncFsToken?pV(e.syncFsToken):void 0}function OV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return bV(e.syncSab,t)}function kV(e,t,n,r,i){let a=OV(e,t),o=DV(e,a);if(Object.assign(r,LN(n,e.cwd,o,i)),e.syncFsToken)return uV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:wV(a)}:{}})}function AV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Dr().version,writable:!1,enumerable:!1,configurable:!1})}function jV(e,t,n){let r=BN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:RN({writeStdout:t,writeStderr:n,exit:e=>{throw new fz(e)},color:r})}}function MV(e,t,n){return{readStdinBytes:()=>yN(e.stdin??``),writeStdout:t,writeStderr:n}}function NV(e){return{usbBridge:NB(e),serialBridge:jB(e),hidBridge:sB(e)}}async function PV(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=mz(i,a),s=hz(e,i,a),{colorApi:c,cliApi:l}=jV(!!e.env?.NO_COLOR,i,a),u=new OM(t),d=MV(e,i,a),f=jN(u,C,d),p=await TV(u,e.cwd,EV(e,a)),m=kV(e,t,p,f,d),h=nB(u,p,e.cwd,a),g=Gz(h,{cwd:e.cwd}),_=LB({argv:e.argv,fs:f,exec:h}),v=Zz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=NV(u),S=Hz({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await u.call(`fetch`,`request`,[n,await Jz(t,e)]),i=r.body.byteLength===0?null:r.body.buffer.slice(r.body.byteOffset,r.body.byteOffset+r.body.byteLength),a=new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers});return Object.defineProperty(a,"url",{value:r.url||n}),a}let w=_B({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=dz(T),D=await bB(u,e.code,e.cwd,T),ee=CB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:VP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:SB(u),nodeReadline:Cz({output:{write:i},onExit:s.recordExit}),nodeOsModule:sF(e.env)}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0,re=D.entrySource??e.code,O=globalThis;AV(),O.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ie=await kB(re,{process:s.processShim,console:o,require:ee,module:te,exports:te.exports,fetch:C,__dirname:E,__filename:T},a,ne);await FV(u,p,a),s.getDidCallProcessExit()?ie=s.getExitCode():await IV(u),delete O.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ie})}async function FV(e,t,n){let r=t.getMutations();if(r.created.length||r.modified.length||r.deleted.length)try{await e.call(`vfs`,`flushWrites`,[r])}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 IV(e){let t=Date.now()+1e3,n=0;do await new Promise(e=>setTimeout(e,0)),n++;while(e.pendingCount>0&&n<50&&Date.now()<t)}function LV(){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 RV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=LV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&PV(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 zV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=LV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&zM(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 BV=RV(),VV=zV();function HV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?WV():VV({kind:e,ctx:t}):typeof Worker<`u`?UV():BV({kind:e,ctx:t})}function UV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return GV(new Worker(new URL(`/assets/js-realm-worker-B8Mm9E9s.js`,``+import.meta.url),{type:`module`}))}function WV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return GV(new Worker(new URL(`/assets/py-realm-worker-D1gqcTkl.js`,``+import.meta.url),{type:`module`}))}function GV(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 KV(){if(va())return decodeURIComponent(ua(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function qV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function JV(e){return e instanceof Error?e.message:String(e)}function YV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function XV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:YV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function ZV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:YV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const QV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,$V=/\bimport\s*\.\s*meta\b/g;function eH(e,t){let n=JSON.stringify(t);return e.replace(QV,n).replace($V,`({ url: ${n} })`)}async function tH(e,t,n,r){let i=await e();return i.transpileModule(eH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function nH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Da(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ca(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Ta(e))return e;let a=qV(t),o;try{return await XV(n,e,t,a)}catch(e){o=e}try{return await tH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${JV(o)}; typescript fallback: ${JV(e)}`)}}}function rH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Da(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ca(t));return async({source:e,filename:t})=>{if(!Ta(e)&&!oa(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?qV(t):void 0,o=i?t:`[eval].js`,s;try{return await ZV(n,e,t,a)}catch(e){s=e}try{return await tH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${JV(s)}; typescript fallback: ${JV(e)}`)}}}function iH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1647
1647
|
`);return t===-1?``:e.slice(t+1)}function aH(e){return he(e).dir}const oH=[`node`,`require`,`default`],sH=[`node`,`import`,`default`],cH=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,lH=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,uH=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,dH=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,fH=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function pH(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function mH(e){let t=ra(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!pH(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(cH,`require`,`require`),r(lH,`import`,`import`),r(uH,`import`,`import`),r(dH,`import`,`export`),r(fH,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function hH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=iH(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ${xa} esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function gH(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??oH,s=e.importConditions??sH,c=i??o,l=new Map,u=[],d={};async function f(e,t){if(l.has(e))return;let n=await r.readFile(e),i=await hH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=aH(e),p={};for(let{specifier:t,kind:i}of mH(n)){let n;try{n=await wa(t,c,r,{conditions:i===`import`?s:o})}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`While loading '${e}': ${n}`)}n.type===`file`&&(p[t]=n.path,await f(n.path,n.moduleKind))}d[e]=p,u.push(e)}let p={};for(let e of t){let t=await wa(e,n,r,{conditions:c});t.type===`file`&&(p[e]=t.path,await f(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:p,edges:d}}function _H(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||na.has(e)||mB.has(e))}async function vH(e){let{entryCode:t,fromDir:n,entryFilename:r,reader:i,transpile:a,transpileEntry:o}=e,s=new Map,c=[],l={},u={},d={};for(let{specifier:e,kind:r}of mH(t))if(_H(e))try{let t=await gH({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?sH:oH,requireConditions:oH,importConditions:sH});for(let e of t.files)s.has(e.path)||(s.set(e.path,e),c.push(e.path));Object.assign(l,t.entryMap);for(let[e,n]of Object.entries(t.edges))u[e]={...u[e]??{},...n}}catch(t){d[e]=t instanceof Error?t.message:String(t)}let f;o&&(Ta(t)||oa(t))&&(f=await o({source:t,filename:r??`[eval]`,fromDir:n}));let p={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,errors:d};return f!==void 0&&(p.entrySource=f),p}function yH(){return globalThis.navigator?.hid??null}function bH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function xH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&bH(e)===bH(t)&&!!e.productName}var SH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(xH(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 CH=null;function wH(){return CH||=new SH,CH}const TH=4194304;function EH(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 DH(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function OH(e){e.opened||await e.open()}function kH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${TH}-byte (4 MiB) v1 limit`)}function AH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function jH(e,t){return(await t.getDevices()).map(t=>EH(e.register(t),t))}async function MH(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>EH(e.register(t),t))}function NH(e,t){return EH(t,DH(e,t))}async function PH(e,t){await DH(e,t).open()}async function FH(e,t){await DH(e,t).close()}async function IH(e,t,n,r){kH(r.byteLength,`send report payload`);let i=DH(e,t);await OH(i),await i.sendReport(n,r)}async function LH(e,t,n,r){kH(r.byteLength,`send feature report payload`);let i=DH(e,t);await OH(i),await i.sendFeatureReport(n,r)}async function RH(e,t,n){let r=DH(e,t);return await OH(r),{reportId:n,bytes:AH(await r.receiveFeatureReport(n))}}async function zH(e,t,n){let r=DH(e,t);await OH(r);let i=e=>{n({reportId:e.reportId,bytes:AH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const BH=6e4;function VH(){return tC()}function HH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),BH);nC(`hid-device`,e??[],void 0,{timeoutMs:BH}).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 UH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var WH=class{registry;constructor(e){this.registry=e}hid(){let e=yH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return jH(this.registry,this.hid())}async request(e){if(VH()){let t=await HH(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=>EH(this.registry.register(e),e))}return MH(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(NH(this.registry,e))}open(e){return PH(this.registry,e)}close(e){return FH(this.registry,e)}sendReport(e,t,n){return IH(this.registry,e,t,UH(n))}sendFeatureReport(e,t,n){return LH(this.registry,e,t,UH(n))}async receiveFeatureReport(e,t){let n=await RH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return zH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},GH=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:UH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:UH(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 KH(e,t){return e&&yH()?new WH(wH()):t?new GH(t):null}function qH(e){return async function(t,n){let r=t instanceof Request?t:null,i=JH(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=XH(r?.headers,n?.headers),s=await $H(n,r,a,o);s.defaultContentType&&!ZH(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 JH(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function YH(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 XH(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=YH(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function ZH(e,t){return QH(e,t)!==void 0}function QH(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function $H(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=nU(e.body,n);return{body:await eU(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=QH(r,`content-type`)??``,a=e&&(!i||!_(i));return{body:n.byteLength===0?void 0:a?rU(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function eU(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 rU(e);if(e instanceof ArrayBuffer)return rU(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return rU(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return rU(new Uint8Array(await e.arrayBuffer()));throw typeof FormData<`u`&&e instanceof FormData?Error(`node fetch shim: FormData request bodies are not supported (post raw application/x-www-form-urlencoded with URLSearchParams instead)`):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, or URLSearchParams`)}}function tU(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function nU(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!tU(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function rU(e){let t=32768,n=``;for(let r=0;r<e.byteLength;r+=t)n+=String.fromCharCode(...e.subarray(r,r+t));return n}function iU(){return globalThis.navigator?.serial??null}var aU=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 oU=null;function sU(){return oU||=new aU,oU}const cU=4194304;function lU(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 uU(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function dU(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function fU(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 pU(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 mU(e){if(await pU(e),e.opened){try{await e.port.close()}catch{}e.opened=!1}}async function hU(e,t){let n=await t.getPorts();for(let{entry:t}of e.retainOnly(n))await mU(t);return n.map(t=>{let n=e.register(t);return lU(n,e.get(n))})}async function gU(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return lU(i,e.get(i))}function _U(e,t){return lU(t,uU(e,t))}async function vU(e,t,n){let r=uU(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 yU(e,t){let n=uU(e,t);await pU(n);try{await n.port.close()}catch(e){if(!bU(e))throw e}n.opened=!1}function bU(e){let t=e instanceof Error?e.message:String(e);return/already closed|not open/i.test(t)}function xU(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 SU(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 CU(e,t,n){let r=uU(e,t),i=Math.min(n.maxBytes??4194304,cU),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=fU(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=xU(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=dU(c,a.value);let e=u();if(e)return e}}return c}async function wU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${cU}-byte (4 MiB) v1 limit`);return await SU(uU(e,t)).write(n),n.length}async function TU(e,t){return uU(e,t).port.getSignals()}async function EU(e,t,n){await uU(e,t).port.setSignals(n)}const DU=6e4;function OU(){return tC()}function kU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),DU);nC(`serial-port`,e??[],void 0,{timeoutMs:DU}).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 AU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var jU=class{registry;constructor(e){this.registry=e}serial(){let e=iU();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return hU(this.registry,this.serial())}async request(e){if(OU()){let t=await kU(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 lU(r,this.registry.get(r))}return gU(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(_U(this.registry,e))}open(e,t){return vU(this.registry,e,t)}close(e){return yU(this.registry,e)}read(e,t){return CU(this.registry,e,t)}write(e,t){return wU(this.registry,e,t)}getSignals(e){return TU(this.registry,e)}setSignals(e,t){return EU(this.registry,e,t)}},MU=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?AU(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:AU(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 NU(e,t){return e&&iU()?new jU(sU()):t?new MU(t):null}function PU(){return globalThis.navigator?.usb??null}function FU(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var IU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(FU(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 LU=null;function RU(){return LU||=new IU,LU}const zU=4194304;function BU(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}}function VU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function HU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${zU}-byte (4 MiB) v1 limit`)}function UU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function WU(e,t){return(await t.getDevices()).map(t=>BU(e.register(t),t))}async function GU(e,t,n){let r=await t.requestDevice({filters:n});return BU(e.register(r),r)}function KU(e,t){return BU(t,VU(e,t))}async function qU(e,t){await VU(e,t).open()}async function JU(e,t){await VU(e,t).close()}async function YU(e,t,n){await VU(e,t).selectConfiguration(n)}async function XU(e,t,n){await VU(e,t).claimInterface(n)}async function ZU(e,t,n){await VU(e,t).releaseInterface(n)}async function QU(e,t,n,r){HU(r,`control-in length`);let i=await VU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?UU(i.data):new ArrayBuffer(0)}}async function $U(e,t,n,r){HU(r.byteLength,`control-out payload`);let i=await VU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function eW(e,t,n,r){HU(r,`transfer-in length`);let i=await VU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?UU(i.data):new ArrayBuffer(0)}}async function tW(e,t,n,r){HU(r.byteLength,`transfer-out payload`);let i=await VU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function nW(e,t){await VU(e,t).reset()}const rW=6e4;function iW(){return tC()}function aW(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),rW);nC(`usb-device`,e??[],void 0,{timeoutMs:rW}).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 oW(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var sW=class{registry;constructor(e){this.registry=e}usb(){let e=PU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return WU(this.registry,this.usb())}async request(e){if(iW()){let t=await aW(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 BU(this.registry.register(n),n)}return GU(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(KU(this.registry,e))}open(e){return qU(this.registry,e)}close(e){return JU(this.registry,e)}selectConfig(e,t){return YU(this.registry,e,t)}claim(e,t){return XU(this.registry,e,t)}release(e,t){return ZU(this.registry,e,t)}async controlIn(e,t,n){let r=await QU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return $U(this.registry,e,t,oW(n))}async transferIn(e,t,n){let r=await eW(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return tW(this.registry,e,t,oW(n))}reset(e){return nW(this.registry,e)}},cW=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:oW(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:oW(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function lW(e,t){return e&&PU()?new sW(RU()):t?new cW(t):null}function uW(e,t,n,r={}){let{header:i,window:a}=vV(t),o=new Map,s=!1,c=r.dispatch??(e=>QB(e)?tV(e):GB(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}=gV(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 dW=r(`realm-host`);function fW(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?BB({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;pW(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?uW(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&UB(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 pW(e,t,n,r,i,a){try{let o=await mW(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=rG(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 mW(e,t,n,r,i){switch(e.channel){case`vfs`:return bW(e.op,e.args,t);case`exec`:return NW(e.op,e.args,t,i);case`fetch`:return LW(e.op,e.args,t);case`browser`:return VW(e.op,e.args,hW(n),n);case`usb`:return eG(e.op,e.args,_W(n));case`serial`:return tG(e.op,e.args,vW(n));case`hid`:return nG(e.op,e.args,yW(n),r);case`module`:return zW(e.op,e.args,t);case`wasm`:return BW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function hW(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 gW(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 _W(e){if(e.usbBackend)return e.usbBackend;let t=lW(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function vW(e){if(e.serialBackend)return e.serialBackend;let t=NU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function yW(e){if(e.hidBackend)return e.hidBackend;let t=KH(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function bW(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 kW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await AW(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const xW=10485760;function SW(e){return e.fileCount>=500||e.totalBytes>=xW}function CW(e){return e.entries.length>=2e4}async function wW(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 TW(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 EW(e,t,n,r,i){if(n>1048576||SW(r)||r.totalBytes+n>xW){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 DW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function DW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await wW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function OW(e,t,n){if(CW(n))return;let r=[t];for(;r.length>0;){if(CW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await TW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await wW(e,t,r,n):a.isFile&&await EW(e,t,a.size,n,r)}}async function kW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await OW(e,t,n),t!==`/tmp`&&await OW(e,`/tmp`,n),{entries:n.entries}}async function AW(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 jW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),MW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function NW(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 FW(t,n,r);if(e===`kill`)return IW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function PW(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 FW(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??{};PW(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 IW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&jW.has(r)?r:`SIGTERM`;MW.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 LW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?qH(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 RW(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 zW(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=RW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return vH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:nH({ipk:s}),transpileEntry:rH({ipk:s})})}async function BW(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 Aa(e=>n.fs.readFileBuffer(e),i)}async function VW(e,t,n,r){switch(e){case`findTab`:return WW(n,t[0]??{});case`ensureTab`:{let e=t[0];return GW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return KW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return KW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return XW(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return ZW(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await gW(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return gW(r).update(e,n)}case`wsClose`:{let e=t[0];return gW(r).close(e)}case`wsList`:return gW(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,async()=>{await n.setViewportOverride(e,r,i)})}case`navigateTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>{await n.navigate(r)})}case`screenshotTab`:{let e=t[0],r=t[1];return n.withTab(e,async()=>(await n.bringToFront(),n.screenshot(r)))}case`waitForLoadState`:{let e=t[0],r=t[1];return YW(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function HW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function UW(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=HW()?i():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){dW.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function WW(e,t){let n=await UW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=QW(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 GW(e,t,n){let r=await UW(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=$W(t);if(e){let t=r.find(t=>$W(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function KW(e,t,n,r){return e.withTab(t,async()=>qW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function qW(e){if(typeof e!=`string`)return e;let t=JW(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=JW(t);if(typeof e==`object`&&e)return e}return t}return e}function JW(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 YW(e,t,n){if(n===`networkidle`)return e.withTab(t,async()=>{for(let t=0;t<20;t++)if(await new Promise(e=>setTimeout(e,250)),await e.evaluate(`(function(){
|
|
1648
1648
|
try {
|
|
1649
1649
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1660,7 +1660,7 @@ except BaseException:
|
|
|
1660
1660
|
})()`,{returnByValue:!0}))return})}async function XW(e,t,n){return e.withTab(t,async()=>{let t=((await e.sendCDP(`Network.getCookies`)).cookies??[]).find(e=>e.name===n);return t&&typeof t.value==`string`?t.value:null})}async function ZW(e,t,n){return e.withTab(t,async()=>{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 QW(e){try{return new URL(e).hostname}catch{return null}}function $W(e){try{return new URL(e).origin}catch{return null}}async function eG(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`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 tG(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 nG(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 rG(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 iG(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?aG(e.syncSabBytes):void 0,a=fW(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:!!e.syncFsBridgeEnabled||i!==void 0,...i?{syncSab:i}:{}});return new Promise(t=>{let o=!1,s=null,c=null,l=null,u=null,d=()=>{c&&r.controlPort.removeEventListener(`message`,c),r.removeEventListener&&(l&&r.removeEventListener(`error`,l),u&&r.removeEventListener(`messageerror`,u)),s?.(),a.dispose()},f=(i,a)=>{if(!o){o=!0,d();try{r.terminate()}catch{}e.pm.exit(n.pid,a),t(i)}};c=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;f({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;f({stdout:``,stderr:t.message+`
|
|
1661
1661
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1662
1662
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1663
|
-
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function aG(e){if(yV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let oG=!1;function sG(e){oG=e}function cG(){return oG}const lG=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 uG(e){return lG[e]??null}function dG(e,t){let n=uG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let fG=null;function pG(e){let t=fG;return fG=e,t}async function mG(){if(!fG)return{};try{return await fG()??{}}catch{return{}}}function hG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-
|
|
1663
|
+
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function aG(e){if(yV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let oG=!1;function sG(e){oG=e}function cG(){return oG}const lG=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 uG(e){return lG[e]??null}function dG(e,t){let n=uG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let fG=null;function pG(e){let t=fG;return fG=e,t}async function mG(){if(!fG)return{};try{return await fG()??{}}catch{return{}}}function hG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t);return dG(t(),e())}}async function gG(e,t,n,r,i={}){return await n.fs.exists(e)?_G(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 _G(e,t,n,r,i={}){let a=i.realmFactory??vG(),o=r?.processManager??xG()??bG(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await iG({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await mG(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:ja(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:cG()})}function vG(){return typeof Worker<`u`||typeof document<`u`?HV():RV()}let yG=null;function bG(){return yG||=new Qi,yG}function xG(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function SG(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 CG=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=Rt();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?wG(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=TG(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:TG(i)})})}};async function wG(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function TG(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function EG(e,t){return t.length?`${e} ${t.join(` `)}`:e}function DG(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function OG(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:DG(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 kG={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}},AG=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function jG(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 MG(e,t){switch(e.type){case`CommandSubstitution`:return UG(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=MG(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function NG(e,t){let n=0;for(let r of e.parts){let e=MG(r,t);if(e===null)return null;n+=e}return n}function PG(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=NG(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=NG(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=jG(e.name);if(r===null||AG.has(r))return null;if(!t.has(r))return n;n+=1;let i=kG[r];if(i){let r=e.args.map(jG);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(AG.has(a))return null;t.has(a)&&(n+=1)}return n}function FG(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 IG(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||jG(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=jG(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 LG(e){let t=0;for(let n of e){let e=n.type===`Word`?RG(n.word):FG(n);if(e===null)return null;t+=e}return t}function RG(e){let t=IG(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=LG(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function zG(e){let t=0;for(let n of e){let e=RG(n);if(e===null)return null;t+=e}return t}function BG(e,t){let n=0;for(let r of e){let e=HG(r,t);if(e===null)return null;n+=e}return n}function VG(e,t){switch(e.type){case`SimpleCommand`:return PG(e,t);case`For`:{if(!e.words)return null;let n=zG(e.words),r=BG(e.body,t);return n===null||r===null?null:e.words.filter(e=>IG(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return BG(e.body,t);case`FunctionDef`:return 0;default:return null}}function HG(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=VG(e,t);if(r===null)return null;n+=r}return n}function UG(e,t){return BG(e.statements,t)}function WG(e,t){let n=UG(e,t);return{totalSteps:n!==null&&n>0?n:null}}function GG(e){return e.split(`
|
|
1664
1664
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var KG=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 qG=globalThis.setTimeout.bind(globalThis);function JG(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function YG(e,t={}){let n=t.now??Date.now,r=t.setTimeout??qG,i=t.isAborted??(()=>!1),a=t.label??JG,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 XG=globalThis.setTimeout.bind(globalThis);function ZG(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 QG(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 $G(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??XG;return{...e,async execute(n,a){let o=QG(n),s=o>=0?ZG(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=EG(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 eK=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 tK(e,t,n={}){if((n.skip??eK).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=EG(r,n);t.emit({id:a,label:o,phase:`start`});try{return await e.execute(n,i)}finally{t.emit({id:a,label:o,phase:`end`})}}}}function nK(e){return si(`sudo`,e)}async function rK(e,t){let n=e.trim();if(!n||dee(ni(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:nK(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const iK={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 aK(e,t=[],n){let r=iK[e],i=t.length?` data-action-data='${JSON.stringify({filters:t}).replace(/'/g,`'`)}'`:``,a=e===`directory`&&n?`<div class="sprinkle-action-card__meta">Target: ${Pa(n)}</div>`:``;return`
|
|
1665
1665
|
<div class="sprinkle-action-card">
|
|
1666
1666
|
<div class="sprinkle-action-card__header">
|
|
@@ -1778,7 +1778,7 @@ Examples:
|
|
|
1778
1778
|
skill list
|
|
1779
1779
|
skill info bluebubbles
|
|
1780
1780
|
skill read bluebubbles
|
|
1781
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1781
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-DFSM0Mzw.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${UK()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:GK(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1782
1782
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:KK(r),stderr:``,exitCode:0}:{stdout:``,stderr:`skill: "${n}" not found\n`,exitCode:1}}case`read`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: read requires a skill name
|
|
1783
1783
|
`,exitCode:1};let r=await i.readSkillInstructions(e,n);return r===null?{stdout:``,stderr:`skill: no SKILL.md found for "${n}"\n`,exitCode:1}:{stdout:r+`
|
|
1784
1784
|
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const YK=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&Ir(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=>$a(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=>jr(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 XK(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=YK.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 ZK(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function QK(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 $K(e,t,n,r){let i=await QK(e,t);return Wa(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?ZK(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function eq(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await $K(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 Ha(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 tq(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 Va(t),d=await Za(s,c,o.ref,u,!0);if(d&&r.sha===d&&await nq(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await rq(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 eq(e,`${za}/${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 cq(e,{changes:h,writes:g,removals:_}),await ro(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 nq(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 rq(e,t,n,r,i,a,o){let s=await Ga(e,t,a,i??`main`);if(s.status===`ok`){let i=Ia(s.files),a=n||iq(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:sq(i,a),path:a}}try{return{files:oq(aq(await Ua(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 iq(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 aq(e){return new Map([...e].filter(([e])=>La(e)))}function oq(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function sq(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);La(e)&&r.set(e,i)}return oq(r)}async function cq(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 lq(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 VK(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${za}/${n}/SKILL.md`,u=await QK(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&zK(new TextDecoder().decode(u))===zK(c.content);if(ZK(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${za}/${n}`,{recursive:!0}),await e.writeFile(l,d),await ro(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function uq(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 dq(e,t,n,r){let i=$a(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 fq(e,t,n){if(t.length===0){let t=await Qa(e);return{targets:t.provenanced,missing:[],skipped:t.unattributed}}let r=[],i=[];for(let a of t){let t=await oo(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?dq(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 pq(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -1811,7 +1811,7 @@ Examples:
|
|
|
1811
1811
|
`,{stdout:s,stderr:``,exitCode:0}}function kq(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1812
1812
|
`,exitCode:1}:Ir(e)?null:{stdout:``,stderr:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters
|
|
1813
1813
|
`,exitCode:1}}function Aq(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`||!jr(r))return t.earlyReturn={stdout:``,stderr:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters
|
|
1814
|
-
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=kq(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 jq(e){let t=await(await import(`./skills-
|
|
1814
|
+
`,exitCode:1},t;t.subPath=r}else if(r===`--list`)t.listOnly=!0;else if(r===`--all`)t.installAll=!0;else if(r===`--force`)t.force=!0;else if(r===`--branch`||r===`-b`){let r=kq(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 jq(e){let t=await(await import(`./skills-DFSM0Mzw.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${UK()}`,stderr:``,exitCode:0}:{stdout:GK(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function Mq(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-DFSM0Mzw.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 oo(n,t),a=i?eo(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:KK(e)+a,stderr:``,exitCode:0}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
1815
1815
|
`,stderr:``,exitCode:0}}async function Nq(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 no(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 Pq(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await to(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 Fq(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await to(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 Iq(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 Lq(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await Va(r),l=await io(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:Iq(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:Iq(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 Ga(i,a,r,o);if(e.status===`ok`){let r=await Za(i,a,o,c),s=await Nq(u,i,a,Ia(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 Pq(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await Fq(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 Xa()),{stdout:p,stderr:m,exitCode:+!!m}}async function Rq(e,t,n,r){switch(e[0]){case`tabs`:return Dq(t,n,r,e.includes(`--json`));case`recommendations`:return Oq(t,n,e.includes(`--install`));case`update`:case`upgrade`:return _q(e.slice(1),t,n);case`list`:return jq(t);case`info`:case`read`:return Mq(e[0],e[1],t);case`search`:return Bq(e,n);default:return null}}function zq(e,t,n){return H(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return qK();let a=await Rq(r,e,t,n);if(a)return a;let o=Aq(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return qK();if(o.sourceRef.startsWith(`tessl:`))return Vq(o.sourceRef,o.force,e,t);let s=IK(o.sourceRef);if(s)return HK(s.hostname,s.task,e,t,o.force);let c=$a(o.sourceRef);return c?Lq(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 Bq(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?Sq(a,t,i):qK()}async function Vq(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1816
1816
|
`,exitCode:1};let a=await yq(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await Va(r);return to(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function Hq(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1817
1817
|
|
|
@@ -2219,7 +2219,7 @@ Examples:
|
|
|
2219
2219
|
`;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+=`
|
|
2220
2220
|
`;return t}async function vZ(e){let t=V(e.slice(1),{});if(`error`in t)return hZ(t.error);if(!Ht()){let e=await cZ();if(!e)return dZ(`list`);let t=await e.listCronTasks();return t.length===0?{stdout:`No active cron tasks
|
|
2221
2221
|
`,stderr:``,exitCode:0}:{stdout:_Z(t),stderr:``,exitCode:0}}let{ok:n,data:r}=await pZ(`GET`,``);if(!n)return{stdout:``,stderr:`crontask: failed to list: ${r.error??`unknown error`}\n`,exitCode:1};let i=r;return i.length===0?{stdout:`No active cron tasks
|
|
2222
|
-
`,stderr:``,exitCode:0}:{stdout:_Z(i),stderr:``,exitCode:0}}async function yZ(e){let t=e[0],n=V(e.slice(1),{});if(`error`in n)return hZ(n.error);let r=n.positionals[0];if(!r)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(!Ht()){let e=await cZ();return e?await e.deleteCronTask(r)?{stdout:`Deleted cron task "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${r}" not found\n`,exitCode:1}:dZ(`delete`)}let{ok:i,status:a,data:o}=await pZ(`DELETE`,`/${r}`);return i?{stdout:`Deleted cron task "${r}"\n`,stderr:``,exitCode:0}:a===404?{stdout:``,stderr:`crontask: task "${r}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${o.error??`unknown error`}\n`,exitCode:1}}function bZ(){return H(`crontask`,async(e,t)=>{let n=e[0];if(!n||Zr(e,{valueFlags:mZ}))return fZ();try{switch(n){case`create`:return await gZ(e,t.env);case`list`:return await vZ(e);case`delete`:case`kill`:return await yZ(e);default:return{stdout:``,stderr:`crontask: unknown command "${n}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function xZ(e){return H(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-
|
|
2222
|
+
`,stderr:``,exitCode:0}:{stdout:_Z(i),stderr:``,exitCode:0}}async function yZ(e){let t=e[0],n=V(e.slice(1),{});if(`error`in n)return hZ(n.error);let r=n.positionals[0];if(!r)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(!Ht()){let e=await cZ();return e?await e.deleteCronTask(r)?{stdout:`Deleted cron task "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${r}" not found\n`,exitCode:1}:dZ(`delete`)}let{ok:i,status:a,data:o}=await pZ(`DELETE`,`/${r}`);return i?{stdout:`Deleted cron task "${r}"\n`,stderr:``,exitCode:0}:a===404?{stdout:``,stderr:`crontask: task "${r}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${o.error??`unknown error`}\n`,exitCode:1}}function bZ(){return H(`crontask`,async(e,t)=>{let n=e[0];if(!n||Zr(e,{valueFlags:mZ}))return fZ();try{switch(n){case`create`:return await gZ(e,t.env);case`list`:return await vZ(e);case`delete`:case`kill`:return await yZ(e);default:return{stdout:``,stderr:`crontask: unknown command "${n}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function xZ(e){return H(`curlwright`,async(t,n)=>{let{runCurlwright:r}=await import(`./run-BvngdJSx.js`);return r(e,t,n)})}const SZ=`slicc-fs`;async function CZ(){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===SZ)}catch{return!0}}async function wZ(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(SZ)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function TZ(){if(!await CZ())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await wZ();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 EZ(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
2223
2223
|
|
|
2224
2224
|
Usage:
|
|
2225
2225
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -3193,7 +3193,7 @@ Common base URLs:
|
|
|
3193
3193
|
`)+`
|
|
3194
3194
|
`,stderr:``,exitCode:0}}function Nce(e,t){let n=t.models.length;return{stdout:[`✓ ${e} (${v6(t.runtime,!1)})`,` Saved ${n} model${n===1?``:`s`} to Settings:`,...y6(t.models)].join(`
|
|
3195
3195
|
`)+`
|
|
3196
|
-
`,stderr:``,exitCode:0}}function Pce(){return H(_6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Ace(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-
|
|
3196
|
+
`,stderr:``,exitCode:0}}function Pce(){return H(_6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Ace(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),{verifyConnection:a}=await import(`./local-llm-CBszF_hu.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(_6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
3197
3197
|
`,exitCode:1};let c=await a(s,t(_6)??void 0);if(!c.ok)return jce(s,c);if(o===`discover`){let e=n(_6)??``;return i(_6,e,s,c.models.join(`, `)),Nce(s,c)}return Mce(s,c)})}function Fce(){return{stdout:`usage: man <topic>
|
|
3198
3198
|
|
|
3199
3199
|
Fetches documentation for a given topic from sliccy.com.
|
|
@@ -3231,20 +3231,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3231
3231
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3232
3232
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3233
3233
|
short name resolves on the PATH.
|
|
3234
|
-
`);let n=V(e,{});if(`error`in n)return w6(n.error);if(n.positionals.length<2)return C6(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return C6(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return C6(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3234
|
+
`);let n=V(e,{});if(`error`in n)return w6(n.error);if(n.positionals.length<2)return C6(`mcp add: expected <url> <name>`);let[r,i]=n.positionals;if(!/^https?:\/\//i.test(r))return C6(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return C6(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-DgTQh3uY.js`).then(e=>e.r);if(await a(i,t.fs))return C6(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-Beg9O208.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 Hce(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>k6(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 sle(i,t);let m=await M6(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-l9BFMaHE.js`);e({name:i,serverUrl:r,auth:u})}return S6([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${x6}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3235
3235
|
`)+`
|
|
3236
|
-
`)}async function Hce(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3237
|
-
`);let n=V(e,{});if(`error`in n)return w6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-
|
|
3236
|
+
`)}async function Hce(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),c=await ale(r.oauthFetchImpl),l=r.oauthLauncher??await A6(),u=await i(e,n,c);b6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await Ao(),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 Uce(e,t){if(Zr(e))return S6(`usage: mcp list
|
|
3237
|
+
`);let n=V(e,{});if(`error`in n)return w6(n.error);let{ensureAllMcpProvidersRegistered:r}=await import(`./provider-l9BFMaHE.js`);await r();let{listServers:i}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),a=await i(t.fs),o=Object.keys(a).sort();if(o.length===0)return S6("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 S6(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(`
|
|
3238
3238
|
`)+`
|
|
3239
3239
|
`}async function Wce(e,t){if(Zr(e))return S6(`usage: mcp search <query>
|
|
3240
3240
|
|
|
3241
3241
|
Case-insensitive substring search across the cached tools of every
|
|
3242
3242
|
registered MCP server. Matches tool name OR description and prints a
|
|
3243
3243
|
table of (server, tool, description, match-field) rows.
|
|
3244
|
-
`);let n=V(e,{});if(`error`in n)return w6(n.error);if(n.positionals.length===0)return C6(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-
|
|
3245
|
-
`);let n=V(e,{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-
|
|
3244
|
+
`);let n=V(e,{});if(`error`in n)return w6(n.error);if(n.positionals.length===0)return C6(`mcp search: expected <query>`);let r=n.positionals[0],i=r.toLowerCase(),{ensureAllMcpProvidersRegistered:a}=await import(`./provider-l9BFMaHE.js`);await a();let{listServers:o}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),s=await o(t.fs),c=Object.keys(s).sort();if(c.length===0)return S6("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 S6(`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,Gce(e.description),e.match]);return S6(T6(u))}function Gce(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Kce(e,t){if(e.length===0||Zr(e))return e.length===0?C6(`mcp delete: expected <name>`):S6(`usage: mcp delete <name>
|
|
3245
|
+
`);let n=V(e,{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp delete: expected <name>`);let{ensureMcpProviderRegistered:i,removeMcpProvider:a}=await import(`./provider-l9BFMaHE.js`);await i(r);let{deleteServer:o}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),s=await o(r,t.fs);await cle(r,t),await lle(r,t);let c=`mcp:${r}`,l=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t);t().some(e=>e.providerId===c)&&(await e(c),l=!0)}catch(e){b6.warn(`mcp delete: OAuth removal failed`,{providerId:c,error:e instanceof Error?e.message:String(e)})}let u=a(r);return!s&&!l&&!u?C6(`mcp delete: no server, alias, or account found for "${r}"`):S6([`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(`
|
|
3246
3246
|
`)+`
|
|
3247
|
-
`)}async function qce(e,t){if(e.length===0)return C6(`mcp invoke: expected <name>`);if(Zr(e.slice(0,1)))return S6(Yce());let n=V([e[0]],{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-
|
|
3247
|
+
`)}async function qce(e,t){if(e.length===0)return C6(`mcp invoke: expected <name>`);if(Zr(e.slice(0,1)))return S6(Yce());let n=V([e[0]],{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp invoke: expected <name>`);let i=e.slice(1),{ensureMcpProviderRegistered:a}=await import(`./provider-l9BFMaHE.js`);await a(r);let{getServer:o}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),s=await o(r,t.fs);if(!s)return C6(`mcp invoke: unknown server "${r}" (run \`mcp add <url> ${r}\` first)`);let c=s.tools??[];if(i.length===0||Zr(i.slice(0,1)))return S6(Xce(r,s,c));let l=V([i[0]],{});if(`error`in l)return w6(l.error);let u=l.positionals[0];if(!u)return C6(`mcp invoke: expected <tool>`);let d=c.find(e=>e.name===u);if(!d)return C6(`mcp invoke: unknown tool "${u}" on "${r}" (run \`${r}\` to list tools)`);let{timeoutMs:f,remaining:p,warnings:m}=Jce(i.slice(1));if(Zr(p))return S6(Zce(r,d));let h=Qce(p,d.inputSchema);if(!h.ok)return C6(`mcp invoke: ${h.error}`);let{McpClient:g}=await import(`./client-Beg9O208.js`).then(e=>e.n),_=new g({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>k6(r):void 0,...f===void 0?{}:{timeoutMs:f}});await _.initialize();let v=nle(await _.toolsCall(u,h.value));return m.length>0&&(v.stderr=m.map(e=>`${e}\n`).join(``)+v.stderr),v}function Jce(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=E6(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=E6(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 E6(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 Yce(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3248
3248
|
|
|
3249
3249
|
mcp invoke <name> List tools on <name>.
|
|
3250
3250
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3274,7 +3274,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3274
3274
|
|
|
3275
3275
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3276
3276
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3277
|
-
`);let n=V(e,{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3277
|
+
`);let n=V(e,{});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`mcp refresh: expected <name>`);let{ensureMcpProviderRegistered:i}=await import(`./provider-l9BFMaHE.js`);await i(r);let{getServer:a,setServer:o}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),s=await a(r,t.fs);if(!s)return C6(`mcp refresh: unknown server "${r}"`);let{McpClient:c,McpAuthRequiredError:l}=await import(`./client-Beg9O208.js`).then(e=>e.n),u=new c({url:s.url,fetchImpl:t.fetchImpl,headers:s.headers,getAuthHeader:s.auth?()=>k6(r):void 0});try{await u.initialize()}catch(e){if(e instanceof l)return C6(`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 M6(r,f,t);return S6(`Refreshed "${r}" — tools: ${d.length}, apps: ${f.length} (${p} sprinkle${p===1?``:`s`})\n`)}async function ile(e,t){if(Zr(e))return S6(`usage: mcp auth <name> [--silent | --interactive]
|
|
3278
3278
|
|
|
3279
3279
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3280
3280
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3286,7 +3286,7 @@ Options:
|
|
|
3286
3286
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3287
3287
|
directly. Use after revoking a refresh token or
|
|
3288
3288
|
when the AS no longer accepts the cached one.
|
|
3289
|
-
`);let n=V(e,{bool:Rce});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`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 C6(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3289
|
+
`);let n=V(e,{bool:Rce});if(`error`in n)return w6(n.error);let r=n.positionals[0];if(!r)return C6(`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 C6(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-l9BFMaHE.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-DgTQh3uY.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return C6(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return C6(`mcp auth: server "${r}" does not use OAuth`);if(!s)return C6(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-Bybk43BU.js`).then(e=>e.r),f=d(u);if(!f)return C6(`mcp auth: provider "${u}" is not registered`);if(a)return await O6(r,f,t);if(!f.onSilentRenew)return i?C6(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await O6(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 C6(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);b6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?S6(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?C6(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await O6(r,f,t)}async function O6(e,t,n){if(!t.onOAuthLogin)return C6(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await A6(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?S6(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):C6(`mcp auth: interactive login for "${e}" did not complete`)}async function k6(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-Bybk43BU.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){b6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function A6(){let{createOAuthLauncher:e}=await import(`./oauth-service-TDESX_tk.js`);return e()}async function ale(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-BduXImRw.js`).then(e=>e.n),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 j6(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BhUjB1cK.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 ole(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3290
3290
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3291
3291
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
3292
3292
|
const escape = (s) => {
|
|
@@ -3300,7 +3300,7 @@ const r = await exec(cmd);
|
|
|
3300
3300
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
3301
3301
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
3302
3302
|
process.exit(r.exitCode || 0);
|
|
3303
|
-
`}async function sle(e,t){let n=await j6(t.fs);await n.mkdir(x6,{recursive:!0}),await n.writeFile(`${x6}/${e}.jsh`,ole(e)),t.scriptCatalog?.invalidateJsh()}async function cle(e,t){let n=await j6(t.fs),r=`${x6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){b6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function lle(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3303
|
+
`}async function sle(e,t){let n=await j6(t.fs);await n.mkdir(x6,{recursive:!0}),await n.writeFile(`${x6}/${e}.jsh`,ole(e)),t.scriptCatalog?.invalidateJsh()}async function cle(e,t){let n=await j6(t.fs),r=`${x6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){b6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function lle(e,t){let{removeAppSprinkles:n}=await import(`./apps-CeTlBebf.js`);await n(e,t.fs)}async function M6(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-CeTlBebf.js`);return(await r(e,t,n.fs)).length}catch(t){return b6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function N6(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function P6(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 ule(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 dle(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function fle(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 ple(e){let t=[`total: ${P6(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(`${P6(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${ule(e)}`)}return`${t.join(`
|
|
3304
3304
|
`)}\n`}function mle(e={}){return H(`meminfo`,async t=>{let n=fle(t);if(`error`in n)return N6(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3305
3305
|
|
|
3306
3306
|
Usage:
|
|
@@ -3327,7 +3327,7 @@ Options:
|
|
|
3327
3327
|
-h, --help Show this help message
|
|
3328
3328
|
`}function Cle(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function z6(e){return`$${e.toFixed(2)}`}const wle=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Tle(e){let t=`${e.id} ${e.name??``}`;return!wle.test(t)}function Ele(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 Dle(e){let t=e.toLowerCase();return t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``),Ele(t)??t.replace(/-[\d.]+$/,``)}function Ole(e){let t=new Map;for(let n of e){let e=Dle(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function kle(e,t,n,r,i){let a=i?xle(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 Ale(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=`${z6(e.cost.input)} / ${z6(e.cost.output)}`,a=`${Cle(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(`
|
|
3329
3329
|
`)+`
|
|
3330
|
-
`}function jle(e){let t=V(e,{bool:hle,value:I6});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 Mle(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 Nle(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Tle);if(o.length===0)return[];let s=o.map(e=>kle(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Ole(s)),s}function Ple(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 Fle(e,t){if(Zr(e,{valueFlags:I6}))return{stdout:Sle(),stderr:``,exitCode:0};let n=jle(e);if(`error`in n)return L6(`models: ${n.error}`);let r=await import(`./account-store-
|
|
3330
|
+
`}function jle(e){let t=V(e,{bool:hle,value:I6});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 Mle(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 Nle(e,t,n,r,i,a){let o=e.getProviderModels(t).filter(Tle);if(o.length===0)return[];let s=o.map(e=>kle(e,t,n,r,i)).sort((e,t)=>t.cost.input-e.cost.input);return a||(s=Ole(s)),s}function Ple(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 Fle(e,t){if(Zr(e,{valueFlags:I6}))return{stdout:Sle(),stderr:``,exitCode:0};let n=jle(e);if(`error`in n)return L6(`models: ${n.error}`);let r=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t);if(r.getAccounts().length===0)return L6(`No provider accounts configured. Run the provider settings to add one.
|
|
3331
3331
|
`);let i=r.resolveCurrentModel(),a=i.id,o=i.provider,s=r.getSelectedProvider(),c=r.getSelectedModelId(),l;if(!n.noBenchmarks){let e=await ble(t,n.forceRefresh);e.length>0&&(l=e)}let u=Mle(r,n,s);if(`error`in u)return L6(u.error);let d=[],f=[];for(let e of u){let t=Nle(r,e,a,o,l,n.allVersions);if(t.length===0){if(!n.allMode)return L6(`No models available for provider ${e}.\n`);continue}if(d.push(...t),!n.jsonMode){let n=r.getProviderConfig(e);f.push(Ale(n.name,e,t,!!l))}}return n.jsonMode?{stdout:JSON.stringify(d,null,2)+`
|
|
3332
3332
|
`,stderr:``,exitCode:0}:(n.allVersions||f.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3333
3333
|
`),f.push(Ple(o,a,s,c)),{stdout:f.join(`
|
|
@@ -3373,7 +3373,7 @@ Examples:
|
|
|
3373
3373
|
`)}\n`,stderr:``,exitCode:0}}async function Jle(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
3374
3374
|
`,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 Yle(e,t,n){if(!t||!n)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
3375
3375
|
`,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 Xle(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>
|
|
3376
|
-
`,exitCode:1}}async function Zle(e,t,n,r){switch(t){case`list`:return qle(e,n);case`add`:return Jle(e,n,r);case`remove`:return Yle(e,n,r);case`clear`:return Xle(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${H6()}`,exitCode:1}}}function Qle(){return H(`oauth-domain`,async e=>{if(e.length===0||Zr(e))return{stdout:H6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return U6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-
|
|
3376
|
+
`,exitCode:1}}async function Zle(e,t,n,r){switch(t){case`list`:return qle(e,n);case`add`:return Jle(e,n,r);case`remove`:return Yle(e,n,r);case`clear`:return Xle(e,n);default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${t}"\n${H6()}`,exitCode:1}}}function Qle(){return H(`oauth-domain`,async e=>{if(e.length===0||Zr(e))return{stdout:H6(),stderr:``,exitCode:0};let t=V(e);if(`error`in t)return U6(t.error);let[n,r,i]=t.positionals,a=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t);try{return await Zle(a,n,r,i)}catch(e){return U6(e instanceof Error?e.message:String(e))}})}const $le={repo:[`repo:status`,`repo_deployment`,`public_repo`,`repo:invite`,`security_events`],user:[`read:user`,`user:email`,`user:follow`],project:[`read:project`]},eue={"admin:":[`write:`,`read:`],"write:":[`read:`]};function W6(e){return e?new Set(e.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)):new Set}function tue(e){let t=[...$le[e]??[]];for(let[n,r]of Object.entries(eue)){if(!e.startsWith(n))continue;let i=e.slice(n.length);if(i)for(let e of r)t.push(`${e}${i}`)}return t}function nue(e){let t=new Set(e),n=[...e];for(;n.length>0;){let e=n.pop();for(let r of tue(e))t.has(r)||(t.add(r),n.push(r))}return t}function rue(e,t){let n=W6(e);if(n.size===0)return!1;let r=W6(t);if(r.size===0)return!0;let i=nue(n);for(let e of r)if(!i.has(e))return!1;return!0}const G6=[`--provider`,`--scope`,`--from-file`,`--authorize-url`,`--redirect-pattern`,`--rewrite`],iue=[`--list`,`--expire`,`--renew`,`--intercept`,`--force-login`,`--leave-tab`];function aue(){return`oauth-token — get an OAuth access token for a provider, or run an
|
|
3377
3377
|
ad-hoc OAuth interception against an arbitrary authorize URL.
|
|
3378
3378
|
|
|
3379
3379
|
Usage:
|
|
@@ -3437,7 +3437,7 @@ Examples:
|
|
|
3437
3437
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
3438
3438
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
3439
3439
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
3440
|
-
`}function oue(){return H(`oauth-token`,sue)}async function sue(e,t){let n=await import(`./account-store-
|
|
3440
|
+
`}function oue(){return H(`oauth-token`,sue)}async function sue(e,t){let n=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),r=await import(`./providers-Bybk43BU.js`).then(e=>e.r);if(Zr(e,{valueFlags:G6}))return{stdout:aue(),stderr:``,exitCode:0};let i=V(e,{value:G6,bool:iue});if(`error`in i)return Z6(`oauth-token: ${i.error}`);if(i.bools.has(`--list`))return Cue(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(i.bools.has(`--expire`))return gue(i.positionals);if(i.bools.has(`--renew`))return _ue(i.positionals);if(i.values.has(`--from-file`)||i.bools.has(`--intercept`))return vue(i,e,t);let a=cue(i);if(!a.ok)return a.result;let o=i.bools.has(`--force-login`),s=lue(i,n,r);if(!s.ok)return s.result;let c=uue(s.value,r.getRegisteredProviderConfig);if(!c.ok)return c.result;if(!o){let e=await due(s.value,c.value,n.getOAuthAccountInfo,a.value);if(e)return e}return fue(s.value,c.value,a.value,n.getOAuthAccountInfo)}function cue(e){if(!e.values.has(`--scope`))return{ok:!0,value:void 0};let t=e.values.get(`--scope`)?.trim();return!t||t.startsWith(`-`)?{ok:!1,result:Z6(`oauth-token: --scope requires a value`)}:{ok:!0,value:t}}function lue(e,t,n){if(e.values.has(`--provider`)){let t=e.values.get(`--provider`);return t?{ok:!0,value:t}:{ok:!1,result:Z6(`oauth-token: --provider requires a value`)}}if(e.positionals.length>0)return{ok:!0,value:e.positionals[0]};let r=t.getSelectedProvider();if(K6(n.getRegisteredProviderConfig(r)))return{ok:!0,value:r};let i=n.getRegisteredProviderIds().find(e=>K6(n.getRegisteredProviderConfig(e)));return i?{ok:!0,value:i}:{ok:!1,result:Z6(`oauth-token: no OAuth providers configured`)}}function K6(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function uue(e,t){let n=t(e);return n?K6(n)?{ok:!0,value:n}:{ok:!1,result:Z6(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:Z6(`oauth-token: unknown provider "${e}"`)}}async function due(e,t,n,r){let i=n(e);return i&&!i.expired?q6(e,i,r):!i?.expired||!t.onSilentRenew||!await hue(t.onSilentRenew)?null:q6(e,n(e),r)}function q6(e,t,n){return n&&!rue(t?.scopes,n)?null:J6(e,t?.maskedValue)}function J6(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:Z6(`oauth-token: no masked value for ${e} (try logging in again)`)}async function fue(e,t,n,r){try{let i=await pue(e,t,n);return i.error?i.error:mue(e,r,i.succeeded)}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof Error&&t.name===`OAuthLaunchError`?(console.error(`[oauth-token] Provider ${e}: login could not be shown:`,n),Z6(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),Z6(`oauth-token: login failed: ${n}`))}}async function pue(e,t,n){let r=n?{scopes:n}:void 0,i=!1,a=()=>{i=!0};if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-TDESX_tk.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:Z6(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`),succeeded:!1}}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-TDESX_tk.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:Z6(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function mue(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),Z6(`oauth-token: interactive login was not completed (cancelled, timed out, or no one could approve it)`);let r=t(e);return r?.token&&!r.expired?J6(e,r.maskedValue):r?.token?Z6(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),Z6(`oauth-token: login completed but no token was saved`))}async function hue(e){try{return await e()!==null}catch{return!1}}function Y6(e,t,n,r){let i=e[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function gue(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-Bybk43BU.js`).then(e=>e.r),o=Y6(e,n,i,a);if(!o)return Z6(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return Z6(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return Z6(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return Z6(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return Z6(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function _ue(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-B5g-mrn8.js`).then(e=>e.t),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-Bybk43BU.js`).then(e=>e.r),a=Y6(e,t,r,i);if(!a)return Z6(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return Z6(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return Z6(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${X6(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${X6(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
|
|
3441
3441
|
`)+`
|
|
3442
3442
|
`,stderr:``,exitCode:+!u}}function X6(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function vue(e,t,n){let{parseInterceptOAuthConfig:r}=await import(`./intercepted-oauth-B0tP4D7f.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:i}=await import(`./oauth-service-TDESX_tk.js`),a=await yue(e,t,n);if(!a.ok)return a.result;let o=r(a.value);if(!o.ok)return Z6(`oauth-token: invalid intercept config: ${o.error}`);let s=await i();if(!s)return Z6(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let c=await s(o.config);return c?{stdout:`${c}\n`,stderr:``,exitCode:0}:Z6(`oauth-token: intercept timed out or was cancelled`)}function yue(e,t,n){return e.values.has(`--from-file`)?bue(e.values.get(`--from-file`),n):xue(e,t)}async function bue(e,t){if(!e)return{ok:!1,result:Z6(`oauth-token: --from-file requires a path`)};try{let n=t.fs.resolvePath(t.cwd,e),r=await t.fs.readFile(n),i=typeof r==`string`?r:new TextDecoder().decode(r);return{ok:!0,value:JSON.parse(i)}}catch(t){return{ok:!1,result:Z6(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function xue(e,t){let n=e.values.get(`--authorize-url`),r=e.values.get(`--redirect-pattern`);if(!n)return{ok:!1,result:Z6(`oauth-token: --authorize-url is required`)};if(!r)return{ok:!1,result:Z6(`oauth-token: --redirect-pattern is required`)};let i=Sue(t);return i.ok?{ok:!0,value:{authorizeUrl:n,redirectUriPattern:r,onCapture:e.bools.has(`--leave-tab`)?`leave`:`close`,...i.value.length>0?{rewrite:i.value}:{}}}:i}function Sue(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r===`--`)break;if(r!==`--rewrite`&&!r.startsWith(`--rewrite=`))continue;let i=r===`--rewrite`?e[++n]:r.slice(10);if(!i)return{ok:!1,result:Z6(`oauth-token: --rewrite requires a value`)};let a=i.split(`=`);if(a.length<3)return{ok:!1,result:Z6(`oauth-token: --rewrite "${i}" must be "<match>=<key>=<value>"`)};let[o,s,...c]=a;t.push({match:o,appendParams:{[s]:c.join(`=`)}})}return{ok:!0,value:t}}function Z6(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function Cue(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
3443
3443
|
`,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}t.scopes&&n.push(`scopes: ${t.scopes}`),a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
@@ -3528,7 +3528,7 @@ Examples:
|
|
|
3528
3528
|
plugin list
|
|
3529
3529
|
plugin info my-plugin
|
|
3530
3530
|
plugin remove my-plugin
|
|
3531
|
-
`}function $ue(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return l8(Que());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await tde(i,a,e);case`list`:case`ls`:return await ade(i,e);case`info`:return await ode(i,e);case`validate`:return await sde(i,a,e,aF(n?.env));case`remove`:case`rm`:case`delete`:return await cde(i,e);default:return u8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return u8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function f8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3531
|
+
`}function $ue(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return l8(Que());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await tde(i,a,e);case`list`:case`ls`:return await ade(i,e);case`info`:return await ode(i,e);case`validate`:return await sde(i,a,e,aF(n?.env));case`remove`:case`rm`:case`delete`:return await cde(i,e);default:return u8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return u8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function f8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-BhUjB1cK.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 p8(e,t,n){let r=lde(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-C_CLyb3u.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 ede(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function m8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${c8}/${t.map(ede).join(`--`)}`}async function h8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-CKXdHtbK.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 g8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function tde(e,t,n){if(Zr(e))return l8(`usage: plugin install <path|repo>
|
|
3532
3532
|
|
|
3533
3533
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3534
3534
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3539,19 +3539,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3539
3539
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3540
3540
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3541
3541
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3542
|
-
`);let r=d8(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return u8(`plugin install: expected <path|repo>`);let i=await f8(n),a=await p8(r.positionals[0],t,i);if(a.kind===`error`)return u8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return u8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=m8(a.ref),s=a.ref.display;let e=await h8(a.ref,o,i,n.fetch);if(e)return u8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-B23_5sFw.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await g8(i,o),u8(`plugin install: plugin at ${s??o} was rejected:\n${_8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3542
|
+
`);let r=d8(`install`,e);if(!(`ok`in r))return r;if(r.positionals.length<1)return u8(`plugin install: expected <path|repo>`);let i=await f8(n),a=await p8(r.positionals[0],t,i);if(a.kind===`error`)return u8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return u8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=m8(a.ref),s=a.ref.display;let e=await h8(a.ref,o,i,n.fetch);if(e)return u8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-B23_5sFw.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await g8(i,o),u8(`plugin install: plugin at ${s??o} was rejected:\n${_8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-BwjB3mN4.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await g8(i,o),u8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await ide(u,n),g=await rde(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),l8(nde(u,h,g,s??o,l.diagnostics))}function nde(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:`,_8(i)),c.join(`
|
|
3543
3543
|
`)+`
|
|
3544
|
-
`}async function rde(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-
|
|
3545
|
-
`);let n=d8(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-
|
|
3544
|
+
`}async function rde(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-DgTQh3uY.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 ide(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-DgTQh3uY.js`).then(e=>e.r),{McpClient:a}=await import(`./client-Beg9O208.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 ade(e,t){if(Zr(e))return l8(`usage: plugin list
|
|
3545
|
+
`);let n=d8(`list`,e);if(!(`ok`in n))return n;let{listInstalledPlugins:r}=await import(`./store-BwjB3mN4.js`),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return l8("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 l8(o.map(e=>e.map((e,t)=>e.padEnd(s[t])).join(` `)).join(`
|
|
3546
3546
|
`)+`
|
|
3547
3547
|
`)}async function ode(e,t){if(Zr(e))return l8(`usage: plugin info <name>
|
|
3548
|
-
`);let n=d8(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return u8(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-
|
|
3548
|
+
`);let n=d8(`info`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return u8(`plugin info: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i}=await import(`./store-BwjB3mN4.js`),a=await i(r,t.fs);if(!a)return u8(`plugin info: no installed plugin named "${r}"`);let o=await f8(t),{loadPluginFromDirectory:s}=await import(`./loader-B23_5sFw.js`),c=await s(o,a.root);if(!c.ok)return u8(`plugin info: plugin at ${a.root} no longer loads:\n${_8(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:`,_8(c.diagnostics)),l8(d.join(`
|
|
3549
3549
|
`)+`
|
|
3550
3550
|
`)}async function sde(e,t,n,r){if(Zr(e))return l8(`usage: plugin validate <path|repo>
|
|
3551
3551
|
`);let i=d8(`validate`,e);if(!(`ok`in i))return i;if(i.positionals.length<1)return u8(`plugin validate: expected <path|repo>`);let a=await f8(n),o=await p8(i.positionals[0],t,a);if(o.kind===`error`)return u8(`plugin validate: ${o.message}`);let s,c=null;if(o.kind===`github`){if(!n.fetch)return u8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);c=`${r}/.plugin-validate/${m8(o.ref).split(`/`).pop()}`;let e=await h8(o.ref,c,a,n.fetch);if(e)return u8(`plugin validate: ${e}`);s=c}else s=o.root;let{loadPluginFromDirectory:l}=await import(`./loader-B23_5sFw.js`),u;try{u=await l(a,s)}finally{c&&await g8(a,c)}if(!u.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${_8(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:`,_8(u.diagnostics)),l8(p.join(`
|
|
3552
3552
|
`)+`
|
|
3553
3553
|
`)}async function cde(e,t){if(Zr(e))return l8(`usage: plugin remove <name>
|
|
3554
|
-
`);let n=d8(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return u8(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-
|
|
3554
|
+
`);let n=d8(`remove`,e);if(!(`ok`in n))return n;if(n.positionals.length<1)return u8(`plugin remove: expected <name>`);let r=n.positionals[0],{getInstalledPlugin:i,deleteInstalledPlugin:a}=await import(`./store-BwjB3mN4.js`),o=await i(r,t.fs);if(!o)return u8(`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-DgTQh3uY.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(`${c8}/`);return c&&await g8(await f8(t),o.root),l8([`Removed agent plugin "${r}"`,` registry: removed`,` mcp servers: ${s} removed`,c?` files: removed (${o.root})`:` files: left in place (${o.root})`].join(`
|
|
3555
3555
|
`)+`
|
|
3556
3556
|
`)}function lde(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 _8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3557
3557
|
`)}const v8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],ude=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],dde={running:`R`,pending:`S`,exited:`Z`,killed:`K`},fde=[`-a`,`-A`,`-e`,`--all`,`-T`,`--tree`],y8=[`-o`,`--columns`];function pde(e={}){return H(`ps`,async t=>{if(Zr(t,{valueFlags:y8}))return Tde();let n=e.processManager??mde();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -5151,8 +5151,8 @@ pass --wait to block and print the full result.`,t_e=new Set([`list`,`status`,`s
|
|
|
5151
5151
|
`)}async function bve(e,t){let n=vve(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return m9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:yve(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function xve(e,t){let{scoop_name:n,prompt:r}=e,i=h9(t).find(_9(n));if(i?.jid===t.scoop.jid)return{content:`Cannot feed yourself.`,isError:!0};if(!i)return b9(n,t);try{return await t.onFeedScoop(i.jid,r),m9.info(`Fed scoop`,{target:i.folder,promptLength:r.length}),{content:`Task sent to ${i.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Sve(e){let t=h9(e);return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>gve(t,e.getScoopTabState)).join(`
|
|
5152
5152
|
`)}`}}function Cve({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,allowedCommands:o,thinkingLevel:s,backgroundAfterSeconds:c,parentJid:l,defaultVisibleRoots:u}){return{name:e,folder:t,trigger:`@${t}`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},visiblePaths:i??u,writablePaths:a??[`/scoops/${t}/`,`/shared/`],...o?{allowedCommands:o}:{},...s?{thinkingLevel:s}:{},...c===void 0?{}:{backgroundAfterSeconds:c}},configSchemaVersion:3,parentJid:l}}async function wve(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return m9.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 Tve(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c,background_after:l}=e,u=pve(c);if(!u.ok)return{content:u.content,isError:u.isError};let d=mve(l);if(!d.ok)return{content:d.content,isError:!0};let f=hve(r,t.resolveModelSelection);if(!f.ok)return{content:f.content,isError:f.isError};let p=fve(n),m=g9(t).find(e=>e.name===n||e.folder===p);if(m)return{content:`A scoop named "${m.name}" (${m.folder}) already exists in your scoops. Use feed_scoop to give it another task, or drop_scoop first.`,isError:!0};let h=on(p,t.getScoops().map(e=>e.folder));try{let e=Cve({name:n,folder:h,model:f.modelId,modelProviderId:f.providerId,visiblePaths:a,writablePaths:o,allowedCommands:s,thinkingLevel:u.level,backgroundAfterSeconds:d.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:bn(hn(t.scoop))}),r=await t.onScoopScoop(e);return m9.info(`Scoop created`,{name:n,folder:h}),i&&t.onFeedScoop?wve(r,i,n,h,t.onFeedScoop):{content:`Scoop "${n}" created as "${h}". 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 Eve(e,t){let{scoop_name:n}=e,r=h9(t).find(_9(n));if(r?.jid===t.scoop.jid)return{content:`Cannot drop yourself.`,isError:!0};if(!r)return b9(n,t);try{return await t.onDropScoop(r.jid),m9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function x9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function S9(e,t){let n=g9(t).map(e=>e.folder).join(`, `);return{content:`No matching scoops found in your scoops (${t.scoop.folder}). Unknown: ${e.join(`, `)}. Available: ${n||`(none)`}`,isError:!0}}async function Dve(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return x9();let{resolved:r,unknown:i}=v9(n,t);return r.length===0?S9(i,t):(t.onMuteScoops(r.map(e=>e.jid)),m9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function Ove(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 kve(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return x9();let{resolved:r,unknown:i}=v9(n,t);if(r.length===0)return S9(i,t);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);m9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...Ove(s,o)),{content:c.join(`
|
|
5153
5153
|
`)}}function Ave(e,t){return!Array.isArray(e)||e.length===0?x9():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 jve(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 Mve(e,t){let{scoop_names:n,timeout_ms:r}=e,i=Ave(n,r);if(i)return i;let{resolved:a,unknown:o}=v9(n,t);if(a.length===0)return S9(o,t);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return m9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:jve(u,o,d,r)}}function Nve(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 Pve(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?(m9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:Nve(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 Fve(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?(m9.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 Ive(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(`
|
|
5154
|
-
`)}`}}async function Lve(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),m9.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 Rve(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=>_ve(t,e)}}function zve(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). '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:[...y9],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=>bve(t,e)}}function Bve(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>xve(t,e)}}function Vve(e){return{name:`list_scoops`,description:`List the scoops you own (your own subtree). Names from this list are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait can resolve.`,inputSchema:{type:`object`,properties:{}},execute:()=>Sve(e)}}function Hve(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, 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: YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other. 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 regardless. 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.`},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:[...Vn],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.`}},required:[`name`]},execute:t=>Tve(t,e)}}function Uve(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`}},required:[`scoop_name`]},execute:t=>Eve(t,e)}}function Wve(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>Dve(t,e)}}function Gve(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>kve(t,e)}}function Kve(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops YOU own (e.g., ["writer-scoop", "reviewer-scoop"]). Another cone's scoop is not a valid target.`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>Mve(t,e)}}function qve(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=>Pve(t,e)}}function Jve(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=>Fve(t,e)}}function Yve(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:()=>Ive(e)}}function Xve(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=>Lve(t,e)}}function Zve(e){let t=[],n=dn(e.scoop);return cn(e.scoop)||(t.push(Rve(e)),e.onSudoRequest&&t.push(zve(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(Bve(e)),t.push(Vve(e)),e.onScoopScoop&&t.push(Hve(e)),e.onDropScoop&&t.push(Uve(e)),e.onMuteScoops&&t.push(Wve(e)),e.onUnmuteScoops&&t.push(Gve(e)),e.onScheduleScoopWait&&t.push(Kve(e)),e.onSudoResolve&&(t.push(qve(e)),t.push(Jve(e))),e.onListSudoRequests&&t.push(Yve(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Xve(e))),t}const Qve=r(`scoop-context`);function $ve(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-MzqLI9n7.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function eye(e){let{scoop:t,unit:n,callbacks:r}=e,i=Zve({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:w,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=[...cve(e.gatedFs),tve(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:ft(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){Qve.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);a.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let o={scrubToolResult:ft()},s=$ve(e);return e.processManager?Bt(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):Bt(a,void 0,o,s)}const C9=r(`scoop-context`);async function tye(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();C9.info(`Filesystem ready`,{folder:t.folder}),await GS(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await B_e({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let l=await eye({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(!DS(t))return C9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=kS(t,n),p=MS(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await qS(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>DS(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:e=>i.onCompactionStateChange?.(e)});if(e.isDisposed())return{kind:`abandoned`};let v=un(t);return{kind:`ready`,agent:US({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:PS(FS()??v.level,f),getApiKey:()=>DS(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 w9=r(`scoop-context`);var nye=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=kt(e.messages);return this.createdAt=e.createdAt,w9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){w9.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 w9.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=di(t);if(n.length===0)return null;let r=kt(n);return t&&(this.createdAt=t.createdAt),w9.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=>{w9.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=>{w9.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){w9.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 rye(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 iye(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function T9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const E9=r(`scoop-context`);var aye=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;E9.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)&&(E9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:fS(r)}),!!(t<3&&(await pS(D9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return dS(e)?(E9.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 Jo(e)?(E9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Xo(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(!fS(e)||t>=3)return!1;let r=D9(t);return E9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await pS(r,n)&&!this.deps.isDisposed()}fail(e,t){gi(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function D9(e){return 1e3*2**(e-1)}function oye(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){E9.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 O9=r(`scoop-context`);var sye=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;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;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){this.scoop=e,this.unit=On(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.sessions=new nye({store:r??null,canonical:c?{store:c,identity:{key:ui(e),workUnitId:e.jid,workspaceId:li(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:gn(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 HS({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new bS({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new SS({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new VS({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 aye({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 L_e(this.unit,this.scoop,ln(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Tn(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 tye({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,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)});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`),O9.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);O9.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(jS(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),iye(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(oye(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=rye(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(){T9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(){this.clearMessages(),await this.sessions.clear()}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return AS(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=LS(this.agent,this.scoop))}async reloadSkills(){this.agent&&await zS(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?FS()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,RS(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.runBounds.disarm(),T9(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||gS(e,this.eventSink,t)}setStatus(e){this.disposed||(this.status=e,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||mS(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 k9=r(`scoop-lifecycle-manager`);var cye=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 lS(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))??ln(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return sn(t.values(),e)??ln(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){k9.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof Vr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)k9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{k9.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=On(t).policy.filesystem,o=a.kind===`full-workspace`?r:new Vr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new sye(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore());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=>{k9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),k9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),k9.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 k9.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(k9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){k9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){k9.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`)),k9.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(fn(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=on(e.folder,n);r!==e.folder&&(k9.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),k9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&hi(`spawn`,e.folder)}catch(n){k9.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){k9.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=>{k9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(yn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Cn(t):void 0)??zx();n&&Pn(e,n)}async unregister(e){let t=this.deps.getScoops(),n=t.get(e);if(n&&n.parentJid===null&&ln(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=>{k9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(ui(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{k9.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&&k9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),k9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){k9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;Pn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Pn(n,r),this.getContext(e)?.updateModel(),k9.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();k9.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=>{k9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),k9.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;mn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){k9.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}=On(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}),hi(`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=>{n.onCompactionStateChange?.(e,t)},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 await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:hn(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(k9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),hi(`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`),On(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){k9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{k9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const A9=r(`scoop-message-router`);var lye=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(A9.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){A9.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}`);hi(`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),A9.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);A9.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){A9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){A9.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(A9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){A9.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{A9.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`;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);A9.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);A9.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,A9.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){A9.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){A9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){A9.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(A9.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){A9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){A9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=or(yr(ur(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){A9.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}: ${bg(e.content,e.attachments)}`).join(`
|
|
5155
|
-
`),l=s.flatMap(e=>xg(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=or(yr(ur(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);A9.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){this.cancelDebounce(e),t&&await t.clearSession().catch(t=>{A9.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=>{A9.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),A9.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=>{A9.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=>{A9.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(),A9.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 j9=r(`orchestrator`),uye={decision:`deny`};var dye=class{scoops=new Map;workUnits=new n_(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Mx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new oS({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 iS({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Qx({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 Wx({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>mr(e),saveMessage:e=>sr(e)});lickRegistry=new Fx({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 lye({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=>sr(e),deleteMessage:e=>lr(e),clearMessagesForScoop:e=>_r(e),clearAllMessages:()=>hr(),getMessagesSince:(e,t,n)=>pr(e,t,n),setState:(e,t)=>ar(e,t)},isExternalLickChannel:jg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new cye({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>ir(e),deleteScoop:e=>gr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Lr(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return Bx(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new Lv({fs:e,watcher:t,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new Y_(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Rx(e,t),await this.modelPolicyFile.init(),n(),br()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Sr(),this.sharedFs=await Bx(e=>Br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new wg,this.conversationStore=new Jb,this.fsWatcher=new zr,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=>En(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),fn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await fr(`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 Hx({onTaskRun:async(e,t)=>{j9.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(),j9.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);j9.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}`)}Ur(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=zv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Dg;try{await Hb({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){j9.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=En(e)?null:t??null;try{await ir(e)}catch(t){j9.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=>!yn(e));if(e.length===0)return;let t=zx(),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?Cn(n):void 0)??t;if(r){Pn(e,r);try{await ir(e)}catch(t){j9.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=`${kn.root}/`,r=bn(pn(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-DeUsUYBD.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:hn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(j9.warn(`Guest approval before SudoManager init — failing closed`),uye)}})}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)}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 ln(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()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return sn(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 Dx(this.sharedFs).catch(e=>{j9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new Lv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Y_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Rx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),j9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}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 mr(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-CLzdz05B.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(qr)]}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&&j9.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,j9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Dg,t=this.sharedFs;return new cb({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:Db(),snapshotStore:{read:e=>yb(t,e),write:(e,n)=>vb(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.110.12`})}};const M9=r(`workflow-run-manager`),N9=`/shared/workflow-runs`,P9=1e3;function fye(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function pye(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){M9.warn(`observeRun handler threw`,e)}},i=(e,n)=>vye(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=fye(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),gye(t,n);let f=i(a.ctx,c),p=_ye(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=>M9.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=`${N9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(N9,{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);M9.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`?hye(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){M9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function mye(e){let t=pye(e);return globalThis[F7]=t,M9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function hye(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function gye(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 _ye(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 vye(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?yye(n,t,a?.args??[],r):e===`agent`?bye(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function yye(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>P9&&i.logs.splice(0,i.logs.length-P9),r()}return{stdout:``,stderr:``,exitCode:0}}async function bye(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 xye=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function Sye(e,t,n){let r=Cye(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=wye(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Cye(e){let t=new Map;return F9(t,e.discoveryOrigin),F9(t,e.discoveryUrl),[...t.values()]}function F9(e,t){if(t){I9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);I9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!xye.has(e)))I9(e,t,1,`substring`)}catch{}}}function I9(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 wye(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Eye(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)Tye(a,e)&&(r+=e.weight*o)}return r}function Tye(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 Eye(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Dye=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=z9(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:R9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===R9)throw new Hn(`ENOTDIR`,`not a directory`,e);let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);return L9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new Hn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=z9(e);if(t.length===1&&t[0]===R9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new Hn(`EISDIR`,`is a directory`,e);let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!L9.includes(r))throw new Hn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new Hn(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=z9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===R9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!L9.includes(r))throw new Hn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new Hn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new Hn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new Hn(`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 Hn(`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:V9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:H9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5154
|
+
`)}`}}async function Lve(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),m9.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 Rve(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=>_ve(t,e)}}function zve(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). '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:[...y9],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=>bve(t,e)}}function Bve(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>xve(t,e)}}function Vve(e){return{name:`list_scoops`,description:`List the scoops you own (your own subtree). Names from this list are the only ones feed_scoop / drop_scoop / scoop_mute / scoop_unmute / scoop_wait can resolve.`,inputSchema:{type:`object`,properties:{}},execute:()=>Sve(e)}}function Hve(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, 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: YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other. 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 regardless. 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.`},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:[...Vn],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.`}},required:[`name`]},execute:t=>Tve(t,e)}}function Uve(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Must be a scoop you own — use list_scoops to see them.`}},required:[`scoop_name`]},execute:t=>Eve(t,e)}}function Wve(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>Dve(t,e)}}function Gve(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>kve(t,e)}}function Kve(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops YOU own (e.g., ["writer-scoop", "reviewer-scoop"]). Another cone's scoop is not a valid target.`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>Mve(t,e)}}function qve(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=>Pve(t,e)}}function Jve(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=>Fve(t,e)}}function Yve(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:()=>Ive(e)}}function Xve(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=>Lve(t,e)}}function Zve(e){let t=[],n=dn(e.scoop);return cn(e.scoop)||(t.push(Rve(e)),e.onSudoRequest&&t.push(zve(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(Bve(e)),t.push(Vve(e)),e.onScoopScoop&&t.push(Hve(e)),e.onDropScoop&&t.push(Uve(e)),e.onMuteScoops&&t.push(Wve(e)),e.onUnmuteScoops&&t.push(Gve(e)),e.onScheduleScoopWait&&t.push(Kve(e)),e.onSudoResolve&&(t.push(qve(e)),t.push(Jve(e))),e.onListSudoRequests&&t.push(Yve(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Xve(e))),t}const Qve=r(`scoop-context`);function $ve(e){return{currentGate(){let t=e.getTurnGuestGates();if(t.length!==0)return{async approve(n,r){let{approveToolCallForGuests:i}=await import(`./guest-tool-gate-DTA3P3jk.js`);return i(t,n,r,e.callbacks.approveGuestToolCall)}}}}}async function eye(e){let{scoop:t,unit:n,callbacks:r}=e,i=Zve({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:w,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=[...cve(e.gatedFs),tve(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:ft(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){Qve.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);a.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let o={scrubToolResult:ft()},s=$ve(e);return e.processManager?Bt(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o,s):Bt(a,void 0,o,s)}const C9=r(`scoop-context`);async function tye(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e,a=e.getTmpDir();C9.info(`Filesystem ready`,{folder:t.folder}),await GS(r,t,n,a);let{shell:o,gatedFs:s,skills:c}=await B_e({scoop:t,unit:n,fs:r,tmpDir:a,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(o);let l=await eye({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(!DS(t))return C9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let f=kS(t,n),p=MS(t,n,d,u,c),m=await e.sessions.restore(),{streamWithSessionId:h,compactFn:g,getCompactionApiKey:_}=await qS(f,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>DS(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:e=>i.onCompactionStateChange?.(e)});if(e.isDisposed())return{kind:`abandoned`};let v=un(t);return{kind:`ready`,agent:US({model:f,tools:l,systemPrompt:p,messages:m,thinkingLevel:PS(FS()??v.level,f),getApiKey:()=>DS(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 w9=r(`scoop-context`);var nye=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=kt(e.messages);return this.createdAt=e.createdAt,w9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){w9.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 w9.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=di(t);if(n.length===0)return null;let r=kt(n);return t&&(this.createdAt=t.createdAt),w9.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=>{w9.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=>{w9.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){w9.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 rye(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 iye(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function T9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const E9=r(`scoop-context`);var aye=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;E9.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)&&(E9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:fS(r)}),!!(t<3&&(await pS(D9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return dS(e)?(E9.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 Jo(e)?(E9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),Xo(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(!fS(e)||t>=3)return!1;let r=D9(t);return E9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await pS(r,n)&&!this.deps.isDisposed()}fail(e,t){gi(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function D9(e){return 1e3*2**(e-1)}function oye(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){E9.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 O9=r(`scoop-context`);var sye=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;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;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){this.scoop=e,this.unit=On(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.sessions=new nye({store:r??null,canonical:c?{store:c,identity:{key:ui(e),workUnitId:e.jid,workspaceId:li(e),folder:e.folder,legacyKeys:{agentSessionId:e.jid,chatSessionId:gn(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 HS({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new bS({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new SS({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new VS({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 aye({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 L_e(this.unit,this.scoop,ln(this.callbacks.getScoops())[0]?.jid)}ownTmpDir(){return Tn(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 tye({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,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)});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`),O9.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);O9.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(jS(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),iye(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(oye(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=rye(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(){T9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}async clearSession(){this.clearMessages(),await this.sessions.clear()}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return AS(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=LS(this.agent,this.scoop))}async reloadSkills(){this.agent&&await zS(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?FS()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,RS(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.runBounds.disarm(),T9(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||gS(e,this.eventSink,t)}setStatus(e){this.disposed||(this.status=e,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||mS(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 k9=r(`scoop-lifecycle-manager`);var cye=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 lS(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))??ln(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return sn(t.values(),e)??ln(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager();if(t)try{await t.initScoopPolicy(e.folder,e.config)}catch(t){k9.warn(`Failed to initialize per-scoop sudo policy; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof Vr))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context){if(n.tab?.status===`error`)k9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{k9.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=On(t).policy.filesystem,o=a.kind===`full-workspace`?r:new Vr(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new sye(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager(),this.deps.getConversationStore());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=>{k9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),k9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),k9.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 k9.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(k9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){k9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){k9.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`)),k9.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(fn(e),this.inheritModel(e),e.parentJid!==null){let n=[];for(let r of t.values())r.jid!==e.jid&&n.push(r.folder);let r=on(e.folder,n);r!==e.folder&&(k9.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),k9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&hi(`spawn`,e.folder)}catch(n){k9.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){k9.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=>{k9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(yn(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?Cn(t):void 0)??zx();n&&Pn(e,n)}async unregister(e){let t=this.deps.getScoops(),n=t.get(e);if(n&&n.parentJid===null&&ln(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=>{k9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),n&&this.deps.getConversationStore()?.delete(ui(n)),this.deps.getSessionStore()?.delete(e).catch(t=>{k9.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&&k9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),n&&this.deps.getSudoManager()?.forgetScoopPolicies(n.folder),k9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){k9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;Pn(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return Pn(n,r),this.getContext(e)?.updateModel(),k9.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();k9.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=>{k9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),k9.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;mn(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){k9.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}=On(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}),hi(`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=>{n.onCompactionStateChange?.(e,t)},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 await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:hn(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(k9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),hi(`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`),On(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){k9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{k9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const A9=r(`scoop-message-router`);var lye=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(A9.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){A9.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}`);hi(`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),A9.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);A9.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){A9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){A9.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(A9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){A9.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{A9.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`;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);A9.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);A9.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,A9.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){A9.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){A9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){A9.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(A9.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){A9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){A9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=or(yr(ur(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){A9.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}: ${bg(e.content,e.attachments)}`).join(`
|
|
5155
|
+
`),l=s.flatMap(e=>xg(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=or(yr(ur(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);A9.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){this.cancelDebounce(e),t&&await t.clearSession().catch(t=>{A9.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=>{A9.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),A9.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=>{A9.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=>{A9.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(),A9.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 j9=r(`orchestrator`),uye={decision:`deny`};var dye=class{scoops=new Map;workUnits=new n_(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Mx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;conversationStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new oS({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 iS({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Qx({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 Wx({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>mr(e),saveMessage:e=>sr(e)});lickRegistry=new Fx({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 lye({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=>sr(e),deleteMessage:e=>lr(e),clearMessagesForScoop:e=>_r(e),clearAllMessages:()=>hr(),getMessagesSince:(e,t,n)=>pr(e,t,n),setState:(e,t)=>ar(e,t)},isExternalLickChannel:jg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new cye({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getConversationStore:()=>this.conversationStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>ir(e),deleteScoop:e=>gr(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>Lr(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t,n)=>this.resolveActionableLick(e,t,n),approveDirectedOrUser:e=>this.approveDirectedOrUser(e),listPendingSudoRequests:e=>this.listPendingSudoRequests(e)},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async initPolicyLayerAndLoadRecords(e,t,n){return Bx(async n=>(await this.ensureRootStructure(),n(),this.sudoManager=new Lv({fs:e,watcher:t,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),n(),this.llmsTxtIgnorePolicy=new Y_(e,t),await this.llmsTxtIgnorePolicy.init(),n(),this.modelPolicyFile=new Rx(e,t),await this.modelPolicyFile.init(),n(),br()),n,{stagePrefix:`orchestrator-init`})}async init(e){await Sr(),this.sharedFs=await Bx(e=>Br.create({dbName:`slicc-fs`,onRepairProgress:e}),e),this.sessionStore=new wg,this.conversationStore=new Jb,this.fsWatcher=new zr,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=>En(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),fn(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await fr(`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 Hx({onTaskRun:async(e,t)=>{j9.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(),j9.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);j9.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}`)}Ur(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=zv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async migrateConversations(e){let t=this.conversationStore;if(!t)return;let n=new Dg;try{await Hb({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){j9.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=En(e)?null:t??null;try{await ir(e)}catch(t){j9.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=>!yn(e));if(e.length===0)return;let t=zx(),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?Cn(n):void 0)??t;if(r){Pn(e,r);try{await ir(e)}catch(t){j9.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=`${kn.root}/`,r=bn(pn(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getConversationStore(){return this.conversationStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setUnitRosterProvider?.(()=>this.getScoops().map(e=>({name:e.name,folder:e.folder}))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){return this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}async approveDirectedOrUser(e){let{runDirectedApproval:t}=await import(`./directed-approval-CRALKPfL.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:hn,approveAsUser:async e=>{let t=this.sudoManager;return t?t.approve(e):(j9.warn(`Guest approval before SudoManager init — failing closed`),uye)}})}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)}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 ln(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()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return sn(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 Dx(this.sharedFs).catch(e=>{j9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new Lv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>{this.lifecycle.syncReadGrants(e),this.approvalRouter.settleGrantedRequests(e)}}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Y_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Rx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),j9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}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 mr(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-CLzdz05B.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(qr)]}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&&j9.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,j9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new Dg,t=this.sharedFs;return new cb({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:Db(),snapshotStore:{read:e=>yb(t,e),write:(e,n)=>vb(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.110.13`})}};const M9=r(`workflow-run-manager`),N9=`/shared/workflow-runs`,P9=1e3;function fye(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function pye(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){M9.warn(`observeRun handler threw`,e)}},i=(e,n)=>vye(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=fye(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),gye(t,n);let f=i(a.ctx,c),p=_ye(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=>M9.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=`${N9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(N9,{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);M9.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`?hye(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){M9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function mye(e){let t=pye(e);return globalThis[F7]=t,M9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function hye(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function gye(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 _ye(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 vye(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?yye(n,t,a?.args??[],r):e===`agent`?bye(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function yye(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>P9&&i.logs.splice(0,i.logs.length-P9),r()}return{stdout:``,stderr:``,exitCode:0}}async function bye(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 xye=new Set([`catalog`,`com`,`html`,`http`,`https`,`json`,`known`,`llms`,`net`,`org`,`txt`,`well`,`www`]);function Sye(e,t,n){let r=Cye(e);if(r.length===0)return;let i,a=0,o=!1;for(let e of t){let t=wye(n(e),r);t>a?(i=e,a=t,o=!1):t>0&&t===a&&(o=!0)}return o?void 0:i}function Cye(e){let t=new Map;return F9(t,e.discoveryOrigin),F9(t,e.discoveryUrl),[...t.values()]}function F9(e,t){if(t){I9(e,t.toLowerCase().replace(/\/$/,``),12,`substring`);try{let n=new URL(t),r=n.hostname.toLowerCase().replace(/^www\./,``);I9(e,r,8,`hostname`);for(let t of`${r}${n.pathname}${n.search}`.split(/[^a-z0-9]+/).filter(e=>e.length>=4&&!xye.has(e)))I9(e,t,1,`substring`)}catch{}}}function I9(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 wye(e,t){let n=e.slice(-8),r=0;for(let[e,i]of n.entries()){let a=Eye(i);if(a.length===0)continue;let o=8-(n.length-1-e);for(let e of t)Tye(a,e)&&(r+=e.weight*o)}return r}function Tye(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 Eye(e){try{return JSON.stringify(e)?.toLowerCase()??``}catch{return``}}var Dye=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=z9(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:R9,kind:`file`,size:this.renderTable().length,lastModified:Date.now()}),t}if(t.length===1){if(t[0]===R9)throw new Hn(`ENOTDIR`,`not a directory`,e);let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);return L9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new Hn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=z9(e);if(t.length===1&&t[0]===R9)return new TextEncoder().encode(this.renderTable());if(t.length!==2)throw new Hn(`EISDIR`,`is a directory`,e);let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!L9.includes(r))throw new Hn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new Hn(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=z9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){if(t[0]===R9)return{kind:`file`,size:this.renderTable().length,mtime:Date.now()};let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=B9(t[0]);if(n===null||!this.pidExists(n))throw new Hn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!L9.includes(r))throw new Hn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new Hn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new Hn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new Hn(`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 Hn(`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:V9(e.status),status:e.status,argv:e.argv.join(` `),cwd:e.cwd,owner:H9(e),startedAt:e.startedAt,finishedAt:e.finishedAt,exitCode:e.exitCode}))};return JSON.stringify(e)+`
|
|
5156
5156
|
`}renderProcFile(e,t){if(e===1)return Mye(t);let n=this.pm.get(e);switch(t){case`status`:return Oye(n);case`cmdline`:return kye(n);case`cwd`:return Aye(n);case`stat`:return jye(n)}}};const L9=[`status`,`cmdline`,`cwd`,`stat`],R9=`table`;function z9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function B9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Oye(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${V9(e.status)} (${e.status})`,`Owner:\t${H9(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(`
|
|
5157
5157
|
`)+`
|
|
5158
5158
|
`}function kye(e){return e.argv.join(`\0`)+`\0`}function Aye(e){return e.cwd+`
|
|
@@ -5162,4 +5162,4 @@ pass --wait to block and print the full result.`,t_e=new Set([`list`,`status`,`s
|
|
|
5162
5162
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5163
5163
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5164
5164
|
`}}function Nye(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(KB(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(!VB(n.token))return;let a=i.get(n.id);if(a){r({type:qB,id:n.id}),a.result&&r({type:JB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:qB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:JB,id:n.id,...e})};(QB(n)?tV(n):GB(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 U9(){return globalThis}function Pye(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 Fye(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 Iye(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Lye(e,t)}function Lye(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=ln(r),a=e.type===`discovery`&&!e.targetScoop?Sye(e,i.filter(K_),e=>t.getScoopContext?.(e.jid)?.getAgentMessages()??[]):void 0,o=e.targetScoop?Qo(r,e.targetScoop):a??i[0];if(!o){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!K_(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=Gg(e);if(s===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let c=Pye(e),l=Fye(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 Rye(e,t,n,r,i){let a=new Qi,o=new dye(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),U9().__slicc_pm=a,pG(hG()),U9().__slicc_browser=t,await n.bind(o,t);let s=tr(()=>n.emitTrayRuntimeStatus()),c=f_(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function zye(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-DNKXuXCE.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-y-5bIVRR.js`).then(e=>e.n),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??Iye,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function Bye(e){let t=e.getScoops();ln(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 Vye(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;mye({sharedFs:i,getStartingRoot:e=>{let n=ln(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)=>_G(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>I7().slice(10,22),splitResult:(e,t)=>L7(e,t)})}async function Hye(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-CtHmog_w.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))+`
|
|
5165
|
-
`,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 Uye(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-BD2lQGbd.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).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 Wye(e,t,n){let r=e.getTransport();if(r.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 L_(r,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})},Gye(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Gye(e){let t=y();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:()=>R_()}}function Kye(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-C-JrPN0s.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-B5XJxoBU.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 qye(){Or(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-d83JrIre.js`);return e()})}function Jye(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-d83JrIre.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 Yye(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-COvv_9Ni.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 Xye(){return Ht()}async function Zye(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);qye();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Rye(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?xe(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Dye(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await zye(l,e,o);s(`lick-manager-ready`),f&&Vye({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),U9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Hye({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});U9().__slicc_wsSubscribers=h;let g=null;Xye()&&(g=await Uye(p,o,e.localLickWsUrl??null));let _=Wye(n,p,o);f&&Kye(f,p,o),a||await Bye(l),s(`cone-bootstrapped`),f&&Jye(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Yye(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Nye({nonce:e.syncFsChannelNonce}).dispose);let x=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){x||(x=!0,await Qye({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,syncFsResponderDispose:b,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:o}))}}}async function Qye(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}W9({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function W9(e){let t=U9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,pG(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 G9=`x-bypass-llm-proxy`;function $ye(e,t,n){return t?(r,i)=>{if(!ebe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function ebe(e,t,n){if(nbe(e,t))return!0;let r=n?.()??null;return r?tbe(e,r,t):!1}function tbe(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function nbe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function rbe(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 ibe=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(!abe(e)||e.source!==`panel`)return;let t=e.payload;obe(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=Na(u(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?q9(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,q9(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 abe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function obe(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 sbe=class extends Q7{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 cbe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new ibe({transport:t,processManager:i,createShell:(a,o)=>new sbe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??Ht,getLeaderStatus:e.webhook?.getLeaderStatus??$n},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function lbe(e){let t=new ube(e);return t.start(),{stop:()=>t.dispose()}}var ube=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(!dbe(e)||e.source!==`panel`)return;let t=e.payload;if(fbe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(pbe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(mbe(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=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new Hn(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new Hn(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(hbe(e.type),e.requestId,new Hn(`EACCES`,`vfs-rpc-host has no writable backend wired`),gbe(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 Hn(`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 Hn(`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 Hn(`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 dbe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function fbe(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 pbe(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 mbe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function hbe(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 gbe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof Hn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function _be(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=$ye(e.bind(globalThis),t,vbe)}function vbe(){let e=pe();if(!e)return null;try{return new URL(e).origin}catch{return null}}function ybe(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 bbe=rbe(e=>Cbe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&bbe.handle(e.data)});function xbe(e){let t=Xee(e.pageBuildId,`6.110.12-mth4oet3`);return()=>{t&&_i(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.110.12-mth4oet3`)}}function Sbe(e){_be(),k(e.localApiBaseUrl??null),le(e.bridgeToken??null),sG(e.syncFsBridgeEnabled??!1),fe(e.extensionDelegateId??null),ybe(e.localStorageSeed??{}),e.flagFloat&&Vee(e.flagFloat)}async function Cbe(e){Jee(e.instanceId);let t=xbe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Sbe(e),yi().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Qee(e.kernelPort),a=new D_(r),o=D_.createCallbacks(a),c=new $ee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Dee(c);Y9=await Zye({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(Aee(i));let m=await Tbe({host:Y9,transport:r,browser:l,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){wbe(e.kernelPort,t)}}function wbe(e,t){Yee(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 Tbe(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=cbe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=lbe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),i=await Ebe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Ebe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CmarhXRU.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-BduXImRw.js`).then(e=>e.n),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())});
|
|
5165
|
+
`,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 Uye(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-BD2lQGbd.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).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 Wye(e,t,n){let r=e.getTransport();if(r.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 L_(r,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})},Gye(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Gye(e){let t=y();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:()=>R_()}}function Kye(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-DBMLMXSG.js`).then(e=>e.n),{hostShadowedEntries:o,mountConfiguredHostMounts:s,withoutHostMountedTargets:c}=await import(`./auto-mount-table-B5XJxoBU.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 qye(){Or(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-Dm6JI5c7.js`);return e()})}function Jye(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Dm6JI5c7.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 Yye(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-COvv_9Ni.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 Xye(){return Ht()}async function Zye(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);qye();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Rye(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?xe(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Dye(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await zye(l,e,o);s(`lick-manager-ready`),f&&Vye({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),U9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Hye({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});U9().__slicc_wsSubscribers=h;let g=null;Xye()&&(g=await Uye(p,o,e.localLickWsUrl??null));let _=Wye(n,p,o);f&&Kye(f,p,o),a||await Bye(l),s(`cone-bootstrapped`),f&&Jye(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Yye(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Nye({nonce:e.syncFsChannelNonce}).dispose);let x=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){x||(x=!0,await Qye({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,syncFsResponderDispose:b,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:o}))}}}async function Qye(e){let{sharedFs:t,wsRegistry:n,wsBridge:r,processManager:i,lickManager:a,browser:o,log:s}=e;if(e.unsubLeader?.(),e.unsubFollower?.(),e.bshWatchdogStop?.(),e.scriptCatalogDispose?.(),e.lickWsBridgeStop?.(),e.syncFsResponderDispose?.(),e.navigationWatcherStop)try{await e.navigationWatcherStop()}catch(e){s.warn(`NavigationWatcher.stop() failed`,e)}if(t)try{await t.unmountInternal(`/proc`)}catch{}try{n.dispose()}catch(e){s.warn(`WsSubscriberRegistry.dispose() failed`,e)}try{r.dispose()}catch(e){s.warn(`CdpWsPageBridge.dispose() failed`,e)}W9({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function W9(e){let t=U9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,pG(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 G9=`x-bypass-llm-proxy`;function $ye(e,t,n){return t?(r,i)=>{if(!ebe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function ebe(e,t,n){if(nbe(e,t))return!0;let r=n?.()??null;return r?tbe(e,r,t):!1}function tbe(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function nbe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function rbe(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 ibe=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(!abe(e)||e.source!==`panel`)return;let t=e.payload;obe(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=Na(u(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?q9(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,q9(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 abe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function obe(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 sbe=class extends Q7{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 cbe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new ibe({transport:t,processManager:i,createShell:(a,o)=>new sbe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??Ht,getLeaderStatus:e.webhook?.getLeaderStatus??$n},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function lbe(e){let t=new ube(e);return t.start(),{stop:()=>t.dispose()}}var ube=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(!dbe(e)||e.source!==`panel`)return;let t=e.payload;if(fbe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(pbe(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}if(mbe(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=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new Hn(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new Hn(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(hbe(e.type),e.requestId,new Hn(`EACCES`,`vfs-rpc-host has no writable backend wired`),gbe(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 Hn(`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 Hn(`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 Hn(`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 dbe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function fbe(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 pbe(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 mbe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-watch`||t===`vfs-unwatch`}function hbe(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 gbe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof Hn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function _be(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=$ye(e.bind(globalThis),t,vbe)}function vbe(){let e=pe();if(!e)return null;try{return new URL(e).origin}catch{return null}}function ybe(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 bbe=rbe(e=>Cbe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&bbe.handle(e.data)});function xbe(e){let t=Xee(e.pageBuildId,`6.110.13-mthj1lxx`);return()=>{t&&_i(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.110.13-mthj1lxx`)}}function Sbe(e){_be(),k(e.localApiBaseUrl??null),le(e.bridgeToken??null),sG(e.syncFsBridgeEnabled??!1),fe(e.extensionDelegateId??null),ybe(e.localStorageSeed??{}),e.flagFloat&&Vee(e.flagFloat)}async function Cbe(e){Jee(e.instanceId);let t=xbe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Sbe(e),yi().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Qee(e.kernelPort),a=new D_(r),o=D_.createCallbacks(a),c=new $ee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Dee(c);Y9=await Zye({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(Aee(i));let m=await Tbe({host:Y9,transport:r,browser:l,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){wbe(e.kernelPort,t)}}function wbe(e,t){Yee(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 Tbe(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=cbe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=lbe({transport:e.transport,client:t,writableClient:t,getWatcher:()=>t.getWatcher(),logger:console}),i=await Ebe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Ebe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CmarhXRU.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-BduXImRw.js`).then(e=>e.n),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())});
|