sliccy 6.71.0 → 6.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/ui/assets/{account-store-DFQ8Dgj9.js → account-store-BGgapOqM.js} +1 -1
- package/dist/ui/assets/{account-store-yQMPeovo.js → account-store-iHtMDYZF.js} +1 -1
- package/dist/ui/assets/{adobe-t02nptZw.js → adobe-Zc7Eyed7.js} +1 -1
- package/dist/ui/assets/{adobe-C0N_GiSE.js → adobe-oizTYfDl.js} +1 -1
- package/dist/ui/assets/{apply-layout-BIMv75Rh.js → apply-layout-12q9RrRr.js} +1 -1
- package/dist/ui/assets/{apps-N_cHAFMa.js → apps--wWNQP2K.js} +1 -1
- package/dist/ui/assets/{azure-openai-DCgUdhkV.js → azure-openai-Bx2BnyQH.js} +1 -1
- package/dist/ui/assets/{azure-openai-DITUdhKw.js → azure-openai-D4kxJ3gG.js} +1 -1
- package/dist/ui/assets/{cerebras-DXvruR-f.js → cerebras-BlMl7nlT.js} +1 -1
- package/dist/ui/assets/{cerebras-BKsOcNmK.js → cerebras-D1WDsYbu.js} +1 -1
- package/dist/ui/assets/{connect-surface-BxkxiSNH.js → connect-surface-OIMianve.js} +1 -1
- package/dist/ui/assets/{fs-DDemTXw8.js → fs-C0cX_P2D.js} +2 -2
- package/dist/ui/assets/{fs-mfTn4f6R.js → fs-DtHl1BTl.js} +1 -1
- package/dist/ui/assets/{github-D3_RDWlR.js → github-DcSH2_9B.js} +1 -1
- package/dist/ui/assets/{github-Cj9EgGkZ.js → github-DeOAHe_r.js} +2 -2
- package/dist/ui/assets/{github-copilot-Dblzr8C1.js → github-copilot-BSBEHX76.js} +1 -1
- package/dist/ui/assets/{github-copilot-DBMMN7nj.js → github-copilot-D6cnQZx4.js} +1 -1
- package/dist/ui/assets/{github-install-S3gH1LN1.js → github-install-D-qYA6oL.js} +1 -1
- package/dist/ui/assets/{github-zip-w452Q-_E.js → github-zip-CmFOTm1q.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-kzfHhxZE.js → js-realm-worker-BCmp7aOj.js} +1 -1
- package/dist/ui/assets/{kernel-worker-CKJO9mkv.js → kernel-worker-0Totg3A4.js} +25 -25
- package/dist/ui/assets/{local-llm-CKMcrybN.js → local-llm-BZBzyZhe.js} +1 -1
- package/dist/ui/assets/{local-llm-bBO3kMGG.js → local-llm-DtjD8w3y.js} +1 -1
- package/dist/ui/assets/{main-NDI7TUj5.js → main-DT2PwvUH.js} +3 -3
- package/dist/ui/assets/{mount-DT8z_PVy.js → mount-DSS18gbH.js} +2 -2
- package/dist/ui/assets/{mount-C9lbsxh0.js → mount-DUfqMR7N.js} +1 -1
- package/dist/ui/assets/{mount-recovery-mi1lXBvI.js → mount-recovery-BhGJRk0L.js} +1 -1
- package/dist/ui/assets/{new-session-B4NDvbFN.js → new-session-D8YNK42w.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-BTERUpnb.js → oauth-bootstrap-BSzXSCUJ.js} +2 -2
- package/dist/ui/assets/{openai-codex-Tm1Y39dv.js → openai-codex-CVZBg9cm.js} +1 -1
- package/dist/ui/assets/{openai-codex-YzN0-rk7.js → openai-codex-Z1lL6fT7.js} +1 -1
- package/dist/ui/assets/{openrouter-DT4yW9JI.js → openrouter-BJs8BjRN.js} +1 -1
- package/dist/ui/assets/{openrouter-L1Z1bzso.js → openrouter-DOH_9gEl.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BbRCDNH_.js → openrouter-oauth-CeLh7v23.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BNIfHZiC.js → openrouter-oauth-DNFXraId.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-DvZFQHmG.js → panel-rpc-handlers-D-I95j4E.js} +2 -2
- package/dist/ui/assets/{panelize-shell-BusmMR6B.js → panelize-shell-BuwzGhwR.js} +1 -1
- package/dist/ui/assets/{provider-CR0TbkfA.js → provider-BX_XNpoZ.js} +2 -2
- package/dist/ui/assets/{provider-DcNunfGw.js → provider-Bo6uW5vD.js} +1 -1
- package/dist/ui/assets/{provider-settings-uQZPJpQ-.js → provider-settings-DCjokX3w.js} +1 -1
- package/dist/ui/assets/{provider-settings-CmFmQOKw.js → provider-settings-DuMJVSU3.js} +1 -1
- package/dist/ui/assets/provider-store-access-C1ZWRiw6.js +1 -0
- package/dist/ui/assets/{provider-store-access-D39HNRa8.js → provider-store-access-Cs1o2DPs.js} +2 -2
- package/dist/ui/assets/{providers-CpDGMO7m.js → providers-DdpSaPOK.js} +1 -1
- package/dist/ui/assets/{providers-CVxe90mP.js → providers-DjBc2Tmu.js} +2 -2
- package/dist/ui/assets/{quick-llm-Ct6grxEh.js → quick-llm-BBqKKxsq.js} +1 -1
- package/dist/ui/assets/{recovery-screen-BtyCzv9Q.js → recovery-screen-ByHX7_KQ.js} +1 -1
- package/dist/ui/assets/{redirect-uri-Cs2XQJRH.js → redirect-uri-B6NgEOlm.js} +1 -1
- package/dist/ui/assets/{session-freezer-Bv1AQxPg.js → session-freezer-JT2_qyqS.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-BqAkCaPE.js → setup-feature-flags-remote-C2IPMY_Q.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-EvR5fr1C.js → setup-standalone-prelude-CCFh12ns.js} +1 -1
- package/dist/ui/assets/{setup-sudo-Ba1ZKNJf.js → setup-sudo-BVYVcn5F.js} +2 -2
- package/dist/ui/assets/{skills-BLthDf6N.js → skills-CKC6knJt.js} +1 -1
- package/dist/ui/assets/slicc-version-BJ8vuJH5.js +1 -0
- package/dist/ui/assets/{src-BXAvZ-ei.js → src-C1dIx3UV.js} +189 -142
- package/dist/ui/assets/{store-DdWTmm3h.js → store-C6JqWWYW.js} +1 -1
- package/dist/ui/assets/{store-B-jkwqm-.js → store-hs-fjUoK.js} +1 -1
- package/dist/ui/assets/{sudo-BeUuC0o9.js → sudo-B6EyhWhN.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-f52RtdSL.js → upgrade-detection-qW4qvW5A.js} +1 -1
- package/dist/ui/assets/{wc-attach-Cs2JeOdI.js → wc-attach-DDaQOa8_.js} +2 -2
- package/dist/ui/assets/{wc-extension-BI4I-KdP.js → wc-extension-DASy0DKg.js} +2 -2
- package/dist/ui/assets/{wc-follower-4iPR_Tul.js → wc-follower-Egi9mkfF.js} +3 -3
- package/dist/ui/assets/wc-live-DZ8JQMwW.js +8 -0
- package/dist/ui/assets/{wc-nav-B5V0ZfKc.js → wc-nav-COdLdTwW.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-YcNmsJ75.js → wc-onboarding-BnKXeXf-.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-DNzomi1i.js → wc-placeholder-QoCSCfPQ.js} +2 -2
- package/dist/ui/assets/{wc-settings--zuiJWUa.js → wc-settings-BlPzHxwH.js} +2 -2
- package/dist/ui/assets/wc-shell-DfslNU_R.js +117 -0
- package/dist/ui/assets/{wc-sprinkles-CcJhUBxA.js → wc-sprinkles-D8VUY-jR.js} +2 -2
- package/dist/ui/assets/{wc-tray-9TbX3W4_.js → wc-tray-ggci63Lw.js} +2 -2
- package/dist/ui/assets/{xai-grok-DjZBl8MI.js → xai-grok-3sJfnokt.js} +1 -1
- package/dist/ui/assets/{xai-grok-QgmTZ127.js → xai-grok-SLa2T0v9.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +1 -1
- package/dist/ui/assets/provider-store-access-DG1MMrgG.js +0 -1
- package/dist/ui/assets/slicc-version-BOhPSJSS.js +0 -1
- package/dist/ui/assets/wc-live-AqeIm2i0.js +0 -8
- package/dist/ui/assets/wc-shell-Db9tKR47.js +0 -117
|
@@ -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"./logger-DQgFbfwx.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-CpDGMO7m.js";import{c as l,d as u,f as d,i as f,l as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-Cf4bBarA.js";import{a as x,i as S,n as C,r as w,s as T,t as E}from"./src-CcFD5QfS.js";import{$t as D,An as O,At as ee,Bt as te,Cn as k,Ct as A,D as ne,Dn as re,Dt as ie,E as ae,En as oe,Et as se,Fn as ce,Ft as le,Gt as ue,Ht as de,In as j,It as fe,Jt as pe,Kt as me,L as he,Ln as M,Lt as ge,M as _e,Mn as ve,Mt as ye,Nn as N,Nt as P,On as be,Ot as xe,Pn as F,Pt as Se,Q as I,Qt as Ce,R as L,Rn as R,Rt as we,Sn as Te,St as Ee,Tn as De,Tt as z,Ut as Oe,V as ke,Vt as Ae,Wt as je,X as Me,Xt as Ne,Y as Pe,Yt as Fe,Z as Ie,Zt as Le,_n as Re,_t as ze,an as Be,at as Ve,bn as He,bt as Ue,cn as We,ct as Ge,dn as Ke,dt as eee,en as tee,et as qe,fn as B,ft as Je,gn as nee,gt as ree,h as iee,hn as Ye,ht as Xe,in as Ze,it as Qe,jn as $e,jt as et,kn as tt,kt as nt,ln as rt,lt as it,m as at,mn as ot,mt as st,nn as aee,nt as ct,on as lt,ot as oee,pn as ut,pt as dt,qt as ft,rn as pt,rt as mt,sn as see,st as cee,tn as ht,tt as gt,un as _t,ut as vt,vn as V,vt as yt,w as bt,wn as xt,wt as St,xn as Ct,xt as lee,yn as wt,yt as Tt,zt as Et}from"./account-store-DFQ8Dgj9.js";import{t as Dt}from"./runtime-env-DadgceZk.js";import{r as uee}from"./binary-cache-bSOhqXB1.js";import{n as Ot,r as kt,t as At}from"./fetch-body-DDu_AU5I.js";import{a as jt,i as Mt,n as Nt,t as Pt}from"./path-utils-DNJG-zQf.js";import{d as Ft}from"./transform-messages-DEFauvrq.js";import{l as It,m as Lt}from"./bedrock-camp-BfNg24Ce.js";import{t as Rt}from"./__vite-browser-external-5eBdwsFd.js";import{n as zt,t as Bt}from"./mime-types-D7IV6i7k.js";import{t as Vt}from"./image-markers-CdcIBWOf.js";import{n as Ht,o as Ut,s as Wt}from"./tool-ui-t6ocn6AG.js";import{a as Gt,i as dee,o as Kt,r as fee,t as pee}from"./agent-message-to-chat-ChAiEgvC.js";import{a as qt,i as Jt,n as Yt,o as Xt,r as Zt,t as Qt}from"./backend-local-CsZd2f8u.js";import"./runtime-env-DVGQx9p3.js";import{t as $t}from"./types-idfTVsM8.js";import{a as en,i as tn,n as nn,r as rn}from"./mount-C9lbsxh0.js";import{o as an}from"./mount-table-store-DrF_Ifaz.js";import{t as on}from"./remote-cache-JAv9sQH_.js";import{r as sn,t as cn}from"./mount-recovery-mi1lXBvI.js";import{a as ln,c as un,i as dn,n as fn,o as pn,r as mn,s as hn}from"./lick-urls-DLSVBTRW.js";import{C as gn,D as _n,E as vn,S as yn,_ as bn,a as xn,b as Sn,d as Cn,g as wn,h as Tn,m as En,n as Dn,o as On,r as kn,s as An,t as jn,u as Mn,w as Nn,y as mee}from"./db-BTiVtoD4.js";import{a as hee,i as Pn,n as Fn,r as In}from"./tray-runtime-config-BXoU8ne0.js";import{n as Ln,r as gee,t as _ee}from"./slicc-version-BOhPSJSS.js";import{a as Rn,c as zn,d as Bn,i as vee,l as Vn,n as yee,o as Hn,s as bee,t as xee,u as See}from"./lick-manager-BpI2wI9M.js";import{a as Cee,n as Un,r as Wn}from"./fs-mfTn4f6R.js";import{a as wee,c as Tee,i as Eee,l as Gn,n as Dee,o as H,r as Oee,s as Kn}from"./cost-command-AOg9dLn6.js";import{_ as qn,a as Jn,b as Yn,c as Xn,d as kee,f as Aee,g as jee,h as Mee,i as Nee,l as Zn,m as Qn,n as Pee,o as Fee,p as Iee,r as $n,s as Lee,u as er,v as tr,y as nr}from"./skills-BLthDf6N.js";import{n as rr,t as ir}from"./llm-session-id-ZObKEXzb.js";import{n as ar,r as or}from"./frozen-archive-format--7sONywg.js";import{i as sr,r as cr}from"./browser-BAL8RehA.js";import{a as lr,i as ur,n as dr,r as fr,t as pr}from"./telemetry-BugxTkxX.js";import{n as mr,t as hr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as gr,i as _r,r as vr,t as yr}from"./git-config-DA8M5e8O.js";import{a as br,c as xr,i as Sr,o as Cr,r as wr,s as Tr,t as Er}from"./script-catalog-Bt94D0RP.js";import{t as Dr}from"./process-manager-unCzdHp3.js";import{A as Or,C as kr,O as Ar,_ as jr,a as Mr,b as Nr,c as Pr,d as Fr,f as Ir,g as Lr,h as Rr,i as zr,k as Br,l as Vr,m as Hr,n as Ur,o as Wr,p as Gr,r as Kr,s as qr,t as Jr,u as Yr,v as Xr,x as Ree,y as Zr}from"./shared-DqziuFis.js";import{n as Qr,t as $r}from"./esbuild-wasm-C_e51T2J.js";import{n as zee,t as Bee}from"./wasm-compiler-Ct7QZURL.js";import{_ as Vee,a as ei,c as ti,f as Hee,g as ni,h as ri,l as ii,m as Uee,n as Wee,p as Gee,r as ai,u as oi,v as si,y as ci}from"./github-zip-w452Q-_E.js";import{a as li,c as ui,d as di,f as fi,i as pi,l as mi,n as hi,o as gi,p as _i,r as vi,s as yi,u as bi}from"./github-install-S3gH1LN1.js";import{n as xi,t as Si}from"./magick-wasm-DVJe3sB9.js";import{a as Ci,c as Kee,i as qee,l as Jee,n as Yee,o as Xee,r as wi,s as Zee,t as Qee,u as $ee}from"./installer-BesmgfFs.js";import{t as Ti}from"./local-llm-CKMcrybN.js";import{t as Ei}from"./client-CSGMDS3X.js";import{t as Di}from"./redirect-uri-Cs2XQJRH.js";var Oi=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 ki(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 Ai=r(`cdp`);var ji=class{ws=null;nextId=1;_superseded=!1;pending=new Oi;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,Ai.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Ai.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(),Ai.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),Ai.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 ki(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;Ai.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Ai.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;Ai.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,Ai.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Ai.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 Mi=r(`har-recorder`);var Ni=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}`),Mi.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{n.sessionId===t&&this.handleRequestWillBeSent(e,n)},i=n=>{n.sessionId===t&&this.handleResponseReceived(e,n)},a=n=>{n.sessionId===t&&this.handleLoadingFinished(e,n)},o=n=>{n.sessionId===t&&this.handleLoadingFailed(e,n)},s=r=>{if(r.sessionId!==t)return;let i=r.frame;if(!i?.parentId&&i?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=i.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{Mi.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 n=t.requestId,r=t.request,i=t.timestamp;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 n=t.requestId,r=t.response,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 n=t.requestId,r=t.timestamp,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}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let n=t.requestId;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 Pi(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Mi.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 Mi.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)),Mi.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 Mi.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 Pi(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){Mi.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Mi.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Fi=`(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"./logger-DQgFbfwx.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-DdpSaPOK.js";import{c as l,d as u,f as d,i as f,l as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-Cf4bBarA.js";import{a as x,i as S,n as C,r as w,s as T,t as E}from"./src-CcFD5QfS.js";import{$t as D,An as O,At as ee,Bt as te,Cn as k,Ct as A,D as ne,Dn as re,Dt as ie,E as ae,En as oe,Et as se,Fn as ce,Ft as le,Gt as ue,Ht as de,In as j,It as fe,Jt as pe,Kt as me,L as he,Ln as M,Lt as ge,M as _e,Mn as ve,Mt as ye,Nn as N,Nt as P,On as be,Ot as xe,Pn as F,Pt as Se,Q as I,Qt as Ce,R as L,Rn as R,Rt as we,Sn as Te,St as Ee,Tn as De,Tt as z,Ut as Oe,V as ke,Vt as Ae,Wt as je,X as Me,Xt as Ne,Y as Pe,Yt as Fe,Z as Ie,Zt as Le,_n as Re,_t as ze,an as Be,at as Ve,bn as He,bt as Ue,cn as We,ct as Ge,dn as Ke,dt as eee,en as tee,et as qe,fn as B,ft as Je,gn as nee,gt as ree,h as iee,hn as Ye,ht as Xe,in as Ze,it as Qe,jn as $e,jt as et,kn as tt,kt as nt,ln as rt,lt as it,m as at,mn as ot,mt as st,nn as aee,nt as ct,on as lt,ot as oee,pn as ut,pt as dt,qt as ft,rn as pt,rt as mt,sn as see,st as cee,tn as ht,tt as gt,un as _t,ut as vt,vn as V,vt as yt,w as bt,wn as xt,wt as St,xn as Ct,xt as lee,yn as wt,yt as Tt,zt as Et}from"./account-store-BGgapOqM.js";import{t as Dt}from"./runtime-env-DadgceZk.js";import{r as uee}from"./binary-cache-bSOhqXB1.js";import{n as Ot,r as kt,t as At}from"./fetch-body-DDu_AU5I.js";import{a as jt,i as Mt,n as Nt,t as Pt}from"./path-utils-DNJG-zQf.js";import{d as Ft}from"./transform-messages-DEFauvrq.js";import{l as It,m as Lt}from"./bedrock-camp-BfNg24Ce.js";import{t as Rt}from"./__vite-browser-external-5eBdwsFd.js";import{n as zt,t as Bt}from"./mime-types-D7IV6i7k.js";import{t as Vt}from"./image-markers-CdcIBWOf.js";import{n as Ht,o as Ut,s as Wt}from"./tool-ui-t6ocn6AG.js";import{a as Gt,i as dee,o as Kt,r as fee,t as pee}from"./agent-message-to-chat-ChAiEgvC.js";import{a as qt,i as Jt,n as Yt,o as Xt,r as Zt,t as Qt}from"./backend-local-CsZd2f8u.js";import"./runtime-env-DVGQx9p3.js";import{t as $t}from"./types-idfTVsM8.js";import{a as en,i as tn,n as nn,r as rn}from"./mount-DUfqMR7N.js";import{o as an}from"./mount-table-store-DrF_Ifaz.js";import{t as on}from"./remote-cache-JAv9sQH_.js";import{r as sn,t as cn}from"./mount-recovery-BhGJRk0L.js";import{a as ln,c as un,i as dn,n as fn,o as pn,r as mn,s as hn}from"./lick-urls-DLSVBTRW.js";import{C as gn,D as _n,E as vn,S as yn,_ as bn,a as xn,b as Sn,d as Cn,g as wn,h as Tn,m as En,n as Dn,o as On,r as kn,s as An,t as jn,u as Mn,w as Nn,y as mee}from"./db-BTiVtoD4.js";import{a as hee,i as Pn,n as Fn,r as In}from"./tray-runtime-config-BXoU8ne0.js";import{n as Ln,r as gee,t as _ee}from"./slicc-version-BJ8vuJH5.js";import{a as Rn,c as zn,d as Bn,i as vee,l as Vn,n as yee,o as Hn,s as bee,t as xee,u as See}from"./lick-manager-BpI2wI9M.js";import{a as Cee,n as Un,r as Wn}from"./fs-DtHl1BTl.js";import{a as wee,c as Tee,i as Eee,l as Gn,n as Dee,o as H,r as Oee,s as Kn}from"./cost-command-AOg9dLn6.js";import{_ as qn,a as Jn,b as Yn,c as Xn,d as kee,f as Aee,g as jee,h as Mee,i as Nee,l as Zn,m as Qn,n as Pee,o as Fee,p as Iee,r as $n,s as Lee,u as er,v as tr,y as nr}from"./skills-CKC6knJt.js";import{n as rr,t as ir}from"./llm-session-id-ZObKEXzb.js";import{n as ar,r as or}from"./frozen-archive-format--7sONywg.js";import{i as sr,r as cr}from"./browser-BAL8RehA.js";import{a as lr,i as ur,n as dr,r as fr,t as pr}from"./telemetry-BugxTkxX.js";import{n as mr,t as hr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as gr,i as _r,r as vr,t as yr}from"./git-config-DA8M5e8O.js";import{a as br,c as xr,i as Sr,o as Cr,r as wr,s as Tr,t as Er}from"./script-catalog-Bt94D0RP.js";import{t as Dr}from"./process-manager-unCzdHp3.js";import{A as Or,C as kr,O as Ar,_ as jr,a as Mr,b as Nr,c as Pr,d as Fr,f as Ir,g as Lr,h as Rr,i as zr,k as Br,l as Vr,m as Hr,n as Ur,o as Wr,p as Gr,r as Kr,s as qr,t as Jr,u as Yr,v as Xr,x as Ree,y as Zr}from"./shared-DqziuFis.js";import{n as Qr,t as $r}from"./esbuild-wasm-C_e51T2J.js";import{n as zee,t as Bee}from"./wasm-compiler-Ct7QZURL.js";import{_ as Vee,a as ei,c as ti,f as Hee,g as ni,h as ri,l as ii,m as Uee,n as Wee,p as Gee,r as ai,u as oi,v as si,y as ci}from"./github-zip-CmFOTm1q.js";import{a as li,c as ui,d as di,f as fi,i as pi,l as mi,n as hi,o as gi,p as _i,r as vi,s as yi,u as bi}from"./github-install-D-qYA6oL.js";import{n as xi,t as Si}from"./magick-wasm-DVJe3sB9.js";import{a as Ci,c as Kee,i as qee,l as Jee,n as Yee,o as Xee,r as wi,s as Zee,t as Qee,u as $ee}from"./installer-BesmgfFs.js";import{t as Ti}from"./local-llm-BZBzyZhe.js";import{t as Ei}from"./client-CSGMDS3X.js";import{t as Di}from"./redirect-uri-B6NgEOlm.js";var Oi=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 ki(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 Ai=r(`cdp`);var ji=class{ws=null;nextId=1;_superseded=!1;pending=new Oi;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,Ai.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Ai.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(),Ai.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),Ai.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 ki(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;Ai.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Ai.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;Ai.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,Ai.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Ai.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 Mi=r(`har-recorder`);var Ni=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}`),Mi.debug(`Started recording`,{recordingId:r,targetId:e,currentUrl:i}),r}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{n.sessionId===t&&this.handleRequestWillBeSent(e,n)},i=n=>{n.sessionId===t&&this.handleResponseReceived(e,n)},a=n=>{n.sessionId===t&&this.handleLoadingFinished(e,n)},o=n=>{n.sessionId===t&&this.handleLoadingFailed(e,n)},s=r=>{if(r.sessionId!==t)return;let i=r.frame;if(!i?.parentId&&i?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=i.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{Mi.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 n=t.requestId,r=t.request,i=t.timestamp;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 n=t.requestId,r=t.response,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 n=t.requestId,r=t.timestamp,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}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let n=t.requestId;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 Pi(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Mi.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 Mi.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)),Mi.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 Mi.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 Pi(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){Mi.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Mi.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Fi=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -5415,7 +5415,7 @@ except BaseException:
|
|
|
5415
5415
|
`)}}function rz(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=az(e.stdin??``,o),c=qR(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:Or},version:`v${Or}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new ez(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var iz=class extends cP.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 ez){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 az(e,t){return new iz(e,t)}function oz(e){if(e===``)return[];let t=e.split(`
|
|
5416
5416
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function sz(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function cz(e){return new TextDecoder(`utf-8`).decode(dN(e))}function lz(e){if(e&&typeof e.write==`function`)return e}var uz=class extends nP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=oz(cz(sz(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 ez&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function dz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=lz(e.output)}else r=t,i=lz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new uz(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:uz,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var fz=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`?`: ${pz(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 pz(e){try{return JSON.stringify(e)}catch{return String(e)}}function mz(e){return new Promise(t=>setTimeout(t,e))}function hz(e,t,n){let r;if(r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:e?`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`:t,!n)return r;let i=[];for(let[e,t]of Object.entries(n))if(t!=null)if(Array.isArray(t))for(let n of t)n!=null&&i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);else i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`);return i.length===0?r:r+(r.includes(`?`)?`&`:`?`)+i.join(`&`)}function gz(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 _z(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function vz(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 yz(e){if(_z(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 bz(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 xz(e){let t=e.sleep??mz;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=hz(n.baseUrl,o,s.params),l=gz(n.headers,s.headers);if(n.token){let e=await n.token({method:a,path:o,url:c});e&&(Object.keys(l).some(e=>e.toLowerCase()===`authorization`)||(l.Authorization=`Bearer ${e}`))}let u=bz(s.body,l),d={method:a,headers:l};u!==void 0&&(d.body=u);let f=null;for(let a=0;a<i;a++){let o=n.timeoutMs?new AbortController:null,l=o?setTimeout(()=>o.abort(Error(`timeout`)),n.timeoutMs):null,u=s.signal&&o?.signal?AbortSignal.any([s.signal,o.signal]):s.signal??o?.signal,p=u?{...d,signal:u}:d,m;try{m=await e.fetch(c,p)}finally{l!==null&&clearTimeout(l)}if(f=m,m.ok){let e=await yz(m);return s.raw?{body:e,headers:Object.fromEntries(m.headers.entries()),status:m.status}:e}if(!(a+1<i&&r.has(m.status))){let e=await yz(m).catch(()=>null);throw new fz(m.status,m.statusText,c,e)}let h=vz(m.headers.get(`retry-after`)),g=500*2**a;await t(h===null?g:h)}if(f){let e=await yz(f).catch(()=>null);throw new fz(f.status,f.statusText,c,e)}throw Error(`http: no attempts made for ${a} ${c}`)}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 Sz(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 Cz(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`,Sz(JSON.stringify(t.schema)));let i=t.readOnly===void 0?`/workspace/`:Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly),a=t.cwd===void 0?n||`.`:String(t.cwd),o=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,`--read-only`,i,a,o,String(e)]}function wz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Cz(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 Tz(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...Array.from(e.subarray(r,r+n)));return btoa(t)}async function Ez(e){let t=[];for(let[n,r]of e.entries()){if(typeof r==`string`){t.push({name:n,value:r});continue}let e=new Uint8Array(await r.arrayBuffer());t.push({name:n,file:{data:Tz(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Dz(e,t){let n=()=>Object.keys(t).some(e=>e.toLowerCase()===`content-type`);return typeof e==`string`?{body:e}:e instanceof URLSearchParams?(n()||(t[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`),{body:e.toString()}):e instanceof Blob?{descriptor:{kind:`blob`,data:Tz(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Tz(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Tz(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Ez(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Oz(e){return e?`const __b64 = (s) => { const bin = atob(s); const n = bin.length; const u = new Uint8Array(n); for (let i = 0; i < n; i++) u[i] = bin.charCodeAt(i); return u; };const __body = `+JSON.stringify(e)+`;if (__body.kind === 'bytes') { __init.body = __b64(__body.data); }else if (__body.kind === 'blob') { __init.body = new Blob([__b64(__body.data)], { type: __body.type }); }else if (__body.kind === 'formdata') { const __fd = new FormData(); for (const e of __body.entries) { if (e.file) { __fd.append(e.name, new Blob([__b64(e.file.data)], { type: e.file.type }), e.file.filename); } else { __fd.append(e.name, e.value); } } __init.body = __fd; }`:``}function kz(e){return`const h = {};r.headers.forEach((v, k) => { h[k] = v; });const ct = r.headers.get('content-type') || '';const __rt = `+JSON.stringify(e??null)+`;const __ctl = ct.toLowerCase();const __binPrefixes = ['image/','audio/','video/','application/octet-stream','application/pdf','application/protobuf','application/x-protobuf','application/wasm','application/zip'];const __isXml = __ctl.indexOf('+xml') !== -1 || __ctl.indexOf('application/xml') === 0 || __ctl.indexOf('text/xml') === 0;const __isBinary = __rt === 'binary' || (__rt !== 'text' && __rt !== 'json' && !__isXml && __binPrefixes.some((p) => __ctl.indexOf(p) === 0));if (__isBinary) {const __u = new Uint8Array(await r.arrayBuffer());let __s = ''; const __cs = 0x8000;for (let __i = 0; __i < __u.length; __i += __cs) { __s += String.fromCharCode.apply(null, __u.subarray(__i, __i + __cs)); }return { ok: r.ok, status: r.status, headers: h, body: btoa(__s), bodyEncoding: 'base64' };}const t = await r.text();let b;const __jsonWanted = __rt === 'json' || (__rt !== 'text' && ct.indexOf('application/json') !== -1);if (__jsonWanted) { if (!t) { b = null; } else { try { b = JSON.parse(t); } catch (e) { b = t; } } }else { b = t; }return { ok: r.ok, status: r.status, headers: h, body: b };`}async function Az(e,t={}){let n={},r=t.headers??{};for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);let i=typeof t.method==`string`?t.method:`GET`,a=t.credentials===`same-origin`||t.credentials===`omit`?t.credentials:`include`,o=t.body,{body:s,descriptor:c}=o==null?{}:await Dz(o,n),l={method:i,credentials:a,headers:n};s!==void 0&&(l.body=s);for(let e of[`mode`,`cache`,`redirect`,`referrer`,`referrerPolicy`,`integrity`,`keepalive`]){let n=t[e];n!==void 0&&(l[e]=n)}let u=Oz(c),d=kz(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function jz(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 Mz(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=jz(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 Nz(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 Pz(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 Pz(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:Fz(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:Fz(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:Fz(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 Fz(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 Iz(e){return{findTab:t=>e.call(`browser`,`findTab`,[Rz(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,zz(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[jz(t),Lz(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[jz(t),Lz(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[jz(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[jz(t),n]),fetch:(t,n,r={})=>Az(n,r).then(n=>e.call(`browser`,`evalAsync`,[jz(t),n])),websocket:Mz(e)}}function Lz(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 Rz(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 zz(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function Bz(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function Vz(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:Bz(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function Hz(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 Uz(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Wz(e){return e==null?[]:Array.isArray(e)?e:[e]}function Gz(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:Uz(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,Hz(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,Hz(r)]),receiveFeatureReport:async t=>Uz((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 Kz(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>Gz(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[Wz(t)]))[0];if(!n)throw Error(`No device selected.`);return Gz(e,n)}}}function qz(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 Jz=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 };`)}},Yz=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=qz(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 Jz(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 Jz(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?.())}},Xz=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 Yz(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()}},Zz=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 Yz(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 Xz(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 Qz(e){let t=async t=>new Zz(e),n=async(t,n)=>new Zz(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const $z=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`]),eB={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 tB(e,t){let n=eB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function nB(e){return{...e,time:QR,fmt:HN,pool:JR}}function rB(e,t){return e?.startsWith(`/`)?$R(e):t}function iB(e){return e.includes(`require`)||e.includes(`import`)}async function aB(e,t,n,r){return iB(t)?e.call(`module`,`buildGraph`,[t,rB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function oB(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:Qz(e)}}function cB(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c}=e,l=new Map(t.files.map(e=>[e.path,e.cjsSource])),u=new Map(t.files.map(e=>[e.path,e.kind])),d=new Map,f=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:dB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=lB(t,n,r,i,c);if(a.hit)return a;if($z.has(t))throw tB(e,t);if(Br.has(t))throw pB(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},p=(e,n)=>{let r=f(n);if(r.hit)return r.value;let i=e?.[n];if(i)return m(i);throw n in t.errors?Error(t.errors[n]):uB(n)};function m(e){let n=d.get(e);if(n)return n.exports;let i=l.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};d.set(e,o);let s=n=>p(t.edges[e],n),c=$R(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,c,e,r,a,globalThis.Buffer,globalThis),u.get(e)===`cjs`&&oB(o.exports),o.exports}return{require:e=>p(t.entryMap,e)}}function lB(e,t,n,r,i){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:sF}:e===`crypto`?{hit:!0,value:YP}: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:eP}:e===`assert/strict`?{hit:!0,value:$N}:e===`util`?{hit:!0,value:wP}:e===`events`?{hit:!0,value:rP}:e===`os`?{hit:!0,value:XP}:e===`tty`?{hit:!0,value:cF}:e===`stream`?{hit:!0,value:cP}:e===`url`?{hit:!0,value:dF}:e===`zlib`?{hit:!0,value:GR}:e===`readline`&&i?{hit:!0,value:i}:e===`readline/promises`&&i?{hit:!0,value:i.promises}:{hit:!1}}function uB(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 dB(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 fB={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function pB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${fB[t]||``}`)}async function mB(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";
|
|
5417
5417
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof ez?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function hB(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?Hz(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,Hz(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function gB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>hB(e,t)),request:async t=>hB(e,await e.call(`serial`,`request`,[Wz(t)]))}}function _B(e,t){let n=t.handle,r=e=>({status:e.status,data:Uz(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,Hz(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,Hz(r)])}}function vB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>_B(e,t)),request:async t=>_B(e,await e.call(`usb`,`request`,[Wz(t)]))}}function yB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function bB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function xB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function SB(e){let t=yB(e.argv[1]??``),n=xB(t,`references`),r=xB(t,`assets`),i=xB(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)+`
|
|
5418
|
-
`),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 ${bB(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 CB=new Map,wB=new Map;function TB(e){let t=crypto.randomUUID();return CB.set(t,e),t}function EB(e){return CB.get(e)??null}function DB(e,t){if(!CB.has(e))return t.abort(),()=>{};let n=wB.get(e);return n||(n=new Set,wB.set(e,n)),n.add(t),()=>{let n=wB.get(e);n&&(n.delete(t),n.size===0&&wB.delete(e))}}function OB(e){CB.delete(e);let t=wB.get(e);if(t){wB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function kB(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 AB(e){let t=EB(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 kB(e)}}function jB(e){return`slicc-sync-fs-`+e}const MB=`sync-fs-ack`,NB=`sync-fs-res`,PB=6e5,FB=5e3,IB=`exec`;function LB(e){return e.channel===IB}function RB(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 zB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,PB)}async function BB(e){let t=EB(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=RB(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()},zB(e.timeoutMs,PB)),o=DB(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`}:kB(e)}finally{clearTimeout(a),o()}}function VB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function HB(e){let t=WB(e);if(GB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw VB(`EIO`,e.label);KB(t,e.label)}function UB(e){let t=HB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw VB(`EIO`,e.label)}}function WB(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 VB(`EIO`,e.label)}return t}function GB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function KB(e,t){throw VB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function qB(e){return(t,n,r)=>{let i=UB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:IB})),timeoutMs:n+FB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw VB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function JB(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 YB(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??qB(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&JB(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=zB(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 XB(e,t){return VB(e,`sync-fs bridge, '${t}'`)}function ZB(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function QB(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:ZB(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return HB(r(`GET`,e))},writeFile(e,t){HB(r(`POST`,e,t))},stat(e){let t=UB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw XB(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=UB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw XB(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=UB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw XB(`EIO`,e);return t},exists(e){let t=UB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw XB(`EIO`,e);return t},mkdir(e){HB(r(`POST`,e,void 0,`mkdir`))},rm(e){HB(r(`POST`,e,void 0,`rm`))}}}const $B=new TextEncoder,eV=new TextDecoder;function tV(e){if(!e.ok)return{status:4,payload:$B.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:$B.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function nV(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(eV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(eV.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 rV(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 iV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function aV(e,t,n={}){let{header:r,window:i}=rV(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 VB(`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 VB(`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 VB(`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 VB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return nV(f,d)}}}function oV(e,t){return VB(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 oV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw oV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw oV(`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 oV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!sV(t))throw oV(`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 oV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw oV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function lV(e){return(t,n,r)=>{let i=e.call({...t,channel:IB},n+FB,r);if(!i.ok)throw VB(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 VB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function uV(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 lN(r)}function dV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function fV(e,t){return t?cV(t):e.syncFsToken?QB(e.syncFsToken):void 0}function pV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return aV(e.syncSab,t)}function mV(e,t,n,r,i){let a=pV(e,t),o=fV(e,a);if(Object.assign(r,kN(n,e.cwd,o,i)),e.syncFsToken)return YB(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:lV(a)}:{}})}function hV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Ln().version,writable:!1,enumerable:!1,configurable:!1})}function gV(e,t,n){let r=MN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:AN({writeStdout:t,writeStderr:n,exit:e=>{throw new ez(e)},color:r})}}function _V(e,t,n){return{readStdinBytes:()=>dN(e.stdin??``),writeStdout:t,writeStderr:n}}function vV(e){return{usbBridge:vB(e),serialBridge:gB(e),hidBridge:Kz(e)}}async function yV(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=nz(i,a),s=rz(e,i,a),{colorApi:c,cliApi:l}=gV(!!e.env?.NO_COLOR,i,a),u=new bM(t),d=_V(e,i,a),f=CN(u,C,d),p=await uV(u,e.cwd,dV(e,a)),m=mV(e,t,p,f,d),h=Vz(u,p,e.cwd,a),g=wz(h,{cwd:e.cwd}),_=SB({argv:e.argv,fs:f,exec:h}),v=Iz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=vV(u),S=xz({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 Nz(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=nB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=$R(T),D=await aB(u,e.code,e.cwd,T),O=cB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:NP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:sB(u),nodeReadline:dz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;hV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await mB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await bV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await xV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function bV(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 xV(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 SV(){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 CV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=SV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&yV(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 wV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=SV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&jM(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 TV=CV(),EV=wV();function DV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?kV():EV({kind:e,ctx:t}):typeof Worker<`u`?OV():TV({kind:e,ctx:t})}function OV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return AV(new Worker(new URL(`/assets/js-realm-worker-kzfHhxZE.js`,``+import.meta.url),{type:`module`}))}function kV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return AV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function AV(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 jV(){if(Ir())return decodeURIComponent(Rr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function MV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function NV(e){return e instanceof Error?e.message:String(e)}function PV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function FV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:PV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function IV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:PV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const LV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,RV=/\bimport\s*\.\s*meta\b/g;function zV(e,t){let n=JSON.stringify(t);return e.replace(LV,n).replace(RV,`({ url: ${n} })`)}async function BV(e,t,n,r){let i=await e();return i.transpileModule(zV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function VV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Qr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Yr(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Nr(e))return e;let a=MV(t),o;try{return await FV(n,e,t,a)}catch(e){o=e}try{return await BV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${NV(o)}; typescript fallback: ${NV(e)}`)}}}function HV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Qr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Yr(t));return async({source:e,filename:t})=>{if(!Nr(e)&&!Zr(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?MV(t):void 0,o=i?t:`[eval].js`,s;try{return await IV(n,e,t,a)}catch(e){s=e}try{return await BV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${NV(s)}; typescript fallback: ${NV(e)}`)}}}function UV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5418
|
+
`),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 ${bB(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 CB=new Map,wB=new Map;function TB(e){let t=crypto.randomUUID();return CB.set(t,e),t}function EB(e){return CB.get(e)??null}function DB(e,t){if(!CB.has(e))return t.abort(),()=>{};let n=wB.get(e);return n||(n=new Set,wB.set(e,n)),n.add(t),()=>{let n=wB.get(e);n&&(n.delete(t),n.size===0&&wB.delete(e))}}function OB(e){CB.delete(e);let t=wB.get(e);if(t){wB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function kB(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 AB(e){let t=EB(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 kB(e)}}function jB(e){return`slicc-sync-fs-`+e}const MB=`sync-fs-ack`,NB=`sync-fs-res`,PB=6e5,FB=5e3,IB=`exec`;function LB(e){return e.channel===IB}function RB(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 zB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,PB)}async function BB(e){let t=EB(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=RB(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()},zB(e.timeoutMs,PB)),o=DB(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`}:kB(e)}finally{clearTimeout(a),o()}}function VB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function HB(e){let t=WB(e);if(GB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw VB(`EIO`,e.label);KB(t,e.label)}function UB(e){let t=HB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw VB(`EIO`,e.label)}}function WB(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 VB(`EIO`,e.label)}return t}function GB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function KB(e,t){throw VB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function qB(e){return(t,n,r)=>{let i=UB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:IB})),timeoutMs:n+FB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw VB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function JB(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 YB(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??qB(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&JB(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=zB(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 XB(e,t){return VB(e,`sync-fs bridge, '${t}'`)}function ZB(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function QB(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:ZB(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return HB(r(`GET`,e))},writeFile(e,t){HB(r(`POST`,e,t))},stat(e){let t=UB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw XB(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=UB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw XB(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=UB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw XB(`EIO`,e);return t},exists(e){let t=UB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw XB(`EIO`,e);return t},mkdir(e){HB(r(`POST`,e,void 0,`mkdir`))},rm(e){HB(r(`POST`,e,void 0,`rm`))}}}const $B=new TextEncoder,eV=new TextDecoder;function tV(e){if(!e.ok)return{status:4,payload:$B.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:$B.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function nV(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(eV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(eV.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 rV(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 iV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function aV(e,t,n={}){let{header:r,window:i}=rV(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 VB(`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 VB(`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 VB(`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 VB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return nV(f,d)}}}function oV(e,t){return VB(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 oV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw oV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw oV(`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 oV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!sV(t))throw oV(`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 oV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw oV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function lV(e){return(t,n,r)=>{let i=e.call({...t,channel:IB},n+FB,r);if(!i.ok)throw VB(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 VB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function uV(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 lN(r)}function dV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function fV(e,t){return t?cV(t):e.syncFsToken?QB(e.syncFsToken):void 0}function pV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return aV(e.syncSab,t)}function mV(e,t,n,r,i){let a=pV(e,t),o=fV(e,a);if(Object.assign(r,kN(n,e.cwd,o,i)),e.syncFsToken)return YB(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:lV(a)}:{}})}function hV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Ln().version,writable:!1,enumerable:!1,configurable:!1})}function gV(e,t,n){let r=MN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:AN({writeStdout:t,writeStderr:n,exit:e=>{throw new ez(e)},color:r})}}function _V(e,t,n){return{readStdinBytes:()=>dN(e.stdin??``),writeStdout:t,writeStderr:n}}function vV(e){return{usbBridge:vB(e),serialBridge:gB(e),hidBridge:Kz(e)}}async function yV(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=nz(i,a),s=rz(e,i,a),{colorApi:c,cliApi:l}=gV(!!e.env?.NO_COLOR,i,a),u=new bM(t),d=_V(e,i,a),f=CN(u,C,d),p=await uV(u,e.cwd,dV(e,a)),m=mV(e,t,p,f,d),h=Vz(u,p,e.cwd,a),g=wz(h,{cwd:e.cwd}),_=SB({argv:e.argv,fs:f,exec:h}),v=Iz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=vV(u),S=xz({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 Nz(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=nB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=$R(T),D=await aB(u,e.code,e.cwd,T),O=cB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:NP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:sB(u),nodeReadline:dz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;hV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await mB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await bV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await xV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function bV(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 xV(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 SV(){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 CV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=SV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&yV(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 wV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=SV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&jM(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 TV=CV(),EV=wV();function DV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?kV():EV({kind:e,ctx:t}):typeof Worker<`u`?OV():TV({kind:e,ctx:t})}function OV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return AV(new Worker(new URL(`/assets/js-realm-worker-BCmp7aOj.js`,``+import.meta.url),{type:`module`}))}function kV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return AV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function AV(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 jV(){if(Ir())return decodeURIComponent(Rr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function MV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function NV(e){return e instanceof Error?e.message:String(e)}function PV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function FV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:PV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function IV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:PV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const LV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,RV=/\bimport\s*\.\s*meta\b/g;function zV(e,t){let n=JSON.stringify(t);return e.replace(LV,n).replace(RV,`({ url: ${n} })`)}async function BV(e,t,n,r){let i=await e();return i.transpileModule(zV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function VV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Qr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Yr(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Nr(e))return e;let a=MV(t),o;try{return await FV(n,e,t,a)}catch(e){o=e}try{return await BV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${NV(o)}; typescript fallback: ${NV(e)}`)}}}function HV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Qr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Yr(t));return async({source:e,filename:t})=>{if(!Nr(e)&&!Zr(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?MV(t):void 0,o=i?t:`[eval].js`,s;try{return await IV(n,e,t,a)}catch(e){s=e}try{return await BV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${NV(s)}; typescript fallback: ${NV(e)}`)}}}function UV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5419
5419
|
`);return t===-1?``:e.slice(t+1)}function WV(e){return jt(e).dir}const GV=[`node`,`require`,`default`],KV=[`node`,`import`,`default`],qV=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,JV=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,YV=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,XV=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,ZV=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function QV(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function $V(e){let t=Ree(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!QV(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(qV,`require`,`require`),r(JV,`import`,`import`),r(YV,`import`,`import`),r(XV,`import`,`export`),r(ZV,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function eH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=UV(e);if(n===`esm`){if(!r)throw Error(`Cannot load ESM module '${t}': no transpile hook configured (run: ipk install esbuild-wasm)`);return await r({source:i,path:t,kind:n})}return i}async function tH(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??GV,s=e.importConditions??KV,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 eH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=WV(e),p={};for(let{specifier:t,kind:i}of $V(n)){let n;try{n=await kr(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 kr(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 nH(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Ar.has(e)||$z.has(e))}async function rH(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 $V(t))if(nH(e))try{let t=await tH({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?KV:GV,requireConditions:GV,importConditions:KV});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&&(Nr(t)||Zr(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 iH(){return globalThis.navigator?.hid??null}function aH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function oH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&aH(e)===aH(t)&&!!e.productName}var sH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(oH(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 lH(){return cH||=new sH,cH}const uH=4194304;function dH(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 fH(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function pH(e){e.opened||await e.open()}function mH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${uH}-byte (4 MiB) v1 limit`)}function hH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function gH(e,t){return(await t.getDevices()).map(t=>dH(e.register(t),t))}async function _H(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>dH(e.register(t),t))}function vH(e,t){return dH(t,fH(e,t))}async function yH(e,t){await fH(e,t).open()}async function bH(e,t){await fH(e,t).close()}async function xH(e,t,n,r){mH(r.byteLength,`send report payload`);let i=fH(e,t);await pH(i),await i.sendReport(n,r)}async function SH(e,t,n,r){mH(r.byteLength,`send feature report payload`);let i=fH(e,t);await pH(i),await i.sendFeatureReport(n,r)}async function CH(e,t,n){let r=fH(e,t);return await pH(r),{reportId:n,bytes:hH(await r.receiveFeatureReport(n))}}async function wH(e,t,n){let r=fH(e,t);await pH(r);let i=e=>{n({reportId:e.reportId,bytes:hH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const TH=6e4;function EH(){return Jt()}function DH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),TH);qt(`hid-device`,e??[],void 0,{timeoutMs:TH}).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 OH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var kH=class{registry;constructor(e){this.registry=e}hid(){let e=iH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return gH(this.registry,this.hid())}async request(e){if(EH()){let t=await DH(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=>dH(this.registry.register(e),e))}return _H(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(vH(this.registry,e))}open(e){return yH(this.registry,e)}close(e){return bH(this.registry,e)}sendReport(e,t,n){return xH(this.registry,e,t,OH(n))}sendFeatureReport(e,t,n){return SH(this.registry,e,t,OH(n))}async receiveFeatureReport(e,t){let n=await CH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return wH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},AH=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:OH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:OH(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 jH(e,t){return e&&iH()?new kH(lH()):t?new AH(t):null}function MH(e){return async function(t,n){let r=t instanceof Request?t:null,i=NH(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=FH(r?.headers,n?.headers),s=await RH(n,r,a,o);s.defaultContentType&&!IH(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 NH(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function PH(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 FH(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=PH(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function IH(e,t){return LH(e,t)!==void 0}function LH(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function RH(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=VH(e.body,n);return{body:await zH(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=LH(r,`content-type`)??``,a=e&&(!i||!u(i));return{body:n.byteLength===0?void 0:a?HH(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function zH(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 HH(e);if(e instanceof ArrayBuffer)return HH(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return HH(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return HH(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 BH(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function VH(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!BH(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function HH(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 UH(){return globalThis.navigator?.serial??null}var WH=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}))}};let GH=null;function KH(){return GH||=new WH,GH}const qH=4194304;function JH(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 YH(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function XH(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function ZH(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 QH(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return JH(n,e.get(n))})}async function $H(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return JH(i,e.get(i))}function eU(e,t){return JH(t,YH(e,t))}async function tU(e,t,n){let r=YH(e,t);await r.port.open(n),r.opened=!0}async function nU(e,t){let n=YH(e,t);if(n.reader){try{await n.reader.cancel()}catch{}try{n.reader.releaseLock()}catch{}n.reader=void 0}if(n.pendingRead=void 0,n.leftover=void 0,n.writer){try{n.writer.releaseLock()}catch{}n.writer=void 0}await n.port.close(),n.opened=!1}function rU(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 iU(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 aU(e,t,n){let r=YH(e,t),i=Math.min(n.maxBytes??4194304,qH),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=ZH(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=rU(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=XH(c,a.value);let e=u();if(e)return e}}return c}async function oU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${qH}-byte (4 MiB) v1 limit`);return await iU(YH(e,t)).write(n),n.length}async function sU(e,t){return YH(e,t).port.getSignals()}async function cU(e,t,n){await YH(e,t).port.setSignals(n)}const lU=6e4;function uU(){return Jt()}function dU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),lU);qt(`serial-port`,e??[],void 0,{timeoutMs:lU}).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 fU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var pU=class{registry;constructor(e){this.registry=e}serial(){let e=UH();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return QH(this.registry,this.serial())}async request(e){if(uU()){let t=await dU(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 JH(r,this.registry.get(r))}return $H(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(eU(this.registry,e))}open(e,t){return tU(this.registry,e,t)}close(e){return nU(this.registry,e)}read(e,t){return aU(this.registry,e,t)}write(e,t){return oU(this.registry,e,t)}getSignals(e){return sU(this.registry,e)}setSignals(e,t){return cU(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?fU(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:fU(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 hU(e,t){return e&&UH()?new pU(KH()):t?new mU(t):null}function gU(){return globalThis.navigator?.usb??null}function _U(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var vU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(_U(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 yU=null;function bU(){return yU||=new vU,yU}const xU=4194304;function SU(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 CU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function wU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${xU}-byte (4 MiB) v1 limit`)}function TU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function EU(e,t){return(await t.getDevices()).map(t=>SU(e.register(t),t))}async function DU(e,t,n){let r=await t.requestDevice({filters:n});return SU(e.register(r),r)}function OU(e,t){return SU(t,CU(e,t))}async function kU(e,t){await CU(e,t).open()}async function AU(e,t){await CU(e,t).close()}async function jU(e,t,n){await CU(e,t).selectConfiguration(n)}async function MU(e,t,n){await CU(e,t).claimInterface(n)}async function NU(e,t,n){await CU(e,t).releaseInterface(n)}async function PU(e,t,n,r){wU(r,`control-in length`);let i=await CU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?TU(i.data):new ArrayBuffer(0)}}async function FU(e,t,n,r){wU(r.byteLength,`control-out payload`);let i=await CU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function IU(e,t,n,r){wU(r,`transfer-in length`);let i=await CU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?TU(i.data):new ArrayBuffer(0)}}async function LU(e,t,n,r){wU(r.byteLength,`transfer-out payload`);let i=await CU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function RU(e,t){await CU(e,t).reset()}const zU=6e4;function BU(){return Jt()}function VU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),zU);qt(`usb-device`,e??[],void 0,{timeoutMs:zU}).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 HU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var UU=class{registry;constructor(e){this.registry=e}usb(){let e=gU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return EU(this.registry,this.usb())}async request(e){if(BU()){let t=await VU(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 SU(this.registry.register(n),n)}return DU(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(OU(this.registry,e))}open(e){return kU(this.registry,e)}close(e){return AU(this.registry,e)}selectConfig(e,t){return jU(this.registry,e,t)}claim(e,t){return MU(this.registry,e,t)}release(e,t){return NU(this.registry,e,t)}async controlIn(e,t,n){let r=await PU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return FU(this.registry,e,t,HU(n))}async transferIn(e,t,n){let r=await IU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return LU(this.registry,e,t,HU(n))}reset(e){return RU(this.registry,e)}},WU=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:HU(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:HU(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function GU(e,t){return e&&gU()?new UU(bU()):t?new WU(t):null}function KU(e,t,n,r={}){let{header:i,window:a}=rV(t),o=new Map,s=!1,c=r.dispatch??(e=>LB(e)?BB(e):AB(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}=tV(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 qU=r(`realm-host`);function JU(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?TB({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;YU(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?KU(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&OB(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 YU(e,t,n,r,i,a){try{let o=await XU(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=zW(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 XU(e,t,n,r,i){switch(e.channel){case`vfs`:return nW(e.op,e.args,t);case`exec`:return hW(e.op,e.args,t,i);case`fetch`:return yW(e.op,e.args,t);case`browser`:return CW(e.op,e.args,ZU(n),n);case`usb`:return IW(e.op,e.args,$U(n));case`serial`:return LW(e.op,e.args,eW(n));case`hid`:return RW(e.op,e.args,tW(n),r);case`module`:return xW(e.op,e.args,t);case`wasm`:return SW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function ZU(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 QU(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 $U(e){if(e.usbBackend)return e.usbBackend;let t=GU(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function eW(e){if(e.serialBackend)return e.serialBackend;let t=hU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function tW(e){if(e.hidBackend)return e.hidBackend;let t=jH(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function nW(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 dW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await fW(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const rW=10485760;function iW(e){return e.fileCount>=500||e.totalBytes>=rW}function aW(e){return e.entries.length>=2e4}async function oW(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 sW(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 cW(e,t,n,r,i){if(n>1048576||iW(r)||r.totalBytes+n>rW){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 lW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function lW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await oW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function uW(e,t,n){if(aW(n))return;let r=[t];for(;r.length>0;){if(aW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await sW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await oW(e,t,r,n):a.isFile&&await cW(e,t,a.size,n,r)}}async function dW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await uW(e,t,n),t!==`/tmp`&&await uW(e,`/tmp`,n),{entries:n.entries}}async function fW(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 pW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),mW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function hW(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 _W(t,n,r);if(e===`kill`)return vW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function gW(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 _W(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??{};gW(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 vW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&pW.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 yW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?MH(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 bW(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 xW(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=bW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return rH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:VV({ipk:s}),transpileEntry:HV({ipk:s})})}async function SW(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 Bee(e=>n.fs.readFileBuffer(e),i)}async function CW(e,t,n,r){switch(e){case`findTab`:return EW(n,t[0]??{});case`ensureTab`:{let e=t[0];return DW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return OW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return OW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return MW(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return NW(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await QU(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return QU(r).update(e,n)}case`wsClose`:{let e=t[0];return QU(r).close(e)}case`wsList`:return QU(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.sendCDP(`Emulation.setDeviceMetricsOverride`,{width:r,height:i,deviceScaleFactor:1,mobile:!1})})}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 jW(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function wW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function TW(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=wW()?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){qU.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function EW(e,t){let n=await TW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=PW(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 DW(e,t,n){let r=await TW(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=FW(t);if(e){let t=r.find(t=>FW(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function OW(e,t,n,r){return e.withTab(t,async()=>kW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function kW(e){if(typeof e!=`string`)return e;let t=AW(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=AW(t);if(typeof e==`object`&&e)return e}return t}return e}function AW(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 jW(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(){
|
|
5420
5420
|
try {
|
|
5421
5421
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -5538,7 +5538,7 @@ Examples:
|
|
|
5538
5538
|
skill list
|
|
5539
5539
|
skill info bluebubbles
|
|
5540
5540
|
skill read bluebubbles
|
|
5541
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5541
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-CKC6knJt.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${IG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:RG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5542
5542
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:zG(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
|
|
5543
5543
|
`,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+`
|
|
5544
5544
|
`,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 HG=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&zn(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=>pi(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=>Vn(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 UG(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=HG.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 WG(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function GG(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 KG(e,t,n,r){let i=await GG(e,t);return Gee(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?WG(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function qG(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await KG(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 Uee(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 JG(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 ii(t),d=await fi(s,c,o.ref,u,!0);if(d&&r.sha===d&&await YG(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await XG(s,c,l,n,o.ref,t,u);if(`error`in f)return{...o,outcome:`error`,error:f.error};let p=f.files,m=f.path;if(p.size===0)return{...o,outcome:`error`,error:`no files at ${s}/${c}${m?`/${m}`:``} — the skill may have moved or been removed upstream`};let{changes:h,writes:g,removals:_}=await qG(e,`${ni}/${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 tK(e,{changes:h,writes:g,removals:_}),await _i(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 YG(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 XG(e,t,n,r,i,a,o){let s=await ai(e,t,a,i??`main`);if(s.status===`ok`){let i=ei(s.files),a=n||ZG(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:eK(i,a),path:a}}try{return{files:$G(QG(await Wee(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 ZG(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 QG(e){return new Map([...e].filter(([e])=>ti(e)))}function $G(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function eK(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);ti(e)&&r.set(e,i)}return $G(r)}async function tK(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 nK(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 PG(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${ni}/${n}/SKILL.md`,u=await GG(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&MG(new TextDecoder().decode(u))===MG(c.content);if(WG(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${ni}/${n}`,{recursive:!0}),await e.writeFile(l,d),await _i(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function rK(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 iK(e,t,n,r){let i=pi(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 aK(e,t,n){if(t.length===0)return{targets:await bi(e),missing:[]};let r=[],i=[];for(let a of t){let t=await di(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?iK(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}}function oK(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -5572,7 +5572,7 @@ Nothing to update — all skills are current.
|
|
|
5572
5572
|
`,{stdout:s,stderr:``,exitCode:0}}function bK(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5573
5573
|
`,exitCode:1}:zn(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
|
|
5574
5574
|
`,exitCode:1}}function xK(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`||!Vn(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
|
|
5575
|
-
`,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=bK(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 SK(e){let t=await(await import(`./skills-
|
|
5575
|
+
`,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=bK(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 SK(e){let t=await(await import(`./skills-CKC6knJt.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${IG()}`,stderr:``,exitCode:0}:{stdout:RG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function CK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-CKC6knJt.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 di(n,t),a=i?mi(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:zG(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+`
|
|
5576
5576
|
`,stderr:``,exitCode:0}}async function wK(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 gi(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 TK(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 hi(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 EK(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await hi(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 DK(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 OK(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await ii(r),l=await vi(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:DK(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:DK(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 ai(i,a,r,o);if(e.status===`ok`){let r=await fi(i,a,o,c),s=await wK(u,i,a,ei(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 TK(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await EK(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 ui()),{stdout:p,stderr:m,exitCode:+!!m}}async function kK(e,t,n,r){switch(e[0]){case`tabs`:return vK(t,n,r,e.includes(`--json`));case`recommendations`:return yK(t,n,e.includes(`--install`));case`update`:case`upgrade`:return cK(e.slice(1),t,n);case`list`:return SK(t);case`info`:case`read`:return CK(e[0],e[1],t);case`search`:return jK(e,n);default:return null}}function AK(e,t,n){return H(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return BG();let a=await kK(r,e,t,n);if(a)return a;let o=xK(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return BG();if(o.sourceRef.startsWith(`tessl:`))return MK(o.sourceRef,o.force,e,t);let s=kG(o.sourceRef);if(s)return FG(s.hostname,s.task,e,t,o.force);let c=pi(o.sourceRef);return c?OK(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 jK(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?pK(a,t,i):BG()}async function MK(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5577
5577
|
`,exitCode:1};let a=await uK(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await ii(r);return hi(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function NK(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5578
5578
|
|
|
@@ -6975,7 +6975,7 @@ Common base URLs:
|
|
|
6975
6975
|
llama.cpp http://localhost:8080/v1
|
|
6976
6976
|
vLLM http://localhost:8000/v1
|
|
6977
6977
|
Jan http://localhost:1337/v1
|
|
6978
|
-
`}function qie(){return H(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Kie(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
6978
|
+
`}function qie(){return H(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Kie(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-DCjokX3w.js`),{verifyConnection:a}=await import(`./local-llm-BZBzyZhe.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(Q6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6979
6979
|
`,exitCode:1};let c=await a(s,t(Q6)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
|
|
6980
6980
|
`)+`
|
|
6981
6981
|
`,exitCode:1}}if(o===`discover`){let e=n(Q6)??``;return i(Q6,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
|
|
@@ -7019,20 +7019,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
7019
7019
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
7020
7020
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
7021
7021
|
short name resolves on the PATH.
|
|
7022
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
7022
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-C6JqWWYW.js`).then(e=>e.r);if(await a(i,t.fs))return n8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CSGMDS3X.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 eae(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>s8(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 yae(i,t);let m=await u8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-Bo6uW5vD.js`);e({name:i,serverUrl:r,auth:u})}return t8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${e8}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
7023
7023
|
`)+`
|
|
7024
|
-
`)}async function eae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
7025
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
7024
|
+
`)}async function eae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-BGgapOqM.js`).then(e=>e.r),c=await _ae(r.oauthFetchImpl),l=r.oauthLauncher??await c8(),u=await i(e,n,c);$6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await Di(),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 tae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp list
|
|
7025
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-Bo6uW5vD.js`);await n();let{listServers:r}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.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 t8(r8(o))}function r8(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(`
|
|
7026
7026
|
`)+`
|
|
7027
7027
|
`}async function nae(e,t){if(jX(e))return t8(`usage: mcp search <query>
|
|
7028
7028
|
|
|
7029
7029
|
Case-insensitive substring search across the cached tools of every
|
|
7030
7030
|
registered MCP server. Matches tool name OR description and prints a
|
|
7031
7031
|
table of (server, tool, description, match-field) rows.
|
|
7032
|
-
`);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
7033
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
7032
|
+
`);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-Bo6uW5vD.js`);await i();let{listServers:a}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return t8(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,rae(e.description),e.match]);return t8(r8(l))}function rae(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function iae(e,t){if(e.length===0||jX(e))return e.length===0?n8(`mcp delete: expected <name>`):t8(`usage: mcp delete <name>
|
|
7033
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-Bo6uW5vD.js`);await r(n);let{deleteServer:a}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),o=await a(n,t.fs);await bae(n,t),await xae(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-BGgapOqM.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){$6.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?n8(`mcp delete: no server, alias, or account found for "${n}"`):t8([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
|
|
7034
7034
|
`)+`
|
|
7035
|
-
`)}async function aae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(sae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
7035
|
+
`)}async function aae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(sae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-Bo6uW5vD.js`);await i(n);let{getServer:a}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return n8(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return t8(cae(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return n8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=oae(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return t8(lae(n,l));let p=uae(d,l.inputSchema);if(!p.ok)return n8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-CSGMDS3X.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=mae(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function oae(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=i8(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=i8(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 i8(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 sae(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
7036
7036
|
|
|
7037
7037
|
mcp invoke <name> List tools on <name>.
|
|
7038
7038
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -7062,7 +7062,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
7062
7062
|
|
|
7063
7063
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
7064
7064
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
7065
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
7065
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-Bo6uW5vD.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return n8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CSGMDS3X.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return n8(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,protocolVersion:l.getNegotiatedProtocolVersion(),tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await u8(n,d,t);return t8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function gae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp auth <name> [--silent | --interactive]
|
|
7066
7066
|
|
|
7067
7067
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
7068
7068
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7074,7 +7074,7 @@ Options:
|
|
|
7074
7074
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7075
7075
|
directly. Use after revoking a refresh token or
|
|
7076
7076
|
when the AS no longer accepts the cached one.
|
|
7077
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7077
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-Bo6uW5vD.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-C6JqWWYW.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return n8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return n8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return n8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-DdpSaPOK.js`).then(e=>e.r),f=d(u);if(!f)return n8(`mcp auth: provider "${u}" is not registered`);if(a)return await o8(r,f,t);if(!f.onSilentRenew)return i?n8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await o8(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 n8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);$6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?t8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?n8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await o8(r,f,t)}async function o8(e,t,n){if(!t.onOAuthLogin)return n8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await c8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?t8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):n8(`mcp auth: interactive login for "${e}" did not complete`)}async function s8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-BGgapOqM.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DdpSaPOK.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){$6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function c8(){let{createOAuthLauncher:e}=await import(`./oauth-service-BWDgBZaN.js`);return e()}async function _ae(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-Cf4bBarA.js`).then(e=>e.a),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 l8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DtHl1BTl.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 vae(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7078
7078
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7079
7079
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7080
7080
|
const escape = (s) => {
|
|
@@ -7088,7 +7088,7 @@ const r = await exec(cmd);
|
|
|
7088
7088
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7089
7089
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7090
7090
|
process.exit(r.exitCode || 0);
|
|
7091
|
-
`}async function yae(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,vae(e)),t.scriptCatalog?.invalidateJsh()}async function bae(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function xae(e,t){let{removeAppSprinkles:n}=await import(`./apps
|
|
7091
|
+
`}async function yae(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,vae(e)),t.scriptCatalog?.invalidateJsh()}async function bae(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function xae(e,t){let{removeAppSprinkles:n}=await import(`./apps--wWNQP2K.js`);await n(e,t.fs)}async function u8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps--wWNQP2K.js`);return(await r(e,t,n.fs)).length}catch(t){return $6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function d8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function f8(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 Sae(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 Cae(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function wae(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 Tae(e){let t=[`total: ${f8(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(`${f8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${Sae(e)}`)}return`${t.join(`
|
|
7092
7092
|
`)}\n`}function Eae(e={}){return H(`meminfo`,async t=>{let n=wae(t);if(`error`in n)return d8(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
7093
7093
|
|
|
7094
7094
|
Usage:
|
|
@@ -7114,7 +7114,7 @@ Options:
|
|
|
7114
7114
|
-h, --help Show this help message
|
|
7115
7115
|
`}function Aae(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function h8(e){return`$${e.toFixed(2)}`}const jae=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Mae(e){let t=`${e.id} ${e.name??``}`;return!jae.test(t)}function Nae(e){let t=e.toLowerCase();t=t.replace(/-\d{8}$/,``),t=t.replace(/-\d{4}$/,``),t=t.replace(/-(preview|latest)$/,``);let n=t.match(/^(claude-(?:opus|sonnet|haiku))/);if(n)return n[1];let r=t.match(/^(gpt-\d+)(?:\.\d+)?(-[a-z][-a-z]*)?$/);if(r)return r[1]+(r[2]??``);let i=t.match(/^gemini-[\d.]+-(.+)$/);if(i)return`gemini-${i[1]}`;let a=t.match(/^gemini-(\d+)-(.+)$/);if(a)return`gemini-${a[2]}`;let o=t.match(/^grok-[\d.]+-([\w-]+)$/);if(o)return`grok-${o[1]}`;if(t.match(/^(grok)-[\d.]+$/))return`grok`;let s=t.match(/^(o\d+(?:-[a-z]+)?)(?:-\d.*)?$/);return s?s[1]:t.replace(/-[\d.]+$/,``)}function Pae(e){let t=new Map;for(let n of e){let e=Nae(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function Fae(e,t,n,r,i){let a=i?Oae(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 Iae(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=`${h8(e.cost.input)} / ${h8(e.cost.output)}`,a=`${Aae(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(`
|
|
7116
7116
|
`)+`
|
|
7117
|
-
`}function Lae(e){return H(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
7117
|
+
`}function Lae(e){return H(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-DCjokX3w.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:kae(),stderr:``,exitCode:0};let l=t.includes(`--json`),u=t.includes(`--all`),d=t.includes(`--all-versions`),f=t.includes(`--refresh`),p=t.includes(`--no-benchmarks`),m=t.indexOf(`--provider`),h=m>=0?t[m+1]:void 0,g=o(),_=s(),v=n();if(v.length===0)return{stdout:``,stderr:`No provider accounts configured. Run the provider settings to add one.
|
|
7118
7118
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await Dae(e,f),S.length===0&&(S=void 0));let C;if(h){let e=r();if(!e.includes(h))return{stdout:``,stderr:`Unknown provider: ${h}. Available: ${e.join(`, `)}\n`,exitCode:1};C=[h]}else C=u?[...new Set(v.map(e=>e.providerId))]:[g];let w=[],T=[];for(let e of C){let t=a(e).filter(Mae);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Fae(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=Pae(n)),w.push(...n),!l){let t=i(e);T.push(Iae(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7119
7119
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7120
7120
|
`);let E=`${x}:${b}`,D=`${g}:${_}`;return T.push(E===D?`Currently using: ${E}\n`:`Currently using: ${E} (selected ${D} — resolved to a different model)\n`),{stdout:T.join(`
|
|
@@ -7154,7 +7154,7 @@ Examples:
|
|
|
7154
7154
|
oauth-domain add adobe '*.da.live'
|
|
7155
7155
|
oauth-domain list adobe
|
|
7156
7156
|
oauth-domain remove adobe admin.da.live
|
|
7157
|
-
`}function qae(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
7157
|
+
`}function qae(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-DCjokX3w.js`),[i,a,o]=e;try{switch(i){case`list`:{if(a){let e=t(a);return e.length===0?{stdout:`(no extra domains configured for ${a})\n`,stderr:``,exitCode:0}:{stdout:e.join(`
|
|
7158
7158
|
`)+`
|
|
7159
7159
|
`,stderr:``,exitCode:0}}let e=r(),n=Object.entries(e).filter(([,e])=>e.length>0);return n.length===0?{stdout:`(no extra OAuth domains configured)
|
|
7160
7160
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7226,7 +7226,7 @@ Examples:
|
|
|
7226
7226
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7227
7227
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7228
7228
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7229
|
-
`}function eoe(){return H(`oauth-token`,toe)}async function toe(e,t){let n=await import(`./account-store-
|
|
7229
|
+
`}function eoe(){return H(`oauth-token`,toe)}async function toe(e,t){let n=await import(`./account-store-BGgapOqM.js`).then(e=>e.r),r=await import(`./providers-DdpSaPOK.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:$ae(),stderr:``,exitCode:0};if(e.includes(`--list`))return voe(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return doe(e);if(e.includes(`--renew`))return foe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return poe(e,t);let i=noe(e);if(!i.ok)return i.result;let a=roe(e),o=ioe(e,n,r);if(!o.ok)return o.result;let s=aoe(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await ooe(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return soe(o.value,s.value,i.value,n.getOAuthAccountInfo)}function noe(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:T8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function roe(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function ioe(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:T8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(y8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>y8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:T8(`oauth-token: no OAuth providers configured`)}}function y8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function aoe(e,t){let n=t(e);return n?y8(n)?{ok:!0,value:n}:{ok:!1,result:T8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:T8(`oauth-token: unknown provider "${e}"`)}}async function ooe(e,t,n,r){let i=n(e);return i&&!i.expired?b8(e,i,r):!i?.expired||!t.onSilentRenew||!await uoe(t.onSilentRenew)?null:b8(e,n(e),r)}function b8(e,t,n){return n&&!Qae(t?.scopes,n)?null:x8(e,t?.maskedValue)}function x8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:T8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function soe(e,t,n,r){try{let i=await coe(e,t,n);return i.error?i.error:loe(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),T8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),T8(`oauth-token: login failed: ${n}`))}}async function coe(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-BWDgBZaN.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:T8(`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-BWDgBZaN.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:T8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function loe(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),T8(`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?x8(e,r.maskedValue):r?.token?T8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),T8(`oauth-token: login completed but no token was saved`))}async function uoe(e){try{return await e()!==null}catch{return!1}}function S8(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function doe(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-BGgapOqM.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-DdpSaPOK.js`).then(e=>e.r),o=S8(e,n,i,a);if(!o)return T8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return T8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return T8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return T8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return T8(`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 foe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-BGgapOqM.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-DdpSaPOK.js`).then(e=>e.r),a=S8(e,t,r,i);if(!a)return T8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return T8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return T8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${C8(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: ${C8(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(`
|
|
7230
7230
|
`)+`
|
|
7231
7231
|
`,stderr:``,exitCode:+!u}}function C8(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 poe(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-BIKnTjZm.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-BWDgBZaN.js`),i=await moe(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return T8(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return T8(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let s=await o(a.config);return s?{stdout:`${s}\n`,stderr:``,exitCode:0}:T8(`oauth-token: intercept timed out or was cancelled`)}function moe(e,t){let n=e.indexOf(`--from-file`);return n>=0?hoe(e[n+1],t):goe(e)}async function hoe(e,t){if(!e)return{ok:!1,result:T8(`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:T8(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function goe(e){let t=w8(e,`--authorize-url`),n=w8(e,`--redirect-pattern`);if(!t)return{ok:!1,result:T8(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:T8(`oauth-token: --redirect-pattern is required`)};let r=_oe(e);return r.ok?{ok:!0,value:{authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.value.length>0?{rewrite:r.value}:{}}}:r}function _oe(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]!==`--rewrite`)continue;let r=e[n+1];if(!r)return{ok:!1,result:T8(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:T8(`oauth-token: --rewrite "${r}" must be "<match>=<key>=<value>"`)};let[a,o,...s]=i;t.push({match:a,appendParams:{[o]:s.join(`=`)}})}return{ok:!0,value:t}}function w8(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function T8(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function voe(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7232
7232
|
`,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(`
|
|
@@ -7344,7 +7344,7 @@ Examples:
|
|
|
7344
7344
|
plugin list
|
|
7345
7345
|
plugin info my-plugin
|
|
7346
7346
|
plugin remove my-plugin
|
|
7347
|
-
`}function Xoe(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(Yoe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Qoe(i,a,e);case`list`:case`ls`:return await nse(i,e);case`info`:return await rse(i,e);case`validate`:return await ise(i,a,e);case`remove`:case`rm`:case`delete`:return await ase(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
7347
|
+
`}function Xoe(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(Yoe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Qoe(i,a,e);case`list`:case`ls`:return await nse(i,e);case`info`:return await rse(i,e);case`validate`:return await ise(i,a,e);case`remove`:case`rm`:case`delete`:return await ase(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-DtHl1BTl.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 W8(e,t,n){let r=ose(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-D-qYA6oL.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 Zoe(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function G8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${B8}/${t.map(Zoe).join(`--`)}`}async function K8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-CmFOTm1q.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 q8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Qoe(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin install <path|repo>
|
|
7348
7348
|
|
|
7349
7349
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
7350
7350
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -7355,19 +7355,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
7355
7355
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
7356
7356
|
standard skills discovery, and each supported streamable-http MCP server
|
|
7357
7357
|
is registered in the MCP store as "<plugin>:<server>".
|
|
7358
|
-
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-sgPDMLWT.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
7358
|
+
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-sgPDMLWT.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-hs-fjUoK.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await q8(i,o),H8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await tse(u,n),g=await ese(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),V8($oe(u,h,g,s??o,l.diagnostics))}function $oe(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:`,J8(i)),c.join(`
|
|
7359
7359
|
`)+`
|
|
7360
|
-
`}async function ese(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-
|
|
7361
|
-
`);let{listInstalledPlugins:n}=await import(`./store-
|
|
7360
|
+
`}async function ese(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-C6JqWWYW.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 tse(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-C6JqWWYW.js`).then(e=>e.r),{McpClient:a}=await import(`./client-CSGMDS3X.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 nse(e,t){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin list
|
|
7361
|
+
`);let{listInstalledPlugins:n}=await import(`./store-hs-fjUoK.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return V8("No agent plugins installed. Use `plugin install <path>`.\n");let a=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of i){let t=r[e];a.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let o=a[0].map((e,t)=>Math.max(...a.map(e=>e[t].length)));return V8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
|
|
7362
7362
|
`)+`
|
|
7363
7363
|
`)}async function rse(e,t){if(e.length===0||jX(e))return e.length===0?H8(`plugin info: expected <name>`):V8(`usage: plugin info <name>
|
|
7364
|
-
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-
|
|
7364
|
+
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-hs-fjUoK.js`),i=await r(n,t.fs);if(!i)return H8(`plugin info: no installed plugin named "${n}"`);let a=await U8(t),{loadPluginFromDirectory:o}=await import(`./loader-sgPDMLWT.js`),s=await o(a,i.root);if(!s.ok)return H8(`plugin info: plugin at ${i.root} no longer loads:\n${J8(s.diagnostics)}`);let{plugin:c}=s,l=c.manifest,u=[`${l.name}${l.version?` v${l.version}`:``}`,...l.description?[` ${l.description}`]:[],` root: ${c.root}`,...l.license?[` license: ${l.license}`]:[],...l.homepage?[` home: ${l.homepage}`]:[],``,`Skills (${c.skills.length}):`,...c.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${c.mcp.servers.length}):`,...c.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return s.diagnostics.length>0&&u.push(``,`Diagnostics:`,J8(s.diagnostics)),V8(u.join(`
|
|
7365
7365
|
`)+`
|
|
7366
7366
|
`)}async function ise(e,t,n){if(e.length===0||jX(e))return e.length===0?H8(`plugin validate: expected <path|repo>`):V8(`usage: plugin validate <path|repo>
|
|
7367
7367
|
`);let r=await U8(n),i=await W8(e[0],t,r);if(i.kind===`error`)return H8(`plugin validate: ${i.message}`);let a,o=null;if(i.kind===`github`){if(!n.fetch)return H8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);o=`/tmp/.plugin-validate/${G8(i.ref).split(`/`).pop()}`;let e=await K8(i.ref,o,r,n.fetch);if(e)return H8(`plugin validate: ${e}`);a=o}else a=i.root;let{loadPluginFromDirectory:s}=await import(`./loader-sgPDMLWT.js`),c;try{c=await s(r,a)}finally{o&&await q8(r,o)}if(!c.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${J8(c.diagnostics)}\n`,exitCode:1};let{plugin:l}=c,u=l.mcp.servers.filter(e=>e.status===`supported`).length,d=[`plugin validate: OK — "${l.manifest.name}"${l.manifest.version?` v${l.manifest.version}`:``}`,` skills: ${l.skills.length}`,` mcp servers: ${u} supported, ${l.mcp.servers.length-u} skipped (mcp.json ${l.mcp.status})`];return c.diagnostics.length>0&&d.push(`Diagnostics:`,J8(c.diagnostics)),V8(d.join(`
|
|
7368
7368
|
`)+`
|
|
7369
7369
|
`)}async function ase(e,t){if(e.length===0||jX(e))return e.length===0?H8(`plugin remove: expected <name>`):V8(`usage: plugin remove <name>
|
|
7370
|
-
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-
|
|
7370
|
+
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-hs-fjUoK.js`),a=await r(n,t.fs);if(!a)return H8(`plugin remove: no installed plugin named "${n}"`);let o=0;if(a.mcpServerNames&&a.mcpServerNames.length>0){let{deleteServer:e,getServer:r}=await import(`./store-C6JqWWYW.js`).then(e=>e.r);for(let i of a.mcpServerNames)(await r(i,t.fs))?.pluginOrigin===n&&await e(i,t.fs)&&(o+=1)}await i(n,t.fs);let s=a.root.startsWith(`${B8}/`);return s&&await q8(await U8(t),a.root),V8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
|
|
7371
7371
|
`)+`
|
|
7372
7372
|
`)}function ose(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 J8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
7373
7373
|
`)}const Y8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],sse=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],cse={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function lse(e={}){return H(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return xse();let n=e.processManager??use();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -9079,7 +9079,7 @@ ${e}
|
|
|
9079
9079
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
9080
9080
|
${t}
|
|
9081
9081
|
---`);let a=yb(n);return a&&(i+=a),i}};const P9=r(`scoop-lifecycle-manager`);var vme=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(t.isCone||e!==void 0&&t.folder!==e)continue;let n=this.contexts.get(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){P9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){P9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof Wn))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}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)P9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{P9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new Wn(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,i));let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new _me(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{P9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),P9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),P9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(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 P9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.contexts.get(e);o||=(await this.createTab(e),this.contexts.get(e));let s=this.tabs.get(e);if(s?.status===`initializing`){if(P9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){P9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.contexts.get(e),s=this.tabs.get(e)}if(!o){P9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s&&(s.status=`processing`,s.lastActivity=new Date().toISOString(),this.tabs.set(e,s),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),P9.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();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),P9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||lr(`spawn`,e.folder)}catch(n){P9.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){P9.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=>{P9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),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=>{P9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{P9.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.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&P9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),P9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){P9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();P9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{P9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),P9.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.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){P9.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();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),lr(`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:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&this.deps.messageRouter.flushOnIdle(e),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);P9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),lr(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.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?.(a.jid,o)}catch(e){P9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{P9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const F9=r(`scoop-message-router`);var yme=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(F9.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){F9.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}`);lr(`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),F9.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);F9.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){F9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){F9.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(F9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){F9.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{F9.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.isCone||!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);F9.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);F9.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;if(n.reported||r<3e5)return;n.reported=!0;let i=`Lick queue remained deferred while scoop was busy for ${3e5/1e3}s`;F9.warn(`Busy lick queue may be starved`,{jid:e,error:i}),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){F9.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){F9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){F9.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(F9.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){F9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){F9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=vn(jn(Sn(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){F9.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}: ${Sh(e.content,e.attachments)}`).join(`
|
|
9082
|
-
`),l=s.flatMap(e=>Ch(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=vn(jn(Sn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`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){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{F9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{F9.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),F9.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=>{F9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();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(),F9.info(`All messages cleared`)}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 I9=r(`orchestrator`);var bme=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new wb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Zb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Yb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Ub({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),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 Fb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>En(e),saveMessage:e=>yn(e)});lickRegistry=new Db({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new yme({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=>yn(e),deleteMessage:e=>xn(e),clearMessagesForScoop:e=>kn(e),clearAllMessages:()=>Dn(),getMessagesSince:(e,t,n)=>Tn(e,t,n),setState:(e,t)=>_n(e,t)},isExternalLickChannel:fg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new vme({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>gn(e),deleteScoop:e=>On(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>xee(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)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(e){await mee(),this.sharedFs=await jb(()=>Un.create({dbName:`slicc-fs`}),e),this.sessionStore=new Eh,this.fsWatcher=new Cee,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new E_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new Jg(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new Ab(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Mn();for(let e of Object.values(t)){e.isCone&&(e.trigger=void 0,e.requiresTrigger=!1,e.assistantLabel=e.assistantLabel||`sliccy`),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await wn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Nb({onTaskRun:async(e,t)=>{I9.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(),I9.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);I9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,isCone:t.isCone,error:n}),t.isCone||this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Eee(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=O_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}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}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setScoopExistenceResolver(e=>this.getScoops().some(t=>yee(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){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)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}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){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}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)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Un.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await bb(this.sharedFs).catch(e=>{I9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new E_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Jg(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Ab(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),I9.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)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return En(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}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--7sONywg.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(Oee)]}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&&I9.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,I9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new ug,t=this.sharedFs;return new Zv({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:hy(),snapshotStore:{read:e=>cy(t,e),write:(e,n)=>sy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.71.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function xme(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){L9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>Eme(e,n,t,()=>r(n));async function o(o){let l=o.runId??e.makeRunId(),u=o.sentinel,d={id:l,name:o.name,source:o.source,origin:i(o.parentJid),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(l,d),wme(t,n);let f=a(o.ctx,l),p=Tme(e.processManager,d,l,()=>r(l));return e.runRealm(o.code,[`workflow`,o.filename,l],f).then(e=>s(l,u,e)).catch(e=>c(l,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>L9.warn(`workflow run lifecycle error`,e)),{runId:l}}async function s(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?l(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?l(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):l(t,`done`,i,null)}function c(e,t){return l(e,`error`,null,t)}async function l(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${R9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(R9,{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:l},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);L9.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=l,s.preview=i===`done`?Cme(a):o??``,r(n),u(s)}function u(t){t.origin===`cone`&&e.fireLick({type:`workflow`,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:o,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){L9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function Sme(e){let t=xme(e);return globalThis[J7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Cme(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function wme(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 Tme(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 Eme(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Dme(n,t,a?.args??[],r):e===`agent`?Ome(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Dme(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>z9&&i.logs.splice(0,i.logs.length-z9),r()}return{stdout:``,stderr:``,exitCode:0}}async function Ome(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())}}var kme=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=V9(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))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new $t(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new $t(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new $t(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new $t(`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 $t(`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}renderProcFile(e,t){if(e===1)return Fme(t);let n=this.pm.get(e);switch(t){case`status`:return Ame(n);case`cmdline`:return jme(n);case`cwd`:return Mme(n);case`stat`:return Nme(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Ame(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Pme(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(`
|
|
9082
|
+
`),l=s.flatMap(e=>Ch(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=vn(jn(Sn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys()){let t=this.deps.getTabs().get(e);this.recordBusyDeferralIfPresent(e);let n=(this.messageQueues.get(e)?.length??0)>0;t?.status===`ready`&&n&&!this.debounceStates.has(e)&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`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){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{F9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{F9.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),F9.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=>{F9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();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(),F9.info(`All messages cleared`)}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 I9=r(`orchestrator`);var bme=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new wb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Zb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Yb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Ub({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),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 Fb({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>En(e),saveMessage:e=>yn(e)});lickRegistry=new Db({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new yme({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=>yn(e),deleteMessage:e=>xn(e),clearMessagesForScoop:e=>kn(e),clearAllMessages:()=>Dn(),getMessagesSince:(e,t,n)=>Tn(e,t,n),setState:(e,t)=>_n(e,t)},isExternalLickChannel:fg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new vme({getScoops:()=>this.scoops,getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>gn(e),deleteScoop:e=>On(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>xee(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)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(e){await mee(),this.sharedFs=await jb(()=>Un.create({dbName:`slicc-fs`}),e),this.sessionStore=new Eh,this.fsWatcher=new Cee,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new E_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new Jg(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new Ab(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Mn();for(let e of Object.values(t)){e.isCone&&(e.trigger=void 0,e.requiresTrigger=!1,e.assistantLabel=e.assistantLabel||`sliccy`),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await wn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Nb({onTaskRun:async(e,t)=>{I9.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(),I9.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);I9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,isCone:t.isCone,error:n}),t.isCone||this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Eee(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=O_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}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}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setScoopExistenceResolver(e=>this.getScoops().some(t=>yee(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){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)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}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){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}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)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Un.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await bb(this.sharedFs).catch(e=>{I9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new E_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new Jg(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Ab(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),I9.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)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return En(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}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--7sONywg.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(Oee)]}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&&I9.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,I9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new ug,t=this.sharedFs;return new Zv({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:hy(),snapshotStore:{read:e=>cy(t,e),write:(e,n)=>sy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.72.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function xme(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){L9.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>Eme(e,n,t,()=>r(n));async function o(o){let l=o.runId??e.makeRunId(),u=o.sentinel,d={id:l,name:o.name,source:o.source,origin:i(o.parentJid),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(l,d),wme(t,n);let f=a(o.ctx,l),p=Tme(e.processManager,d,l,()=>r(l));return e.runRealm(o.code,[`workflow`,o.filename,l],f).then(e=>s(l,u,e)).catch(e=>c(l,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>L9.warn(`workflow run lifecycle error`,e)),{runId:l}}async function s(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?l(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?l(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):l(t,`done`,i,null)}function c(e,t){return l(e,`error`,null,t)}async function l(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${R9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(R9,{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:l},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);L9.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=l,s.preview=i===`done`?Cme(a):o??``,r(n),u(s)}function u(t){t.origin===`cone`&&e.fireLick({type:`workflow`,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:o,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){L9.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function Sme(e){let t=xme(e);return globalThis[J7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Cme(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function wme(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 Tme(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 Eme(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Dme(n,t,a?.args??[],r):e===`agent`?Ome(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Dme(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>z9&&i.logs.splice(0,i.logs.length-z9),r()}return{stdout:``,stderr:``,exitCode:0}}async function Ome(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())}}var kme=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=V9(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))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new $t(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new $t(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new $t(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new $t(`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 $t(`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}renderProcFile(e,t){if(e===1)return Fme(t);let n=this.pm.get(e);switch(t){case`status`:return Ame(n);case`cmdline`:return jme(n);case`cwd`:return Mme(n);case`stat`:return Nme(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Ame(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Pme(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(`
|
|
9083
9083
|
`)+`
|
|
9084
9084
|
`}function jme(e){return e.argv.join(`\0`)+`\0`}function Mme(e){return e.cwd+`
|
|
9085
9085
|
`}function Nme(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -9088,4 +9088,4 @@ ${t}
|
|
|
9088
9088
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
9089
9089
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
9090
9090
|
`}}function Ime(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(jB(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(!EB(n.token))return;let a=i.get(n.id);if(a){r({type:MB,id:n.id}),a.result&&r({type:NB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:MB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:NB,id:n.id,...e})};(LB(n)?BB(n):AB(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 W9(){return globalThis}function Lme(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 Rme(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 zme(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Bme(e,t)}function Bme(e,{orchestrator:t,log:n}){let r=t.getScoops(),i;if(i=e.targetScoop?r.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):r.find(e=>e.isCone),!i){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!pre(i)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:i.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 a=Eg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=Lme(e),s=Rme(e),c=e.type,l={id:`${c}-${s}-${Date.now()}`,chatJid:i.jid,senderId:c,senderName:`${c}:${o}`,content:a.content,timestamp:e.timestamp,fromAssistant:!1,channel:c,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l).catch(e=>{n.warn(`Lick message routing failed`,{channel:c,eventName:o,error:String(e)})})}async function Vme(e,t,n,r,i){let a=new Dr,o=new bme(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,W9().__slicc_browser=t,await n.bind(o,t);let s=pn(()=>n.emitTrayRuntimeStatus()),c=Xne(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function Hme(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-AOg9dLn6.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-BpI2wI9M.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??zme,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function Ume(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function Wme(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Sme({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>YW(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>Y7().slice(10,22),splitResult:(e,t)=>X7(e,t)})}async function Gme(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.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))+`
|
|
9091
|
-
`,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 Kme(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-Cxjciab-.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 qme(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 cre(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})},Jme(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Jme(e){let t=m();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:()=>lre()}}function Yme(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-mi1lXBvI.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function Xme(){gee(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-f52RtdSL.js`);return e()})}function Zme(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-f52RtdSL.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 Qme(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-BM2oq7W2.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 $me(){return mt()}async function ehe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Xme();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Vme(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?Yh(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new kme(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Hme(l,e,o);s(`lick-manager-ready`),f&&Wme({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Gme({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;$me()&&(g=await Kme(p,o,e.localLickWsUrl??null));let _=qme(n,p,o);f&&Yme(f,p,o),a||await Ume(l),s(`cone-bootstrapped`),f&&Zme(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Qme(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Ime({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 the({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 the(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)}nhe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function nhe(e){let t=W9();t.__slicc_pm===e.processManager&&delete t.__slicc_pm,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[J7]}const G9=`x-bypass-llm-proxy`;function rhe(e,t,n){return t?(r,i)=>{if(!ihe(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 ihe(e,t,n){if(ohe(e,t))return!0;let r=n?.()??null;return r?ahe(e,r,t):!1}function ahe(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 ohe(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 she(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 che=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(!lhe(e)||e.source!==`panel`)return;let t=e.payload;uhe(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=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,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 lhe(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 uhe(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 dhe=class extends c9{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 fhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new che({transport:t,processManager:i,createShell:(a,o)=>new dhe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??mt,getLeaderStatus:e.webhook?.getLeaderStatus??dn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function phe(e){let t=new mhe(e);return t.start(),{stop:()=>t.dispose()}}var mhe=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!hhe(e)||e.source!==`panel`)return;let t=e.payload;if(ghe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(_he(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}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 $t(`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 $t(`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(vhe(e.type),e.requestId,new $t(`EACCES`,`vfs-rpc-host has no writable backend wired`),yhe(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 $t(`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 $t(`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 $t(`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 hhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ghe(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 _he(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 vhe(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 yhe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof $t?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function bhe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=rhe(e.bind(globalThis),t,xhe)}function xhe(){let e=f();if(!e)return null;try{return new URL(e).origin}catch{return null}}function She(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 Che=she(e=>Ehe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Che.handle(e.data)});function whe(e){let t=xa(e.pageBuildId,`6.71.0-mt1x8rbl`);return()=>{t&&dr(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.71.0-mt1x8rbl`)}}function The(e){bhe(),p(e.localApiBaseUrl??null),v(e.bridgeToken??null),UW(e.syncFsBridgeEnabled??!1),l(e.extensionDelegateId??null),She(e.localStorageSeed??{}),e.flagFloat&&la(e.flagFloat)}async function Ehe(e){va(e.instanceId);let t=whe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{The(e),pr().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=wa(e.kernelPort),a=new zg(r),o=zg.createCallbacks(a),c=new Ta(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Bi(c);Y9=await ehe({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-14cdGa6x.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(Ki(i));let m=await Ohe({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){Dhe(e.kernelPort,t)}}function Dhe(e,t){ba(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 Ohe(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=fhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=phe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await khe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function khe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-Cbtek1FE.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-SaPIFvTd.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-Cf4bBarA.js`).then(e=>e.a),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())});
|
|
9091
|
+
`,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 Kme(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-Cxjciab-.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 qme(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 cre(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})},Jme(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Jme(e){let t=m();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:()=>lre()}}function Yme(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-BhGJRk0L.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function Xme(){gee(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-qW4qvW5A.js`);return e()})}function Zme(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-qW4qvW5A.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 Qme(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-BM2oq7W2.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 $me(){return mt()}async function ehe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Xme();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Vme(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?Yh(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new kme(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Hme(l,e,o);s(`lick-manager-ready`),f&&Wme({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Gme({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;$me()&&(g=await Kme(p,o,e.localLickWsUrl??null));let _=qme(n,p,o);f&&Yme(f,p,o),a||await Ume(l),s(`cone-bootstrapped`),f&&Zme(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Qme(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Ime({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 the({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 the(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)}nhe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function nhe(e){let t=W9();t.__slicc_pm===e.processManager&&delete t.__slicc_pm,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[J7]}const G9=`x-bypass-llm-proxy`;function rhe(e,t,n){return t?(r,i)=>{if(!ihe(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 ihe(e,t,n){if(ohe(e,t))return!0;let r=n?.()??null;return r?ahe(e,r,t):!1}function ahe(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 ohe(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 she(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 che=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(!lhe(e)||e.source!==`panel`)return;let t=e.payload;uhe(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=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,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 lhe(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 uhe(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 dhe=class extends c9{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 fhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new che({transport:t,processManager:i,createShell:(a,o)=>new dhe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??mt,getLeaderStatus:e.webhook?.getLeaderStatus??dn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function phe(e){let t=new mhe(e);return t.start(),{stop:()=>t.dispose()}}var mhe=class{transport;client;writableClient;log;unsubscribe=null;constructor(e){this.transport=e.transport,this.client=e.client,this.writableClient=e.writableClient??null,this.log=e.logger??console}start(){this.unsubscribe||=this.transport.onMessage(e=>{if(!hhe(e)||e.source!==`panel`)return;let t=e.payload;if(ghe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(_he(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}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 $t(`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 $t(`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(vhe(e.type),e.requestId,new $t(`EACCES`,`vfs-rpc-host has no writable backend wired`),yhe(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 $t(`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 $t(`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 $t(`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 hhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function ghe(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 _he(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 vhe(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 yhe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof $t?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function bhe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=rhe(e.bind(globalThis),t,xhe)}function xhe(){let e=f();if(!e)return null;try{return new URL(e).origin}catch{return null}}function She(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 Che=she(e=>Ehe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Che.handle(e.data)});function whe(e){let t=xa(e.pageBuildId,`6.72.0-mt2qv8w3`);return()=>{t&&dr(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.72.0-mt2qv8w3`)}}function The(e){bhe(),p(e.localApiBaseUrl??null),v(e.bridgeToken??null),UW(e.syncFsBridgeEnabled??!1),l(e.extensionDelegateId??null),She(e.localStorageSeed??{}),e.flagFloat&&la(e.flagFloat)}async function Ehe(e){va(e.instanceId);let t=whe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{The(e),pr().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=wa(e.kernelPort),a=new zg(r),o=zg.createCallbacks(a),c=new Ta(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Bi(c);Y9=await ehe({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-14cdGa6x.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(Ki(i));let m=await Ohe({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){Dhe(e.kernelPort,t)}}function Dhe(e,t){ba(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 Ohe(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=fhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=phe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await khe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function khe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-Cbtek1FE.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-SaPIFvTd.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-Cf4bBarA.js`).then(e=>e.a),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())});
|