sliccy 6.74.0 → 6.74.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/.vite/manifest.json +117 -117
- package/dist/ui/assets/{account-store-DiqmjUAQ.js → account-store-Bs5wYmPH.js} +1 -1
- package/dist/ui/assets/{account-store-h1Ohm-av.js → account-store-DhXm-hp2.js} +1 -1
- package/dist/ui/assets/{adobe-uR-oWaeY.js → adobe-BY6VkVG7.js} +1 -1
- package/dist/ui/assets/{adobe-BhNCbU4l.js → adobe-ZJw2pWdU.js} +1 -1
- package/dist/ui/assets/{apply-layout-N2_kdM3F.js → apply-layout-Ceii10ec.js} +1 -1
- package/dist/ui/assets/{apps-UwhykMN9.js → apps-B3hWxSJa.js} +1 -1
- package/dist/ui/assets/{azure-openai-BoIQv7GR.js → azure-openai-6A7ULWsO.js} +1 -1
- package/dist/ui/assets/{azure-openai-BUfk-Cgc.js → azure-openai-DYx6GjSK.js} +1 -1
- package/dist/ui/assets/{cerebras-CVYo98dQ.js → cerebras-EP9KkiyX.js} +1 -1
- package/dist/ui/assets/{cerebras-C_3taxhb.js → cerebras-Tsgj47QL.js} +1 -1
- package/dist/ui/assets/{connect-surface-DC_Nbevf.js → connect-surface-CJASCNXx.js} +1 -1
- package/dist/ui/assets/{fs-Dhl2HmMs.js → fs-B9b0E2_f.js} +2 -2
- package/dist/ui/assets/{fs-BnlVy7cU.js → fs-DVnwglvE.js} +1 -1
- package/dist/ui/assets/{github-B0ahyeqT.js → github-DjPj9qkm.js} +1 -1
- package/dist/ui/assets/{github-CQVGT4sz.js → github-Dm6bGUQw.js} +2 -2
- package/dist/ui/assets/{github-copilot-CtNGfYrB.js → github-copilot-BwNKa1YA.js} +1 -1
- package/dist/ui/assets/{github-copilot-CEHSRXMz.js → github-copilot-Clu3Ah3c.js} +1 -1
- package/dist/ui/assets/{github-install-k7zKoFOC.js → github-install-BU__F4cn.js} +1 -1
- package/dist/ui/assets/{github-zip-Ba-hMXLa.js → github-zip-Bg2XmI3w.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-BSRq1C5L.js → js-realm-worker-D9dufpct.js} +1 -1
- package/dist/ui/assets/{kernel-worker-DO1h6rMZ.js → kernel-worker-BeQsXS7Z.js} +26 -26
- package/dist/ui/assets/{local-llm-CDrXotz7.js → local-llm-46v21F6v.js} +1 -1
- package/dist/ui/assets/{local-llm-VPd8AciJ.js → local-llm-4eumet6V.js} +1 -1
- package/dist/ui/assets/{main-Bpt82Io_.js → main-Cc_Ew7tx.js} +3 -3
- package/dist/ui/assets/{mount-CW4BzRt2.js → mount-B5EPyAiB.js} +1 -1
- package/dist/ui/assets/{mount-BgMlcZ8d.js → mount-DlhGjFpz.js} +2 -2
- package/dist/ui/assets/{mount-recovery-CFJCVOxF.js → mount-recovery-B6xgXgIN.js} +1 -1
- package/dist/ui/assets/{new-session-BW7LIyke.js → new-session-ICgxt805.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DjovZ3p_.js → oauth-bootstrap-36Ol1qSd.js} +2 -2
- package/dist/ui/assets/{openai-codex-YSS7XGKx.js → openai-codex-B4yjYiyu.js} +1 -1
- package/dist/ui/assets/{openai-codex-Yqmpz6Ha.js → openai-codex-Cl-TQRio.js} +1 -1
- package/dist/ui/assets/{openrouter-B3VxdBJ4.js → openrouter-DEc7uQ6U.js} +1 -1
- package/dist/ui/assets/{openrouter-BFjtjG7V.js → openrouter-DxCfhknQ.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-DAJwXxBz.js → openrouter-oauth-Cn0pR8xA.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-ClD2fqDF.js → openrouter-oauth-F7U_v5W7.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-8RPxfTbG.js → panel-rpc-handlers-Kg81C_dG.js} +2 -2
- package/dist/ui/assets/{provider-D4Ceq2V3.js → provider-B30Ksfaf.js} +2 -2
- package/dist/ui/assets/{provider-Du1J9V93.js → provider-Dp6zI7eY.js} +1 -1
- package/dist/ui/assets/{provider-settings-E56tpMqq.js → provider-settings-BjjWqkj0.js} +1 -1
- package/dist/ui/assets/{provider-settings-B13WCvOh.js → provider-settings-C5pzMk-0.js} +1 -1
- package/dist/ui/assets/{provider-store-access-YSsrVtLZ.js → provider-store-access-DkhPM-2g.js} +2 -2
- package/dist/ui/assets/provider-store-access-XCgBUiZn.js +1 -0
- package/dist/ui/assets/{providers-CS7ugxJ9.js → providers-BrDyUzyA.js} +2 -2
- package/dist/ui/assets/{providers-_0kW270e.js → providers-pB7s55hk.js} +1 -1
- package/dist/ui/assets/{quick-llm-DAgNey2j.js → quick-llm-CQWlRmAB.js} +1 -1
- package/dist/ui/assets/{recovery-screen-CBF_sy3T.js → recovery-screen-uzNaac2n.js} +1 -1
- package/dist/ui/assets/{redirect-uri-DwSs4f1-.js → redirect-uri-BbDAhEn_.js} +1 -1
- package/dist/ui/assets/{session-freezer-D2YzYSSc.js → session-freezer-DFRTF4GP.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-D90B-6L9.js → setup-feature-flags-remote-xYY2KoRd.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-CJNRiYaS.js → setup-standalone-prelude-yxWF4qBw.js} +1 -1
- package/dist/ui/assets/{setup-sudo-DY04SBHW.js → setup-sudo-B2sKjBny.js} +2 -2
- package/dist/ui/assets/{skills-BZxv_9u8.js → skills-8NiwYZ4d.js} +1 -1
- package/dist/ui/assets/slicc-version-D3muNOTC.js +1 -0
- package/dist/ui/assets/{store-Dz1s40ln.js → store-DbHU-U7R.js} +1 -1
- package/dist/ui/assets/{store-Brv1Ot8F.js → store-DiFedg2r.js} +1 -1
- package/dist/ui/assets/{sudo-SvdrfHTS.js → sudo-BpgGkYVu.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-Cx0NleIo.js → upgrade-detection-CrtIw3_B.js} +1 -1
- package/dist/ui/assets/{wc-extension-BwhQoAnq.js → wc-extension-CSapnTcp.js} +2 -2
- package/dist/ui/assets/{wc-follower-9BD2N_56.js → wc-follower-CbxYM2hr.js} +3 -3
- package/dist/ui/assets/{wc-live-9oCwAy_6.js → wc-live-BcwQzHWX.js} +4 -4
- package/dist/ui/assets/{wc-nav-Cpk1g3uX.js → wc-nav-DA5n1AdF.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-MiHEi8Ay.js → wc-onboarding-D-SyzUOU.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-CA5JaWnW.js → wc-placeholder-Daucr5kB.js} +2 -2
- package/dist/ui/assets/{wc-settings-DrfXLyeG.js → wc-settings-ylQZwBuJ.js} +2 -2
- package/dist/ui/assets/{wc-shell-B4GlooOU.js → wc-shell-DDuip0n8.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-DsSwKt9i.js → wc-sprinkles-J1ztSjiF.js} +2 -2
- package/dist/ui/assets/{wc-tray-qU2Brxre.js → wc-tray-BFo9Iac7.js} +2 -2
- package/dist/ui/assets/{xai-grok-CFOHqvES.js → xai-grok-CNQFCjQM.js} +1 -1
- package/dist/ui/assets/{xai-grok-ix17AsTo.js → xai-grok-DKl8JIC2.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-B7Iq20KZ.js +0 -1
- package/dist/ui/assets/slicc-version-TJDyM1y0.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import"./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-_0kW270e.js";import{a as l,c as u,d,f,i as p,l as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-CWqWgyRG.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 eee,dn as Ge,dt as Ke,en as qe,et as Je,fn as B,ft as Ye,gn as Xe,gt as Ze,h as tee,hn as Qe,ht as $e,in as et,it as tt,jn as nt,jt as rt,kn as it,kt as at,ln as ot,lt as st,m as ct,mn as lt,mt as ut,nn as dt,nt as ft,on as pt,ot as nee,pn as mt,pt as ht,qt as gt,rn as _t,rt as vt,sn as yt,st as bt,tn as xt,tt as St,un as Ct,ut as wt,vn as V,vt as Tt,w as Et,wn as Dt,wt as Ot,xn as kt,xt as At,yn as jt,yt as Mt,zt as Nt}from"./account-store-DiqmjUAQ.js";import{t as Pt}from"./runtime-env-DadgceZk.js";import{r as Ft}from"./binary-cache-bSOhqXB1.js";import{n as It,r as Lt,t as Rt}from"./fetch-body-DDu_AU5I.js";import{a as zt,i as Bt,n as Vt,t as Ht}from"./path-utils-DNJG-zQf.js";import{d as Ut}from"./transform-messages-DEFauvrq.js";import{l as Wt,m as Gt}from"./bedrock-camp-BfNg24Ce.js";import{t as Kt}from"./__vite-browser-external-5eBdwsFd.js";import{n as qt,t as Jt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Yt}from"./image-markers-CdcIBWOf.js";import{a as Xt,i as Zt,r as Qt}from"./tool-ui-DRnUkp2g.js";import{a as $t,i as en,o as tn,r as nn,t as rn}from"./agent-message-to-chat-ChAiEgvC.js";import{a as an,i as on,n as sn,o as cn,r as ln,t as un}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as dn}from"./types-idfTVsM8.js";import{a as fn,i as pn,n as mn,o as hn,r as gn,s as ree}from"./mount-CW4BzRt2.js";import{o as _n}from"./mount-table-store-DrF_Ifaz.js";import{t as vn}from"./remote-cache-JAv9sQH_.js";import{r as yn,t as iee}from"./mount-recovery-CFJCVOxF.js";import{a as bn,c as xn,i as Sn,n as Cn,o as wn,r as Tn,s as En}from"./lick-urls-DEfVsxzt.js";import{C as Dn,D as On,E as kn,S as An,_ as jn,a as Mn,b as Nn,d as Pn,g as Fn,h as In,m as Ln,n as Rn,o as zn,r as Bn,s as Vn,t as Hn,u as Un,w as Wn,y as Gn}from"./db-BTiVtoD4.js";import{a as Kn,i as qn,n as Jn,r as Yn}from"./tray-runtime-config-BoItLnrD.js";import{n as Xn,r as Zn,t as Qn}from"./slicc-version-TJDyM1y0.js";import{a as $n,c as er,d as tr,i as nr,l as rr,n as ir,o as ar,s as or,t as sr,u as cr}from"./lick-manager-BpI2wI9M.js";import{a as lr,n as ur,r as dr}from"./fs-BnlVy7cU.js";import{a as fr,c as pr,i as mr,l as hr,n as gr,o as H,r as _r,s as vr}from"./cost-command-AOg9dLn6.js";import{_ as yr,a as br,b as xr,c as Sr,d as Cr,f as wr,g as Tr,h as aee,i as oee,l as Er,m as Dr,n as see,o as cee,p as lee,r as Or,s as uee,u as dee,v as fee,y as kr}from"./skills-BZxv_9u8.js";import{n as pee,t as mee}from"./llm-session-id-ZObKEXzb.js";import{n as hee,r as gee}from"./frozen-archive-format--7sONywg.js";import{i as _ee,r as vee}from"./browser-BAL8RehA.js";import{a as Ar,i as jr,n as Mr,r as Nr,t as Pr}from"./telemetry-BugxTkxX.js";import{n as Fr,t as Ir}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Lr,i as Rr,r as zr,t as Br}from"./git-config-DA8M5e8O.js";import{a as Vr,c as Hr,i as Ur,o as Wr,r as Gr,s as Kr,t as qr}from"./script-catalog-Bt94D0RP.js";import{t as Jr}from"./process-manager-unCzdHp3.js";import{A as Yr,C as Xr,O as Zr,_ as Qr,a as $r,b as ei,c as ti,d as ni,f as ri,g as ii,h as ai,i as oi,k as si,l as ci,m as li,n as ui,o as di,p as fi,r as pi,s as mi,t as hi,u as gi,v as _i,x as vi,y as yi}from"./shared-DqziuFis.js";import{n as bi,t as xi}from"./esbuild-wasm-C_e51T2J.js";import{n as Si,t as Ci}from"./wasm-compiler-Ct7QZURL.js";import{_ as wi,a as Ti,c as Ei,f as Di,g as Oi,h as ki,l as Ai,m as ji,n as Mi,p as Ni,r as Pi,u as Fi,v as Ii,y as Li}from"./github-zip-Ba-hMXLa.js";import{a as Ri,c as zi,d as Bi,f as Vi,i as Hi,l as Ui,n as Wi,o as Gi,p as Ki,r as qi,s as Ji,u as Yi}from"./github-install-k7zKoFOC.js";import{n as Xi,t as Zi}from"./magick-wasm-DVJe3sB9.js";import{a as Qi,c as $i,i as ea,l as ta,n as na,o as ra,r as ia,s as aa,t as oa,u as sa}from"./installer-CyaKvN2m.js";import{t as ca}from"./local-llm-CDrXotz7.js";import{t as la}from"./client-BGJKiXya.js";import{t as ua}from"./redirect-uri-DwSs4f1-.js";var da=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 fa(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 pa=r(`cdp`);var ma=class{ws=null;nextId=1;_superseded=!1;pending=new da;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,pa.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(pa.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(),pa.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),pa.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 fa(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;pa.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(pa.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;pa.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,pa.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):pa.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 ha=r(`har-recorder`);var ga=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}`),ha.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=>{ha.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 _a(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ha.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 ha.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)),ha.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 ha.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 _a(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){ha.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ha.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const va=`(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-pB7s55hk.js";import{a as l,c as u,d,f,i as p,l as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-CWqWgyRG.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 eee,dn as Ge,dt as Ke,en as qe,et as Je,fn as B,ft as Ye,gn as Xe,gt as Ze,h as tee,hn as Qe,ht as $e,in as et,it as tt,jn as nt,jt as rt,kn as it,kt as at,ln as ot,lt as st,m as ct,mn as lt,mt as ut,nn as dt,nt as ft,on as pt,ot as nee,pn as mt,pt as ht,qt as gt,rn as _t,rt as vt,sn as yt,st as bt,tn as xt,tt as St,un as Ct,ut as wt,vn as V,vt as Tt,w as Et,wn as Dt,wt as Ot,xn as kt,xt as At,yn as jt,yt as Mt,zt as Nt}from"./account-store-Bs5wYmPH.js";import{t as Pt}from"./runtime-env-DadgceZk.js";import{r as Ft}from"./binary-cache-bSOhqXB1.js";import{n as It,r as Lt,t as Rt}from"./fetch-body-DDu_AU5I.js";import{a as zt,i as Bt,n as Vt,t as Ht}from"./path-utils-DNJG-zQf.js";import{d as Ut}from"./transform-messages-DEFauvrq.js";import{l as Wt,m as Gt}from"./bedrock-camp-BfNg24Ce.js";import{t as Kt}from"./__vite-browser-external-5eBdwsFd.js";import{n as qt,t as Jt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Yt}from"./image-markers-CdcIBWOf.js";import{a as Xt,i as Zt,r as Qt}from"./tool-ui-DRnUkp2g.js";import{a as $t,i as en,o as tn,r as nn,t as rn}from"./agent-message-to-chat-ChAiEgvC.js";import{a as an,i as on,n as sn,o as cn,r as ln,t as un}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as dn}from"./types-idfTVsM8.js";import{a as fn,i as pn,n as mn,o as hn,r as gn,s as ree}from"./mount-B5EPyAiB.js";import{o as _n}from"./mount-table-store-DrF_Ifaz.js";import{t as vn}from"./remote-cache-JAv9sQH_.js";import{r as yn,t as iee}from"./mount-recovery-B6xgXgIN.js";import{a as bn,c as xn,i as Sn,n as Cn,o as wn,r as Tn,s as En}from"./lick-urls-DEfVsxzt.js";import{C as Dn,D as On,E as kn,S as An,_ as jn,a as Mn,b as Nn,d as Pn,g as Fn,h as In,m as Ln,n as Rn,o as zn,r as Bn,s as Vn,t as Hn,u as Un,w as Wn,y as Gn}from"./db-BTiVtoD4.js";import{a as Kn,i as qn,n as Jn,r as Yn}from"./tray-runtime-config-BoItLnrD.js";import{n as Xn,r as Zn,t as Qn}from"./slicc-version-D3muNOTC.js";import{a as $n,c as er,d as tr,i as nr,l as rr,n as ir,o as ar,s as or,t as sr,u as cr}from"./lick-manager-BpI2wI9M.js";import{a as lr,n as ur,r as dr}from"./fs-DVnwglvE.js";import{a as fr,c as pr,i as mr,l as hr,n as gr,o as H,r as _r,s as vr}from"./cost-command-AOg9dLn6.js";import{_ as yr,a as br,b as xr,c as Sr,d as Cr,f as wr,g as Tr,h as aee,i as oee,l as Er,m as Dr,n as see,o as cee,p as lee,r as Or,s as uee,u as dee,v as fee,y as kr}from"./skills-8NiwYZ4d.js";import{n as pee,t as mee}from"./llm-session-id-ZObKEXzb.js";import{n as hee,r as gee}from"./frozen-archive-format--7sONywg.js";import{i as _ee,r as vee}from"./browser-BAL8RehA.js";import{a as Ar,i as jr,n as Mr,r as Nr,t as Pr}from"./telemetry-BugxTkxX.js";import{n as Fr,t as Ir}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Lr,i as Rr,r as zr,t as Br}from"./git-config-DA8M5e8O.js";import{a as Vr,c as Hr,i as Ur,o as Wr,r as Gr,s as Kr,t as qr}from"./script-catalog-Bt94D0RP.js";import{t as Jr}from"./process-manager-unCzdHp3.js";import{A as Yr,C as Xr,O as Zr,_ as Qr,a as $r,b as ei,c as ti,d as ni,f as ri,g as ii,h as ai,i as oi,k as si,l as ci,m as li,n as ui,o as di,p as fi,r as pi,s as mi,t as hi,u as gi,v as _i,x as vi,y as yi}from"./shared-DqziuFis.js";import{n as bi,t as xi}from"./esbuild-wasm-C_e51T2J.js";import{n as Si,t as Ci}from"./wasm-compiler-Ct7QZURL.js";import{_ as wi,a as Ti,c as Ei,f as Di,g as Oi,h as ki,l as Ai,m as ji,n as Mi,p as Ni,r as Pi,u as Fi,v as Ii,y as Li}from"./github-zip-Bg2XmI3w.js";import{a as Ri,c as zi,d as Bi,f as Vi,i as Hi,l as Ui,n as Wi,o as Gi,p as Ki,r as qi,s as Ji,u as Yi}from"./github-install-BU__F4cn.js";import{n as Xi,t as Zi}from"./magick-wasm-DVJe3sB9.js";import{a as Qi,c as $i,i as ea,l as ta,n as na,o as ra,r as ia,s as aa,t as oa,u as sa}from"./installer-CyaKvN2m.js";import{t as ca}from"./local-llm-46v21F6v.js";import{t as la}from"./client-BGJKiXya.js";import{t as ua}from"./redirect-uri-BbDAhEn_.js";var da=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 fa(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 pa=r(`cdp`);var ma=class{ws=null;nextId=1;_superseded=!1;pending=new da;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,pa.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(pa.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(),pa.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),pa.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 fa(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;pa.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(pa.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;pa.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,pa.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):pa.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 ha=r(`har-recorder`);var ga=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}`),ha.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=>{ha.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 _a(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ha.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 ha.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)),ha.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 ha.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 _a(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){ha.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ha.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const va=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -888,7 +888,7 @@ import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}f
|
|
|
888
888
|
|
|
889
889
|
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function Eg(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Dg(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function Og(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function kg(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function Ag(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" to deny.`),{label:t,content:o.join(`
|
|
890
890
|
`)}}function jg(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
|
|
891
|
-
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Mg(e,t){let n=Cg(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ng(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Mg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Pg(e,t){let n=Mg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Fg(e){let t=Sg[e.type];return e.type===`session-reload`?wg(e,t):e.type===`upgrade`?Tg(e,t):e.type===`cherry`?Eg(e,t):e.type===`preview`?Dg(e,t):e.type===`workflow`?Og(e,t):e.type===`bash`?kg(e,t):e.type===`sudo-request`?Ag(e,t):e.type===`navigate`?Pg(e,t):e.type===`webhook`?Ng(e,t):e.type===`discovery`?jg(e,t):Mg(e,t)}const Ig=new Map;function Lg(e){let t=Ig.get(e.id);t&&(Ig.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Rg=r(`kernel-agent-event-stream`);var zg=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Rg.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${Bg()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Bg(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Vg=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Hg(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=n.find(e=>e.isCone);return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Hg(e){if(!e.config)return;let{modelId:t,thinkingLevel:n}=e.config;if(t!==void 0||n!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{thinkingLevel:n}}}let Ug={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Wg(){return{...Ug}}function Gg(){let e=Wg();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(En);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Kg=new Set;function qg(e){return Kg.add(e),()=>{Kg.delete(e)}}function Jg(){return Yg(bn(),Wg())}function Yg(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Xg=`__slicc_binary__`;function Zg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Xg]===`b64`&&typeof t.data==`string`}function Qg(e){if(e instanceof Uint8Array)return{[Xg]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(Qg);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Qg(r);return t}return e}function $g(e){if(Zg(e))return f(e.data);if(Array.isArray(e))return e.map($g);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=$g(r);return t}return e}const e_=r(`panel-transport`);function t_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function n_(){return{onMessage:e=>{let t=(t,n,r)=>(t_(t)&&e($g(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Qg(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||e_.error(`Offscreen → panel transport send failed`,{error:t})})}}}const r_=r(`kernel-bridge`);function i_(){return globalThis}function a_(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var o_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Vg;agentEventStream=new zg;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=n_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new _g;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${s_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r)=>{tn.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{tn.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=nn(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:s_(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=en(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:$t(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Jg())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Jg()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=a_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Fg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{r_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){r_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=this.orchestrator?.getSudoManager()??null;if(!r)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await r.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:c_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:c_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){r_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${s_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Lg(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear())}}async handleAgentSpawn(e){let t=i_()[Vh];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.scoopPresentation.clearStatus(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.agentEventStream.clear(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=i_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=i_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Zt.markMounted(t);return}try{await Zt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Zt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function s_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function c_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
891
|
+
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Mg(e,t){let n=Cg(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ng(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Mg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Pg(e,t){let n=Mg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Fg(e){let t=Sg[e.type];return e.type===`session-reload`?wg(e,t):e.type===`upgrade`?Tg(e,t):e.type===`cherry`?Eg(e,t):e.type===`preview`?Dg(e,t):e.type===`workflow`?Og(e,t):e.type===`bash`?kg(e,t):e.type===`sudo-request`?Ag(e,t):e.type===`navigate`?Pg(e,t):e.type===`webhook`?Ng(e,t):e.type===`discovery`?jg(e,t):Mg(e,t)}const Ig=new Map;function Lg(e){let t=Ig.get(e.id);t&&(Ig.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Rg=r(`kernel-agent-event-stream`);var zg=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Rg.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${Bg()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Bg(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Vg=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Hg(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=n.find(e=>e.isCone);return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Hg(e){if(!e.config)return;let{modelId:t,thinkingLevel:n}=e.config;if(t!==void 0||n!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{thinkingLevel:n}}}let Ug={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Wg(){return{...Ug}}function Gg(){let e=Wg();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(En);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Kg=new Set;function qg(e){return Kg.add(e),()=>{Kg.delete(e)}}function Jg(){return Yg(bn(),Wg())}function Yg(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Xg=`__slicc_binary__`;function Zg(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Xg]===`b64`&&typeof t.data==`string`}function Qg(e){if(e instanceof Uint8Array)return{[Xg]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(Qg);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Qg(r);return t}return e}function $g(e){if(Zg(e))return f(e.data);if(Array.isArray(e))return e.map($g);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=$g(r);return t}return e}const e_=r(`panel-transport`);function t_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function n_(){return{onMessage:e=>{let t=(t,n,r)=>(t_(t)&&e($g(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Qg(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||e_.error(`Offscreen → panel transport send failed`,{error:t})})}}}const r_=r(`kernel-bridge`);function i_(){return globalThis}function a_(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var o_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Vg;agentEventStream=new zg;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=n_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new _g;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${s_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r)=>{tn.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{tn.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=nn(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:s_(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=en(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:$t(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Jg())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Jg()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=a_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=Fg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{r_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t});return}}catch(e){r_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[]})}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=this.orchestrator?.getSudoManager()??null;if(!r)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await r.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:c_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:c_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){r_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${s_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Lg(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear())}}async handleAgentSpawn(e){let t=i_()[Vh];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.scoopPresentation.clearStatus(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.agentEventStream.clear(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=i_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=i_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Zt.markMounted(t);return}try{await Zt.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Zt.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function s_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function c_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
892
892
|
`)}const l_=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function u_(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(l_.map(e=>d_(i,e,t,r)))).filter(e=>e!==null)}async function d_(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!f_(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function f_(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}const p_=r(`navigation-watcher`);function m_(e,t){return or(e,t)}var h_=class{transport;onEvent;sessions=new Map;started=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;probedOrigins=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;t&&this.sessions.delete(t)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId)for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url))};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameNavigated=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n)return;let r=e.frame;r?.id&&(r.parentId||(n.rootFrameId=r.id,typeof r.url==`string`&&(n.url=r.url)))};onResponseReceived=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n||e.type!==`Document`)return;let r=e.frameId;if(!r||r!==n.rootFrameId)return;let i=e.response;if(!i)return;let a=typeof i.url==`string`&&i.url.length>0?i.url:n.url;if(!a)return;let{match:o,links:s}=m_(i.headers,a);if(o){let e={url:a,verb:o.verb,target:o.target,links:s,targetId:n.targetId};o.instruction!=null&&(e.instruction=o.instruction),o.branch!=null&&(e.branch=o.branch),o.path!=null&&(e.path=o.path),n.title!=null&&(e.title=n.title),this.onEvent(e)}this.maybeRunDiscovery(a,s,n.targetId)};constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=cr(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await u_(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){p_.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){this.transport.on(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.on(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.on(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.on(`Target.targetCreated`,this.onTargetCreated),this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.transport.on(`Network.responseReceived`,this.onResponseReceived);try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!0})}catch(e){p_.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived);return}this.started=!0;try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;if(!(e||typeof n!=`string`))try{await this.transport.send(`Target.attachToTarget`,{targetId:n,flatten:!0})}catch(e){p_.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){p_.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}}async stop(){if(this.started){this.started=!1,this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived),this.sessions.clear();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){p_.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;if(t?.type===`page`&&typeof t.targetId==`string`&&!t.attached)try{await this.transport.send(`Target.attachToTarget`,{targetId:t.targetId,flatten:!0})}catch(e){p_.debug(`Failed to attach to discovered target`,{targetId:t.targetId,error:e instanceof Error?e.message:String(e)})}}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!(!t||!n||n.type!==`page`||typeof n.targetId!=`string`)){this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,title:n.title,url:n.url});try{await this.transport.send(`Page.enable`,{},t),await this.transport.send(`Network.enable`,{},t);let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){p_.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};function g_(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var __=`# /etc/llmstxtignore — llms.txt discovery suppression
|
|
893
893
|
#
|
|
894
894
|
# One advertising hostname or glob per line. Matching is case-insensitive.
|
|
@@ -5425,7 +5425,7 @@ except BaseException:
|
|
|
5425
5425
|
`)}}function cz(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=uz(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:Yr},version:`v${Yr}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new az(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var lz=class extends pP.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 az){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 uz(e,t){return new lz(e,t)}function dz(e){if(e===``)return[];let t=e.split(`
|
|
5426
5426
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function fz(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function pz(e){return new TextDecoder(`utf-8`).decode(gN(e))}function mz(e){if(e&&typeof e.write==`function`)return e}var hz=class extends sP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=dz(pz(fz(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 az&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function gz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=mz(e.output)}else r=t,i=mz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new hz(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:hz,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var _z=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`?`: ${vz(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 vz(e){try{return JSON.stringify(e)}catch{return String(e)}}function yz(e){return new Promise(t=>setTimeout(t,e))}function bz(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 xz(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 Sz(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function Cz(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 wz(e){if(Sz(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 Tz(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 Ez(e){let t=e.sleep??yz;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=bz(n.baseUrl,o,s.params),l=xz(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=Tz(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 wz(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 wz(m).catch(()=>null);throw new _z(m.status,m.statusText,c,e)}let h=Cz(m.headers.get(`retry-after`)),g=500*2**a;await t(h===null?g:h)}if(f){let e=await wz(f).catch(()=>null);throw new _z(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 Dz(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 Oz(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`,Dz(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 kz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Oz(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 Az(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 jz(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:Az(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Mz(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:Az(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Az(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Az(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await jz(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Nz(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 Pz(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 Fz(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 Mz(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=Nz(c),d=Pz(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function Iz(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 Lz(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=Iz(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 Rz(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 zz(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 zz(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:Bz(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:Bz(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:Bz(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 Bz(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 Vz(e){return{findTab:t=>e.call(`browser`,`findTab`,[Uz(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,Wz(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Iz(t),Hz(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Iz(t),Hz(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Iz(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Iz(t),n]),fetch:(t,n,r={})=>Fz(n,r).then(n=>e.call(`browser`,`evalAsync`,[Iz(t),n])),websocket:Lz(e)}}function Hz(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 Uz(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 Wz(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function Gz(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function Kz(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:Gz(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function qz(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 Jz(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Yz(e){return e==null?[]:Array.isArray(e)?e:[e]}function Xz(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:Jz(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,qz(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,qz(r)]),receiveFeatureReport:async t=>Jz((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 Zz(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>Xz(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[Yz(t)]))[0];if(!n)throw Error(`No device selected.`);return Xz(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 $z=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 };`)}},eB=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 $z(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 $z(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?.())}},tB=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 eB(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()}},nB=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 eB(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 tB(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 rB(e){let t=async t=>new nB(e),n=async(t,n)=>new nB(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const iB=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`]),aB={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 oB(e,t){let n=aB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function sB(e){return{...e,time:rz,fmt:qN,pool:$R}}function cB(e,t){return e?.startsWith(`/`)?iz(e):t}function lB(e){return e.includes(`require`)||e.includes(`import`)}async function uB(e,t,n,r){return lB(t)?e.call(`module`,`buildGraph`,[t,cB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function dB(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 fB(e){return{playwright:rB(e)}}function pB(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:gB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=mB(t,n,r,i,c);if(a.hit)return a;if(iB.has(t))throw oB(e,t);if(si.has(t))throw vB(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]):hB(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=iz(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`&&dB(o.exports),o.exports}return{require:e=>p(t.entryMap,e)}}function mB(e,t,n,r,i){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:fF}:e===`crypto`?{hit:!0,value:eF}: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:aP}:e===`assert/strict`?{hit:!0,value:iP}:e===`util`?{hit:!0,value:kP}:e===`events`?{hit:!0,value:cP}:e===`os`?{hit:!0,value:tF}:e===`tty`?{hit:!0,value:pF}:e===`stream`?{hit:!0,value:pP}:e===`url`?{hit:!0,value:gF}:e===`zlib`?{hit:!0,value:XR}:e===`readline`&&i?{hit:!0,value:i}:e===`readline/promises`&&i?{hit:!0,value:i.promises}:{hit:!1}}function hB(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 gB(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 _B={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function vB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${_B[t]||``}`)}async function yB(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";
|
|
5427
5427
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof az?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function bB(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?qz(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,qz(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function xB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>bB(e,t)),request:async t=>bB(e,await e.call(`serial`,`request`,[Yz(t)]))}}function SB(e,t){let n=t.handle,r=e=>({status:e.status,data:Jz(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,qz(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,qz(r)])}}function CB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>SB(e,t)),request:async t=>SB(e,await e.call(`usb`,`request`,[Yz(t)]))}}function wB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function TB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function EB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function DB(e){let t=wB(e.argv[1]??``),n=EB(t,`references`),r=EB(t,`assets`),i=EB(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)+`
|
|
5428
|
-
`),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 ${TB(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 OB=new Map,kB=new Map;function AB(e){let t=crypto.randomUUID();return OB.set(t,e),t}function jB(e){return OB.get(e)??null}function MB(e,t){if(!OB.has(e))return t.abort(),()=>{};let n=kB.get(e);return n||(n=new Set,kB.set(e,n)),n.add(t),()=>{let n=kB.get(e);n&&(n.delete(t),n.size===0&&kB.delete(e))}}function NB(e){OB.delete(e);let t=kB.get(e);if(t){kB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function PB(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 FB(e){let t=jB(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 PB(e)}}function IB(e){return`slicc-sync-fs-`+e}const LB=`sync-fs-ack`,RB=`sync-fs-res`,zB=6e5,BB=5e3,VB=`exec`;function HB(e){return e.channel===VB}function UB(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 WB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,zB)}async function GB(e){let t=jB(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=UB(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()},WB(e.timeoutMs,zB)),o=MB(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`}:PB(e)}finally{clearTimeout(a),o()}}function KB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function qB(e){let t=YB(e);if(XB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw KB(`EIO`,e.label);ZB(t,e.label)}function JB(e){let t=qB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw KB(`EIO`,e.label)}}function YB(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 KB(`EIO`,e.label)}return t}function XB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function ZB(e,t){throw KB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function QB(e){return(t,n,r)=>{let i=JB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:VB})),timeoutMs:n+BB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw KB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function $B(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 eV(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&&$B(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=WB(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 tV(e,t){return KB(e,`sync-fs bridge, '${t}'`)}function nV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function rV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:nV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return qB(r(`GET`,e))},writeFile(e,t){qB(r(`POST`,e,t))},stat(e){let t=JB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw tV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=JB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw tV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=JB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw tV(`EIO`,e);return t},exists(e){let t=JB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw tV(`EIO`,e);return t},mkdir(e){qB(r(`POST`,e,void 0,`mkdir`))},rm(e){qB(r(`POST`,e,void 0,`rm`))}}}const iV=new TextEncoder,aV=new TextDecoder;function oV(e){if(!e.ok)return{status:4,payload:iV.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:iV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function sV(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(aV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(aV.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 cV(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 lV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function uV(e,t,n={}){let{header:r,window:i}=cV(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 KB(`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 KB(`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 KB(`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 KB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return sV(f,d)}}}function dV(e,t){return KB(e,`sync-sab bridge, '${t}'`)}function fV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function pV(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 dV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw dV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw dV(`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(!fV(t))throw dV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!fV(t))throw dV(`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 dV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw dV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function mV(e){return(t,n,r)=>{let i=e.call({...t,channel:VB},n+BB,r);if(!i.ok)throw KB(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 KB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function hV(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 mN(r)}function gV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function _V(e,t){return t?pV(t):e.syncFsToken?rV(e.syncFsToken):void 0}function vV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return uV(e.syncSab,t)}function yV(e,t,n,r,i){let a=vV(e,t),o=_V(e,a);if(Object.assign(r,PN(n,e.cwd,o,i)),e.syncFsToken)return eV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:mV(a)}:{}})}function bV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Xn().version,writable:!1,enumerable:!1,configurable:!1})}function xV(e,t,n){let r=LN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:FN({writeStdout:t,writeStderr:n,exit:e=>{throw new az(e)},color:r})}}function SV(e,t,n){return{readStdinBytes:()=>gN(e.stdin??``),writeStdout:t,writeStderr:n}}function CV(e){return{usbBridge:CB(e),serialBridge:xB(e),hidBridge:Zz(e)}}async function wV(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=sz(i,a),s=cz(e,i,a),{colorApi:c,cliApi:l}=xV(!!e.env?.NO_COLOR,i,a),u=new TM(t),d=SV(e,i,a),f=ON(u,C,d),p=await hV(u,e.cwd,gV(e,a)),m=yV(e,t,p,f,d),h=Kz(u,p,e.cwd,a),g=kz(h,{cwd:e.cwd}),_=DB({argv:e.argv,fs:f,exec:h}),v=Vz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=CV(u),S=Ez({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 Rz(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=sB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=iz(T),D=await uB(u,e.code,e.cwd,T),O=pB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:RP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:fB(u),nodeReadline:gz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;bV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await yB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await TV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await EV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function TV(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 EV(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 DV(){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 OV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=DV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&wV(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 kV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=DV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&IM(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 AV=OV(),jV=kV();function MV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?PV():jV({kind:e,ctx:t}):typeof Worker<`u`?NV():AV({kind:e,ctx:t})}function NV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return FV(new Worker(new URL(`/assets/js-realm-worker-BSRq1C5L.js`,``+import.meta.url),{type:`module`}))}function PV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return FV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function FV(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 IV(){if(ri())return decodeURIComponent(ai(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function LV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function RV(e){return e instanceof Error?e.message:String(e)}function zV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function BV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:zV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function VV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:zV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const HV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,UV=/\bimport\s*\.\s*meta\b/g;function WV(e,t){let n=JSON.stringify(t);return e.replace(HV,n).replace(UV,`({ url: ${n} })`)}async function GV(e,t,n,r){let i=await e();return i.transpileModule(WV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function KV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>bi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>gi(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!ei(e))return e;let a=LV(t),o;try{return await BV(n,e,t,a)}catch(e){o=e}try{return await GV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${RV(o)}; typescript fallback: ${RV(e)}`)}}}function qV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>bi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>gi(t));return async({source:e,filename:t})=>{if(!ei(e)&&!yi(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?LV(t):void 0,o=i?t:`[eval].js`,s;try{return await VV(n,e,t,a)}catch(e){s=e}try{return await GV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${RV(s)}; typescript fallback: ${RV(e)}`)}}}function JV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5428
|
+
`),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 ${TB(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 OB=new Map,kB=new Map;function AB(e){let t=crypto.randomUUID();return OB.set(t,e),t}function jB(e){return OB.get(e)??null}function MB(e,t){if(!OB.has(e))return t.abort(),()=>{};let n=kB.get(e);return n||(n=new Set,kB.set(e,n)),n.add(t),()=>{let n=kB.get(e);n&&(n.delete(t),n.size===0&&kB.delete(e))}}function NB(e){OB.delete(e);let t=kB.get(e);if(t){kB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function PB(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 FB(e){let t=jB(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 PB(e)}}function IB(e){return`slicc-sync-fs-`+e}const LB=`sync-fs-ack`,RB=`sync-fs-res`,zB=6e5,BB=5e3,VB=`exec`;function HB(e){return e.channel===VB}function UB(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 WB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,zB)}async function GB(e){let t=jB(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=UB(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()},WB(e.timeoutMs,zB)),o=MB(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`}:PB(e)}finally{clearTimeout(a),o()}}function KB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function qB(e){let t=YB(e);if(XB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw KB(`EIO`,e.label);ZB(t,e.label)}function JB(e){let t=qB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw KB(`EIO`,e.label)}}function YB(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 KB(`EIO`,e.label)}return t}function XB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function ZB(e,t){throw KB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function QB(e){return(t,n,r)=>{let i=JB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:VB})),timeoutMs:n+BB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw KB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function $B(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 eV(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&&$B(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=WB(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 tV(e,t){return KB(e,`sync-fs bridge, '${t}'`)}function nV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function rV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:nV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return qB(r(`GET`,e))},writeFile(e,t){qB(r(`POST`,e,t))},stat(e){let t=JB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw tV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=JB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw tV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=JB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw tV(`EIO`,e);return t},exists(e){let t=JB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw tV(`EIO`,e);return t},mkdir(e){qB(r(`POST`,e,void 0,`mkdir`))},rm(e){qB(r(`POST`,e,void 0,`rm`))}}}const iV=new TextEncoder,aV=new TextDecoder;function oV(e){if(!e.ok)return{status:4,payload:iV.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:iV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function sV(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(aV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(aV.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 cV(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 lV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function uV(e,t,n={}){let{header:r,window:i}=cV(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 KB(`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 KB(`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 KB(`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 KB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return sV(f,d)}}}function dV(e,t){return KB(e,`sync-sab bridge, '${t}'`)}function fV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function pV(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 dV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw dV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw dV(`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(!fV(t))throw dV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!fV(t))throw dV(`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 dV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw dV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function mV(e){return(t,n,r)=>{let i=e.call({...t,channel:VB},n+BB,r);if(!i.ok)throw KB(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 KB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function hV(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 mN(r)}function gV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function _V(e,t){return t?pV(t):e.syncFsToken?rV(e.syncFsToken):void 0}function vV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return uV(e.syncSab,t)}function yV(e,t,n,r,i){let a=vV(e,t),o=_V(e,a);if(Object.assign(r,PN(n,e.cwd,o,i)),e.syncFsToken)return eV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:mV(a)}:{}})}function bV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Xn().version,writable:!1,enumerable:!1,configurable:!1})}function xV(e,t,n){let r=LN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:FN({writeStdout:t,writeStderr:n,exit:e=>{throw new az(e)},color:r})}}function SV(e,t,n){return{readStdinBytes:()=>gN(e.stdin??``),writeStdout:t,writeStderr:n}}function CV(e){return{usbBridge:CB(e),serialBridge:xB(e),hidBridge:Zz(e)}}async function wV(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=sz(i,a),s=cz(e,i,a),{colorApi:c,cliApi:l}=xV(!!e.env?.NO_COLOR,i,a),u=new TM(t),d=SV(e,i,a),f=ON(u,C,d),p=await hV(u,e.cwd,gV(e,a)),m=yV(e,t,p,f,d),h=Kz(u,p,e.cwd,a),g=kz(h,{cwd:e.cwd}),_=DB({argv:e.argv,fs:f,exec:h}),v=Vz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=CV(u),S=Ez({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 Rz(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=sB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=iz(T),D=await uB(u,e.code,e.cwd,T),O=pB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:RP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:fB(u),nodeReadline:gz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;bV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await yB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await TV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await EV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function TV(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 EV(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 DV(){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 OV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=DV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&wV(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 kV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=DV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&IM(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 AV=OV(),jV=kV();function MV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?PV():jV({kind:e,ctx:t}):typeof Worker<`u`?NV():AV({kind:e,ctx:t})}function NV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return FV(new Worker(new URL(`/assets/js-realm-worker-D9dufpct.js`,``+import.meta.url),{type:`module`}))}function PV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return FV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function FV(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 IV(){if(ri())return decodeURIComponent(ai(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function LV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function RV(e){return e instanceof Error?e.message:String(e)}function zV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function BV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:zV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function VV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:zV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const HV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,UV=/\bimport\s*\.\s*meta\b/g;function WV(e,t){let n=JSON.stringify(t);return e.replace(HV,n).replace(UV,`({ url: ${n} })`)}async function GV(e,t,n,r){let i=await e();return i.transpileModule(WV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function KV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>bi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>gi(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!ei(e))return e;let a=LV(t),o;try{return await BV(n,e,t,a)}catch(e){o=e}try{return await GV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${RV(o)}; typescript fallback: ${RV(e)}`)}}}function qV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>bi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>gi(t));return async({source:e,filename:t})=>{if(!ei(e)&&!yi(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?LV(t):void 0,o=i?t:`[eval].js`,s;try{return await VV(n,e,t,a)}catch(e){s=e}try{return await GV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${RV(s)}; typescript fallback: ${RV(e)}`)}}}function JV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5429
5429
|
`);return t===-1?``:e.slice(t+1)}function YV(e){return zt(e).dir}const XV=[`node`,`require`,`default`],ZV=[`node`,`import`,`default`],QV=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,$V=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,eH=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,tH=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,nH=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function rH(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function iH(e){let t=vi(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!rH(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(QV,`require`,`require`),r($V,`import`,`import`),r(eH,`import`,`import`),r(tH,`import`,`export`),r(nH,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function aH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=JV(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 oH(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??XV,s=e.importConditions??ZV,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 aH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=YV(e),p={};for(let{specifier:t,kind:i}of iH(n)){let n;try{n=await Xr(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 Xr(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 sH(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Zr.has(e)||iB.has(e))}async function cH(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 iH(t))if(sH(e))try{let t=await oH({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?ZV:XV,requireConditions:XV,importConditions:ZV});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&&(ei(t)||yi(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 lH(){return globalThis.navigator?.hid??null}function uH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function dH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&uH(e)===uH(t)&&!!e.productName}var fH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(dH(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 pH=null;function mH(){return pH||=new fH,pH}const hH=4194304;function gH(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 _H(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function vH(e){e.opened||await e.open()}function yH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${hH}-byte (4 MiB) v1 limit`)}function bH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function xH(e,t){return(await t.getDevices()).map(t=>gH(e.register(t),t))}async function SH(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>gH(e.register(t),t))}function CH(e,t){return gH(t,_H(e,t))}async function wH(e,t){await _H(e,t).open()}async function TH(e,t){await _H(e,t).close()}async function EH(e,t,n,r){yH(r.byteLength,`send report payload`);let i=_H(e,t);await vH(i),await i.sendReport(n,r)}async function DH(e,t,n,r){yH(r.byteLength,`send feature report payload`);let i=_H(e,t);await vH(i),await i.sendFeatureReport(n,r)}async function OH(e,t,n){let r=_H(e,t);return await vH(r),{reportId:n,bytes:bH(await r.receiveFeatureReport(n))}}async function kH(e,t,n){let r=_H(e,t);await vH(r);let i=e=>{n({reportId:e.reportId,bytes:bH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const AH=6e4;function jH(){return on()}function MH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),AH);an(`hid-device`,e??[],void 0,{timeoutMs:AH}).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 NH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var PH=class{registry;constructor(e){this.registry=e}hid(){let e=lH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return xH(this.registry,this.hid())}async request(e){if(jH()){let t=await MH(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=>gH(this.registry.register(e),e))}return SH(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(CH(this.registry,e))}open(e){return wH(this.registry,e)}close(e){return TH(this.registry,e)}sendReport(e,t,n){return EH(this.registry,e,t,NH(n))}sendFeatureReport(e,t,n){return DH(this.registry,e,t,NH(n))}async receiveFeatureReport(e,t){let n=await OH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return kH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},FH=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:NH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:NH(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 IH(e,t){return e&&lH()?new PH(mH()):t?new FH(t):null}function LH(e){return async function(t,n){let r=t instanceof Request?t:null,i=RH(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=BH(r?.headers,n?.headers),s=await UH(n,r,a,o);s.defaultContentType&&!VH(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 RH(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function zH(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 BH(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=zH(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function VH(e,t){return HH(e,t)!==void 0}function HH(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function UH(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=KH(e.body,n);return{body:await WH(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=HH(r,`content-type`)??``,a=e&&(!i||!d(i));return{body:n.byteLength===0?void 0:a?qH(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function WH(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 qH(e);if(e instanceof ArrayBuffer)return qH(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return qH(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return qH(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 GH(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function KH(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!GH(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function qH(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 JH(){return globalThis.navigator?.serial??null}var YH=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 XH=null;function ZH(){return XH||=new YH,XH}const QH=4194304;function $H(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 eU(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function tU(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function nU(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 rU(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return $H(n,e.get(n))})}async function iU(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return $H(i,e.get(i))}function aU(e,t){return $H(t,eU(e,t))}async function oU(e,t,n){let r=eU(e,t);await r.port.open(n),r.opened=!0}async function sU(e,t){let n=eU(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 cU(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 lU(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 uU(e,t,n){let r=eU(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=nU(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=cU(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=tU(c,a.value);let e=u();if(e)return e}}return c}async function dU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${QH}-byte (4 MiB) v1 limit`);return await lU(eU(e,t)).write(n),n.length}async function fU(e,t){return eU(e,t).port.getSignals()}async function pU(e,t,n){await eU(e,t).port.setSignals(n)}const mU=6e4;function hU(){return on()}function gU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),mU);an(`serial-port`,e??[],void 0,{timeoutMs:mU}).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 _U(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var vU=class{registry;constructor(e){this.registry=e}serial(){let e=JH();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return rU(this.registry,this.serial())}async request(e){if(hU()){let t=await gU(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 $H(r,this.registry.get(r))}return iU(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(aU(this.registry,e))}open(e,t){return oU(this.registry,e,t)}close(e){return sU(this.registry,e)}read(e,t){return uU(this.registry,e,t)}write(e,t){return dU(this.registry,e,t)}getSignals(e){return fU(this.registry,e)}setSignals(e,t){return pU(this.registry,e,t)}},yU=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?_U(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:_U(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 bU(e,t){return e&&JH()?new vU(ZH()):t?new yU(t):null}function xU(){return globalThis.navigator?.usb??null}function SU(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var CU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(SU(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 wU=null;function TU(){return wU||=new CU,wU}const EU=4194304;function DU(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 OU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function kU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${EU}-byte (4 MiB) v1 limit`)}function AU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function jU(e,t){return(await t.getDevices()).map(t=>DU(e.register(t),t))}async function MU(e,t,n){let r=await t.requestDevice({filters:n});return DU(e.register(r),r)}function NU(e,t){return DU(t,OU(e,t))}async function PU(e,t){await OU(e,t).open()}async function FU(e,t){await OU(e,t).close()}async function IU(e,t,n){await OU(e,t).selectConfiguration(n)}async function LU(e,t,n){await OU(e,t).claimInterface(n)}async function RU(e,t,n){await OU(e,t).releaseInterface(n)}async function zU(e,t,n,r){kU(r,`control-in length`);let i=await OU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?AU(i.data):new ArrayBuffer(0)}}async function BU(e,t,n,r){kU(r.byteLength,`control-out payload`);let i=await OU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function VU(e,t,n,r){kU(r,`transfer-in length`);let i=await OU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?AU(i.data):new ArrayBuffer(0)}}async function HU(e,t,n,r){kU(r.byteLength,`transfer-out payload`);let i=await OU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function UU(e,t){await OU(e,t).reset()}const WU=6e4;function GU(){return on()}function KU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),WU);an(`usb-device`,e??[],void 0,{timeoutMs:WU}).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 qU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var JU=class{registry;constructor(e){this.registry=e}usb(){let e=xU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return jU(this.registry,this.usb())}async request(e){if(GU()){let t=await KU(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 DU(this.registry.register(n),n)}return MU(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(NU(this.registry,e))}open(e){return PU(this.registry,e)}close(e){return FU(this.registry,e)}selectConfig(e,t){return IU(this.registry,e,t)}claim(e,t){return LU(this.registry,e,t)}release(e,t){return RU(this.registry,e,t)}async controlIn(e,t,n){let r=await zU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return BU(this.registry,e,t,qU(n))}async transferIn(e,t,n){let r=await VU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return HU(this.registry,e,t,qU(n))}reset(e){return UU(this.registry,e)}},YU=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:qU(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:qU(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function XU(e,t){return e&&xU()?new JU(TU()):t?new YU(t):null}function ZU(e,t,n,r={}){let{header:i,window:a}=cV(t),o=new Map,s=!1,c=r.dispatch??(e=>HB(e)?GB(e):FB(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}=oV(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 $U(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?AB({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;eW(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?ZU(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&NB(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 eW(e,t,n,r,i,a){try{let o=await tW(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=WW(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 tW(e,t,n,r,i){switch(e.channel){case`vfs`:return sW(e.op,e.args,t);case`exec`:return bW(e.op,e.args,t,i);case`fetch`:return wW(e.op,e.args,t);case`browser`:return OW(e.op,e.args,nW(n),n);case`usb`:return VW(e.op,e.args,iW(n));case`serial`:return HW(e.op,e.args,aW(n));case`hid`:return UW(e.op,e.args,oW(n),r);case`module`:return EW(e.op,e.args,t);case`wasm`:return DW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function nW(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 rW(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 iW(e){if(e.usbBackend)return e.usbBackend;let t=XU(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function aW(e){if(e.serialBackend)return e.serialBackend;let t=bU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function oW(e){if(e.hidBackend)return e.hidBackend;let t=IH(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function sW(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 gW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await _W(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const cW=10485760;function lW(e){return e.fileCount>=500||e.totalBytes>=cW}function uW(e){return e.entries.length>=2e4}async function dW(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 fW(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 pW(e,t,n,r,i){if(n>1048576||lW(r)||r.totalBytes+n>cW){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 mW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function mW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await dW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function hW(e,t,n){if(uW(n))return;let r=[t];for(;r.length>0;){if(uW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await fW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await dW(e,t,r,n):a.isFile&&await pW(e,t,a.size,n,r)}}async function gW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await hW(e,t,n),t!==`/tmp`&&await hW(e,`/tmp`,n),{entries:n.entries}}async function _W(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 vW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),yW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function bW(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 SW(t,n,r);if(e===`kill`)return CW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function xW(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 SW(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??{};xW(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 CW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&vW.has(r)?r:`SIGTERM`;yW.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 wW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?LH(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 TW(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 EW(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=TW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return cH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:KV({ipk:s}),transpileEntry:qV({ipk:s})})}async function DW(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 Ci(e=>n.fs.readFileBuffer(e),i)}async function OW(e,t,n,r){switch(e){case`findTab`:return jW(n,t[0]??{});case`ensureTab`:{let e=t[0];return MW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return NW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return NW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return LW(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return RW(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await rW(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return rW(r).update(e,n)}case`wsClose`:{let e=t[0];return rW(r).close(e)}case`wsList`:return rW(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 IW(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function kW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function AW(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=kW()?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 jW(e,t){let n=await AW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=zW(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 MW(e,t,n){let r=await AW(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=BW(t);if(e){let t=r.find(t=>BW(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function NW(e,t,n,r){return e.withTab(t,async()=>PW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function PW(e){if(typeof e!=`string`)return e;let t=FW(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=FW(t);if(typeof e==`object`&&e)return e}return t}return e}function FW(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 IW(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(){
|
|
5430
5430
|
try {
|
|
5431
5431
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -5548,7 +5548,7 @@ Examples:
|
|
|
5548
5548
|
skill list
|
|
5549
5549
|
skill info bluebubbles
|
|
5550
5550
|
skill read bluebubbles
|
|
5551
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5551
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-8NiwYZ4d.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${VG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:UG(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5552
5552
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:WG(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
|
|
5553
5553
|
`,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+`
|
|
5554
5554
|
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const qG=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&er(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=>Hi(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=>rr(e),error:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters`,apply:(e,t)=>{e.path=t}}];function JG(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=qG.find(e=>e.names.includes(r));if(i){let r=e[++n];if(!r||!i.validate(r))return t.error=i.error,t;i.apply(t,r)}else if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--json`)t.json=!0;else if(r.startsWith(`-`))return t.error=`upskill: unknown option "${r}" for update`,t;else t.skills.push(r)}return t}function YG(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function XG(e,t){try{let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(String(n))}catch{return}}async function ZG(e,t,n,r){let i=await XG(e,t);return Ni(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?YG(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function QG(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await ZG(e,n,r,a);i.changes.push({path:r,status:o}),s&&i.writes.push({path:n,content:a})}let a=new Set(r.files??[]);for(let r of await ji(e,t)){if(n.has(r))continue;let e=a.has(r);i.changes.push({path:r,status:e?`removed`:`kept-local`}),e&&i.removals.push(`${t}/${r}`)}return i.changes.sort((e,t)=>e.path.localeCompare(t.path)),i}async function $G(e,t,n,r,i,a){let o={skill:n,source:`${r.kind}:${r.source}`,ref:i??r.ref,from:r.sha,outcome:`current`,changes:[]},[s,c]=r.source.split(`/`);if(!s||!c)return{...o,outcome:`error`,error:`unusable source "${r.source}"`};let l=(r.path??``).replace(/^\/|\/$/g,``),u=await Ai(t),d=await Vi(s,c,o.ref,u,!0);if(d&&r.sha===d&&await eK(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await tK(s,c,l,n,o.ref,t,u);if(`error`in f)return{...o,outcome:`error`,error:f.error};let p=f.files,m=f.path;if(p.size===0)return{...o,outcome:`error`,error:`no files at ${s}/${c}${m?`/${m}`:``} — the skill may have moved or been removed upstream`};let{changes:h,writes:g,removals:_}=await QG(e,`${Oi}/${n}`,p,r),v=g.length>0||_.length>0;if(a)return{...o,outcome:v?`updated`:`current`,changes:h};let y=d??r.sha;return v&&await oK(e,{changes:h,writes:g,removals:_}),await Ki(e,n,{...r,ref:o.ref,path:m,sha:y,files:[...p.keys()].sort()}),{...o,to:y,outcome:v?`updated`:`current`,changes:h}}async function eK(e,t,n){if(!n.files?.length)return!1;for(let r of n.files)if(!await e.exists(`/workspace/skills/${t}/${r}`))return!1;return!0}async function tK(e,t,n,r,i,a,o){let s=await Pi(e,t,a,i??`main`);if(s.status===`ok`){let i=Ti(s.files),a=n||nK(i,r);return a===null?{error:`could not find "${r}/SKILL.md" in ${e}/${t} — pass --path <dir> to say where the skill lives`}:{files:aK(i,a),path:a}}try{return{files:iK(rK(await Mi(e,t,n,i,o))),path:n}}catch(e){let t=e instanceof Error?e.message:String(e);return{error:`${s.message}; Contents API fallback failed: ${t}`}}}function nK(e,t){let n=[];for(let r of Object.keys(e))r===`SKILL.md`?n.push(``):(r.endsWith(`/${t}/SKILL.md`)||r===`${t}/SKILL.md`)&&n.push(r.slice(0,-9));return n.length===0?null:(n.sort((e,t)=>e.split(`/`).length-t.split(`/`).length||e.localeCompare(t)),n[0])}function rK(e){return new Map([...e].filter(([e])=>Ei(e)))}function iK(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function aK(e,t){let n=t?`${t}/`:``,r=new Map;for(let[t,i]of Object.entries(e)){if(!t.startsWith(n)||t.endsWith(`/`))continue;let e=t.slice(n.length);Ei(e)&&r.set(e,i)}return iK(r)}async function oK(e,t){for(let n of t.writes){let t=n.path.slice(0,n.path.lastIndexOf(`/`));await e.mkdir(t,{recursive:!0}),await e.writeFile(n.path,n.content)}for(let n of t.removals)await e.rm(n).catch(()=>{})}async function sK(e,t,n,r,i){let a={skill:n,source:`${r.kind}:${r.source}`,outcome:`current`,changes:[]},[o,s]=r.source.split(`/`);if(!o||!s)return{...a,outcome:`error`,error:`unusable source "${r.source}"`};let c=await zG(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${Oi}/${n}/SKILL.md`,u=await XG(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&LG(new TextDecoder().decode(u))===LG(c.content);if(YG(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${Oi}/${n}`,{recursive:!0}),await e.writeFile(l,d),await Ki(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function cK(e,t){if(e.outcome===`error`)return` ${e.skill}: failed — ${e.error}\n`;let n=new Map;for(let t of e.changes)n.set(t.status,(n.get(t.status)??0)+1);let r=e.to&&e.to!==e.from?` → ${e.to.slice(0,7)}`:``;if(e.outcome===`current`)return` ${e.skill}: already current (${e.source}${r})\n`;let i=t?`would update`:`updated`,a=` ${e.skill}: ${i} from ${e.source}${r}\n`;for(let t of e.changes)t.status!==`unchanged`&&(a+=` ${t.status.padEnd(10)} ${t.path}\n`);let o=n.get(`kept-local`)??0;return o>0&&(a+=` (${o} kept-local — dotfiles and local additions are never touched)\n`),a}function lK(e,t,n,r){let i=Hi(t);return i?{version:1,kind:`github`,source:`${i.owner}/${i.repo}`,skill:e,ref:r??i.branch,path:n??i.path,installed:new Date().toISOString()}:null}async function uK(e,t,n){if(t.length===0)return{targets:await Yi(e),missing:[]};let r=[],i=[];for(let a of t){let t=await Bi(e,a);if(t){r.push({name:a,provenance:t});continue}if(!await e.exists(`/workspace/skills/${a}`)){i.push({name:a,reason:`not-installed`});continue}let o=n.from?lK(a,n.from,n.path,n.branch):null;o?r.push({name:a,provenance:o}):i.push({name:a,reason:`no-provenance`})}return{targets:r,missing:i}}function dK(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -5582,7 +5582,7 @@ Nothing to update — all skills are current.
|
|
|
5582
5582
|
`,{stdout:s,stderr:``,exitCode:0}}function TK(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5583
5583
|
`,exitCode:1}:er(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
|
|
5584
5584
|
`,exitCode:1}}function EK(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`||!rr(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
|
|
5585
|
-
`,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=TK(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 DK(e){let t=await(await import(`./skills-
|
|
5585
|
+
`,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=TK(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 DK(e){let t=await(await import(`./skills-8NiwYZ4d.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${VG()}`,stderr:``,exitCode:0}:{stdout:UG(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function OK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-8NiwYZ4d.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 Bi(n,t),a=i?Ui(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:WG(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+`
|
|
5586
5586
|
`,stderr:``,exitCode:0}}async function kK(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 AK(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 Wi(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 jK(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await Wi(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 MK(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 NK(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await Ai(r),l=await qi(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:MK(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:MK(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 Pi(i,a,r,o);if(e.status===`ok`){let r=await Vi(i,a,o,c),s=await kK(u,i,a,Ti(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 AK(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await jK(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 zi()),{stdout:p,stderr:m,exitCode:+!!m}}async function PK(e,t,n,r){switch(e[0]){case`tabs`:return CK(t,n,r,e.includes(`--json`));case`recommendations`:return wK(t,n,e.includes(`--install`));case`update`:case`upgrade`:return pK(e.slice(1),t,n);case`list`:return DK(t);case`info`:case`read`:return OK(e[0],e[1],t);case`search`:return IK(e,n);default:return null}}function FK(e,t,n){return H(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return GG();let a=await PK(r,e,t,n);if(a)return a;let o=EK(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return GG();if(o.sourceRef.startsWith(`tessl:`))return LK(o.sourceRef,o.force,e,t);let s=PG(o.sourceRef);if(s)return BG(s.hostname,s.task,e,t,o.force);let c=Hi(o.sourceRef);return c?NK(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 IK(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?vK(a,t,i):GG()}async function LK(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5587
5587
|
`,exitCode:1};let a=await hK(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await Ai(r);return Wi(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function RK(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5588
5588
|
|
|
@@ -6985,7 +6985,7 @@ Common base URLs:
|
|
|
6985
6985
|
llama.cpp http://localhost:8080/v1
|
|
6986
6986
|
vLLM http://localhost:8000/v1
|
|
6987
6987
|
Jan http://localhost:1337/v1
|
|
6988
|
-
`}function Zie(){return H(e8,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Xie(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
6988
|
+
`}function Zie(){return H(e8,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Xie(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-C5pzMk-0.js`),{verifyConnection:a}=await import(`./local-llm-46v21F6v.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(e8);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6989
6989
|
`,exitCode:1};let c=await a(s,t(e8)??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(`
|
|
6990
6990
|
`)+`
|
|
6991
6991
|
`,exitCode:1}}if(o===`discover`){let e=n(e8)??``;return i(e8,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(`
|
|
@@ -7029,20 +7029,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
7029
7029
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
7030
7030
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
7031
7031
|
short name resolves on the PATH.
|
|
7032
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return i8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return i8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return i8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
7032
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return i8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return i8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return i8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-DiFedg2r.js`).then(e=>e.r);if(await a(i,t.fs))return i8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.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 iae(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>l8(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 Cae(i,t);let m=await f8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-Dp6zI7eY.js`);e({name:i,serverUrl:r,auth:u})}return r8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${n8}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
7033
7033
|
`)+`
|
|
7034
|
-
`)}async function iae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
7035
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
7034
|
+
`)}async function iae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r),c=await xae(r.oauthFetchImpl),l=r.oauthLauncher??await u8(),u=await i(e,n,c);t8.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await ua(),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 aae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return r8(`usage: mcp list
|
|
7035
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-Dp6zI7eY.js`);await n();let{listServers:r}=await import(`./store-DiFedg2r.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return r8("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 r8(a8(o))}function a8(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(`
|
|
7036
7036
|
`)+`
|
|
7037
7037
|
`}async function oae(e,t){if(IX(e))return r8(`usage: mcp search <query>
|
|
7038
7038
|
|
|
7039
7039
|
Case-insensitive substring search across the cached tools of every
|
|
7040
7040
|
registered MCP server. Matches tool name OR description and prints a
|
|
7041
7041
|
table of (server, tool, description, match-field) rows.
|
|
7042
|
-
`);if(e.length===0)return i8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
7043
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
7042
|
+
`);if(e.length===0)return i8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-Dp6zI7eY.js`);await i();let{listServers:a}=await import(`./store-DiFedg2r.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return r8("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 r8(`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,sae(e.description),e.match]);return r8(a8(l))}function sae(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function cae(e,t){if(e.length===0||IX(e))return e.length===0?i8(`mcp delete: expected <name>`):r8(`usage: mcp delete <name>
|
|
7043
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-Dp6zI7eY.js`);await r(n);let{deleteServer:a}=await import(`./store-DiFedg2r.js`).then(e=>e.r),o=await a(n,t.fs);await wae(n,t),await Tae(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){t8.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?i8(`mcp delete: no server, alias, or account found for "${n}"`):r8([`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(`
|
|
7044
7044
|
`)+`
|
|
7045
|
-
`)}async function lae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?i8(`mcp invoke: expected <name>`):r8(dae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
7045
|
+
`)}async function lae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?i8(`mcp invoke: expected <name>`):r8(dae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-Dp6zI7eY.js`);await i(n);let{getServer:a}=await import(`./store-DiFedg2r.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return i8(`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 r8(fae(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return i8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=uae(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return r8(pae(n,l));let p=mae(d,l.inputSchema);if(!p.ok)return i8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BGJKiXya.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>l8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=vae(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function uae(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=o8(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=o8(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 o8(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 dae(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
7046
7046
|
|
|
7047
7047
|
mcp invoke <name> List tools on <name>.
|
|
7048
7048
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -7072,7 +7072,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
7072
7072
|
|
|
7073
7073
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
7074
7074
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
7075
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
7075
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-Dp6zI7eY.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-DiFedg2r.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return i8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>l8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return i8(`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 f8(n,d,t);return r8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function bae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return r8(`usage: mcp auth <name> [--silent | --interactive]
|
|
7076
7076
|
|
|
7077
7077
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
7078
7078
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7084,7 +7084,7 @@ Options:
|
|
|
7084
7084
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7085
7085
|
directly. Use after revoking a refresh token or
|
|
7086
7086
|
when the AS no longer accepts the cached one.
|
|
7087
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return i8(`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 i8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7087
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return i8(`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 i8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-Dp6zI7eY.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-DiFedg2r.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return i8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return i8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return i8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-pB7s55hk.js`).then(e=>e.r),f=d(u);if(!f)return i8(`mcp auth: provider "${u}" is not registered`);if(a)return await c8(r,f,t);if(!f.onSilentRenew)return i?i8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await c8(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 i8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);t8.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?r8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?i8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await c8(r,f,t)}async function c8(e,t,n){if(!t.onOAuthLogin)return i8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await u8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?r8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):i8(`mcp auth: interactive login for "${e}" did not complete`)}async function l8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-pB7s55hk.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){t8.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function u8(){let{createOAuthLauncher:e}=await import(`./oauth-service-DNcIcWT8.js`);return e()}async function xae(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function d8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-DVnwglvE.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 Sae(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7088
7088
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7089
7089
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7090
7090
|
const escape = (s) => {
|
|
@@ -7098,7 +7098,7 @@ const r = await exec(cmd);
|
|
|
7098
7098
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7099
7099
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7100
7100
|
process.exit(r.exitCode || 0);
|
|
7101
|
-
`}async function Cae(e,t){let n=await d8(t.fs);await n.mkdir(n8,{recursive:!0}),await n.writeFile(`${n8}/${e}.jsh`,Sae(e)),t.scriptCatalog?.invalidateJsh()}async function wae(e,t){let n=await d8(t.fs),r=`${n8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){t8.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Tae(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
7101
|
+
`}async function Cae(e,t){let n=await d8(t.fs);await n.mkdir(n8,{recursive:!0}),await n.writeFile(`${n8}/${e}.jsh`,Sae(e)),t.scriptCatalog?.invalidateJsh()}async function wae(e,t){let n=await d8(t.fs),r=`${n8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){t8.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Tae(e,t){let{removeAppSprinkles:n}=await import(`./apps-B3hWxSJa.js`);await n(e,t.fs)}async function f8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-B3hWxSJa.js`);return(await r(e,t,n.fs)).length}catch(t){return t8.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function p8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function m8(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 Eae(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 Dae(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function Oae(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 kae(e){let t=[`total: ${m8(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(`${m8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${Eae(e)}`)}return`${t.join(`
|
|
7102
7102
|
`)}\n`}function Aae(e={}){return H(`meminfo`,async t=>{let n=Oae(t);if(`error`in n)return p8(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
7103
7103
|
|
|
7104
7104
|
Usage:
|
|
@@ -7124,7 +7124,7 @@ Options:
|
|
|
7124
7124
|
-h, --help Show this help message
|
|
7125
7125
|
`}function Pae(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function _8(e){return`$${e.toFixed(2)}`}const Fae=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Iae(e){let t=`${e.id} ${e.name??``}`;return!Fae.test(t)}function Lae(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 Rae(e){let t=new Map;for(let n of e){let e=Lae(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function zae(e,t,n,r,i){let a=i?Mae(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 Bae(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=`${_8(e.cost.input)} / ${_8(e.cost.output)}`,a=`${Pae(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(`
|
|
7126
7126
|
`)+`
|
|
7127
|
-
`}function Vae(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-
|
|
7127
|
+
`}function Vae(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-C5pzMk-0.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Nae(),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.
|
|
7128
7128
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await jae(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(Iae);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>zae(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=Rae(n)),w.push(...n),!l){let t=i(e);T.push(Bae(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7129
7129
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7130
7130
|
`);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(`
|
|
@@ -7164,7 +7164,7 @@ Examples:
|
|
|
7164
7164
|
oauth-domain add adobe '*.da.live'
|
|
7165
7165
|
oauth-domain list adobe
|
|
7166
7166
|
oauth-domain remove adobe admin.da.live
|
|
7167
|
-
`}function Zae(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:y8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
7167
|
+
`}function Zae(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:y8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-C5pzMk-0.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(`
|
|
7168
7168
|
`)+`
|
|
7169
7169
|
`,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)
|
|
7170
7170
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7236,7 +7236,7 @@ Examples:
|
|
|
7236
7236
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7237
7237
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7238
7238
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7239
|
-
`}function ioe(){return H(`oauth-token`,aoe)}async function aoe(e,t){let n=await import(`./account-store-
|
|
7239
|
+
`}function ioe(){return H(`oauth-token`,aoe)}async function aoe(e,t){let n=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r),r=await import(`./providers-pB7s55hk.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:roe(),stderr:``,exitCode:0};if(e.includes(`--list`))return Soe(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return hoe(e);if(e.includes(`--renew`))return goe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return _oe(e,t);let i=ooe(e);if(!i.ok)return i.result;let a=soe(e),o=coe(e,n,r);if(!o.ok)return o.result;let s=loe(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await uoe(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return doe(o.value,s.value,i.value,n.getOAuthAccountInfo)}function ooe(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:D8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function soe(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function coe(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:D8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(x8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>x8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:D8(`oauth-token: no OAuth providers configured`)}}function x8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function loe(e,t){let n=t(e);return n?x8(n)?{ok:!0,value:n}:{ok:!1,result:D8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:D8(`oauth-token: unknown provider "${e}"`)}}async function uoe(e,t,n,r){let i=n(e);return i&&!i.expired?S8(e,i,r):!i?.expired||!t.onSilentRenew||!await moe(t.onSilentRenew)?null:S8(e,n(e),r)}function S8(e,t,n){return n&&!noe(t?.scopes,n)?null:C8(e,t?.maskedValue)}function C8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:D8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function doe(e,t,n,r){try{let i=await foe(e,t,n);return i.error?i.error:poe(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),D8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),D8(`oauth-token: login failed: ${n}`))}}async function foe(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-DNcIcWT8.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:D8(`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-DNcIcWT8.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:D8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function poe(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),D8(`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?C8(e,r.maskedValue):r?.token?D8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),D8(`oauth-token: login completed but no token was saved`))}async function moe(e){try{return await e()!==null}catch{return!1}}function w8(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 hoe(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-pB7s55hk.js`).then(e=>e.r),o=w8(e,n,i,a);if(!o)return D8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return D8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return D8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return D8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return D8(`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 goe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-Bs5wYmPH.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-pB7s55hk.js`).then(e=>e.r),a=w8(e,t,r,i);if(!a)return D8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return D8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return D8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${T8(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: ${T8(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(`
|
|
7240
7240
|
`)+`
|
|
7241
7241
|
`,stderr:``,exitCode:+!u}}function T8(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 _oe(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-BIKnTjZm.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-DNcIcWT8.js`),i=await voe(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return D8(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return D8(`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}:D8(`oauth-token: intercept timed out or was cancelled`)}function voe(e,t){let n=e.indexOf(`--from-file`);return n>=0?yoe(e[n+1],t):boe(e)}async function yoe(e,t){if(!e)return{ok:!1,result:D8(`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:D8(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function boe(e){let t=E8(e,`--authorize-url`),n=E8(e,`--redirect-pattern`);if(!t)return{ok:!1,result:D8(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:D8(`oauth-token: --redirect-pattern is required`)};let r=xoe(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 xoe(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:D8(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:D8(`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 E8(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function D8(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function Soe(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7242
7242
|
`,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(`
|
|
@@ -7354,7 +7354,7 @@ Examples:
|
|
|
7354
7354
|
plugin list
|
|
7355
7355
|
plugin info my-plugin
|
|
7356
7356
|
plugin remove my-plugin
|
|
7357
|
-
`}function ese(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return U8($oe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await nse(i,a,e);case`list`:case`ls`:return await ose(i,e);case`info`:return await sse(i,e);case`validate`:return await cse(i,a,e);case`remove`:case`rm`:case`delete`:return await lse(i,e);default:return W8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return W8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function G8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
7357
|
+
`}function ese(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return U8($oe());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await nse(i,a,e);case`list`:case`ls`:return await ose(i,e);case`info`:return await sse(i,e);case`validate`:return await cse(i,a,e);case`remove`:case`rm`:case`delete`:return await lse(i,e);default:return W8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return W8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function G8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-DVnwglvE.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 K8(e,t,n){let r=use(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-BU__F4cn.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 tse(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function q8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${H8}/${t.map(tse).join(`--`)}`}async function J8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-Bg2XmI3w.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 Y8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function nse(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return U8(`usage: plugin install <path|repo>
|
|
7358
7358
|
|
|
7359
7359
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
7360
7360
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -7365,19 +7365,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
7365
7365
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
7366
7366
|
standard skills discovery, and each supported streamable-http MCP server
|
|
7367
7367
|
is registered in the MCP store as "<plugin>:<server>".
|
|
7368
|
-
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return W8(`plugin install: expected <path|repo>`);let i=await G8(n),a=await K8(r[0],t,i);if(a.kind===`error`)return W8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return W8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=q8(a.ref),s=a.ref.display;let e=await J8(a.ref,o,i,n.fetch);if(e)return W8(`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 Y8(i,o),W8(`plugin install: plugin at ${s??o} was rejected:\n${X8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
7368
|
+
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return W8(`plugin install: expected <path|repo>`);let i=await G8(n),a=await K8(r[0],t,i);if(a.kind===`error`)return W8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return W8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=q8(a.ref),s=a.ref.display;let e=await J8(a.ref,o,i,n.fetch);if(e)return W8(`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 Y8(i,o),W8(`plugin install: plugin at ${s??o} was rejected:\n${X8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-DbHU-U7R.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await Y8(i,o),W8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await ase(u,n),g=await ise(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),U8(rse(u,h,g,s??o,l.diagnostics))}function rse(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:`,X8(i)),c.join(`
|
|
7369
7369
|
`)+`
|
|
7370
|
-
`}async function ise(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-
|
|
7371
|
-
`);let{listInstalledPlugins:n}=await import(`./store-
|
|
7370
|
+
`}async function ise(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-DiFedg2r.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 ase(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-DiFedg2r.js`).then(e=>e.r),{McpClient:a}=await import(`./client-BGJKiXya.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 ose(e,t){if(e.includes(`--help`)||e.includes(`-h`))return U8(`usage: plugin list
|
|
7371
|
+
`);let{listInstalledPlugins:n}=await import(`./store-DbHU-U7R.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return U8("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 U8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
|
|
7372
7372
|
`)+`
|
|
7373
7373
|
`)}async function sse(e,t){if(e.length===0||IX(e))return e.length===0?W8(`plugin info: expected <name>`):U8(`usage: plugin info <name>
|
|
7374
|
-
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-
|
|
7374
|
+
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-DbHU-U7R.js`),i=await r(n,t.fs);if(!i)return W8(`plugin info: no installed plugin named "${n}"`);let a=await G8(t),{loadPluginFromDirectory:o}=await import(`./loader-sgPDMLWT.js`),s=await o(a,i.root);if(!s.ok)return W8(`plugin info: plugin at ${i.root} no longer loads:\n${X8(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:`,X8(s.diagnostics)),U8(u.join(`
|
|
7375
7375
|
`)+`
|
|
7376
7376
|
`)}async function cse(e,t,n){if(e.length===0||IX(e))return e.length===0?W8(`plugin validate: expected <path|repo>`):U8(`usage: plugin validate <path|repo>
|
|
7377
7377
|
`);let r=await G8(n),i=await K8(e[0],t,r);if(i.kind===`error`)return W8(`plugin validate: ${i.message}`);let a,o=null;if(i.kind===`github`){if(!n.fetch)return W8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);o=`/tmp/.plugin-validate/${q8(i.ref).split(`/`).pop()}`;let e=await J8(i.ref,o,r,n.fetch);if(e)return W8(`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 Y8(r,o)}if(!c.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${X8(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:`,X8(c.diagnostics)),U8(d.join(`
|
|
7378
7378
|
`)+`
|
|
7379
7379
|
`)}async function lse(e,t){if(e.length===0||IX(e))return e.length===0?W8(`plugin remove: expected <name>`):U8(`usage: plugin remove <name>
|
|
7380
|
-
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-
|
|
7380
|
+
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-DbHU-U7R.js`),a=await r(n,t.fs);if(!a)return W8(`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-DiFedg2r.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(`${H8}/`);return s&&await Y8(await G8(t),a.root),U8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
|
|
7381
7381
|
`)+`
|
|
7382
7382
|
`)}function use(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 X8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
7383
7383
|
`)}const Z8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],dse=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],fse={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function pse(e={}){return H(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return Tse();let n=e.processManager??mse();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -9074,7 +9074,7 @@ ${e}
|
|
|
9074
9074
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
9075
9075
|
${t}
|
|
9076
9076
|
---`);let a=sx(n);return a&&(i+=a),i}};const P9=r(`scoop-lifecycle-manager`);var xme=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 dr))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 dr(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 bme(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||Ar(`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)),Ar(`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}),Ar(`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 Sme=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}`);Ar(`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=kn(Hn(Nn(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}: ${kh(e.content,e.attachments)}`).join(`
|
|
9077
|
-
`),l=s.flatMap(e=>Ah(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=kn(Hn(Nn(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 Cme=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new fx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new zx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Lx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new jx({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 Cx({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Ln(e),saveMessage:e=>An(e)});lickRegistry=new hx({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 Sme({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=>An(e),deleteMessage:e=>Mn(e),clearMessagesForScoop:e=>Bn(e),clearAllMessages:()=>Rn(),getMessagesSince:(e,t,n)=>In(e,t,n),setState:(e,t)=>On(e,t)},isExternalLickChannel:xg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new xme({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=>Dn(e),deleteScoop:e=>zn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>sr(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 Gn(),this.sharedFs=await yx(()=>ur.create({dbName:`slicc-fs`}),e),this.sessionStore=new Nh,this.fsWatcher=new lr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new mv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new D_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new vx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Un();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 Fn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new xx({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}`)}mr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=gv(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=>ir(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 ur.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await cx(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 mv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new D_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new vx(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 Ln(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(_r)]}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 _g,t=this.sharedFs;return new zy({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:rb(),snapshotStore:{read:e=>Xy(t,e),write:(e,n)=>Yy(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.74.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function wme(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)=>kme(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),Dme(t,n);let f=a(o.ctx,l),p=Ome(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`?Eme(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 Tme(e){let t=wme(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Eme(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Dme(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 Ome(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 kme(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Ame(n,t,a?.args??[],r):e===`agent`?jme(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Ame(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 jme(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 Mme=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 dn(`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 dn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new dn(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new dn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new dn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new dn(`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 dn(`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 dn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new dn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new dn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new dn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new dn(`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 dn(`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 Rme(t);let n=this.pm.get(e);switch(t){case`status`:return Nme(n);case`cmdline`:return Pme(n);case`cwd`:return Fme(n);case`stat`:return Ime(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 Nme(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Lme(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(`
|
|
9077
|
+
`),l=s.flatMap(e=>Ah(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=kn(Hn(Nn(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 Cme=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new fx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new zx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Lx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new jx({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 Cx({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Ln(e),saveMessage:e=>An(e)});lickRegistry=new hx({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 Sme({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=>An(e),deleteMessage:e=>Mn(e),clearMessagesForScoop:e=>Bn(e),clearAllMessages:()=>Rn(),getMessagesSince:(e,t,n)=>In(e,t,n),setState:(e,t)=>On(e,t)},isExternalLickChannel:xg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new xme({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=>Dn(e),deleteScoop:e=>zn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>sr(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 Gn(),this.sharedFs=await yx(()=>ur.create({dbName:`slicc-fs`}),e),this.sessionStore=new Nh,this.fsWatcher=new lr,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new mv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new D_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new vx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Un();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 Fn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new xx({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}`)}mr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=gv(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=>ir(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 ur.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await cx(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 mv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new D_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new vx(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 Ln(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(_r)]}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 _g,t=this.sharedFs;return new zy({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:rb(),snapshotStore:{read:e=>Xy(t,e),write:(e,n)=>Yy(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.74.1`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function wme(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)=>kme(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),Dme(t,n);let f=a(o.ctx,l),p=Ome(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`?Eme(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 Tme(e){let t=wme(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Eme(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Dme(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 Ome(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 kme(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Ame(n,t,a?.args??[],r):e===`agent`?jme(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Ame(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 jme(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 Mme=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 dn(`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 dn(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new dn(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new dn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new dn(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new dn(`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 dn(`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 dn(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new dn(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new dn(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new dn(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new dn(`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 dn(`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 Rme(t);let n=this.pm.get(e);switch(t){case`status`:return Nme(n);case`cmdline`:return Pme(n);case`cwd`:return Fme(n);case`stat`:return Ime(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 Nme(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Lme(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(`
|
|
9078
9078
|
`)+`
|
|
9079
9079
|
`}function Pme(e){return e.argv.join(`\0`)+`\0`}function Fme(e){return e.cwd+`
|
|
9080
9080
|
`}function Ime(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -9083,4 +9083,4 @@ ${t}
|
|
|
9083
9083
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
9084
9084
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
9085
9085
|
`}}function zme(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(IB(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(!jB(n.token))return;let a=i.get(n.id);if(a){r({type:LB,id:n.id}),a.result&&r({type:RB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:LB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:RB,id:n.id,...e})};(HB(n)?GB(n):FB(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 Bme(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 Vme(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 Hme(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Ume(e,t)}function Ume(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`&&!w_(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=Fg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=Bme(e),s=Vme(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 Wme(e,t,n,r,i){let a=new Jr,o=new Cme(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,W9().__slicc_browser=t,await n.bind(o,t);let s=wn(()=>n.emitTrayRuntimeStatus()),c=qg(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function Gme(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??Hme,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function Kme(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 qme(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Tme({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>eG(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>Z7().slice(10,22),splitResult:(e,t)=>Q7(e,t)})}async function Jme(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))+`
|
|
9086
|
-
`,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 Yme(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C5jpbwXT.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 Xme(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 h_(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})},Zme(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Zme(e){let t=y();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>g_()}}function Qme(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-CFJCVOxF.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 $me(){Zn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-Cx0NleIo.js`);return e()})}function ehe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Cx0NleIo.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 the(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 nhe(){return vt()}async function rhe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);$me();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Wme(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?ng(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Mme(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Gme(l,e,o);s(`lick-manager-ready`),f&&qme({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Jme({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;nhe()&&(g=await Yme(p,o,e.localLickWsUrl??null));let _=Xme(n,p,o);f&&Qme(f,p,o),a||await Kme(l),s(`cone-bootstrapped`),f&&ehe(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await the(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=zme({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 ihe({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 ihe(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)}ahe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function ahe(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[X7]}const G9=`x-bypass-llm-proxy`;function ohe(e,t,n){return t?(r,i)=>{if(!she(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 she(e,t,n){if(lhe(e,t))return!0;let r=n?.()??null;return r?che(e,r,t):!1}function che(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 lhe(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 uhe(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 dhe=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(!fhe(e)||e.source!==`panel`)return;let t=e.payload;phe(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 fhe(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 phe(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 mhe=class extends u9{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 hhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new dhe({transport:t,processManager:i,createShell:(a,o)=>new mhe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??vt,getLeaderStatus:e.webhook?.getLeaderStatus??Sn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function ghe(e){let t=new _he(e);return t.start(),{stop:()=>t.dispose()}}var _he=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(!vhe(e)||e.source!==`panel`)return;let t=e.payload;if(yhe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(bhe(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 dn(`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 dn(`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(xhe(e.type),e.requestId,new dn(`EACCES`,`vfs-rpc-host has no writable backend wired`),She(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 dn(`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 dn(`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 dn(`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 vhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function yhe(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 bhe(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 xhe(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 She(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof dn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Che(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ohe(e.bind(globalThis),t,whe)}function whe(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function The(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 Ehe=uhe(e=>khe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Ehe.handle(e.data)});function Dhe(e){let t=Tee(e.pageBuildId,`6.74.0-mt2xel67`);return()=>{t&&Mr(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.74.0-mt2xel67`)}}function Ohe(e){Che(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),JW(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),The(e.localStorageSeed??{}),e.flagFloat&&Ka(e.flagFloat)}async function khe(e){Cee(e.instanceId);let t=Dhe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Ohe(e),Pr().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Dee(e.kernelPort),a=new o_(r),o=o_.createCallbacks(a),c=new Oee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Ca(c);Y9=await rhe({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(ka(i));let m=await jhe({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){Ahe(e.kernelPort,t)}}function Ahe(e,t){wee(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 jhe(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=hhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=ghe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Mhe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Mhe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-tfN1ILpq.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|
|
9086
|
+
`,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 Yme(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C5jpbwXT.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 Xme(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 h_(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})},Zme(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Zme(e){let t=y();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>g_()}}function Qme(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-B6xgXgIN.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 $me(){Zn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-CrtIw3_B.js`);return e()})}function ehe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CrtIw3_B.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 the(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 nhe(){return vt()}async function rhe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);$me();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Wme(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?ng(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Mme(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Gme(l,e,o);s(`lick-manager-ready`),f&&qme({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Jme({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;nhe()&&(g=await Yme(p,o,e.localLickWsUrl??null));let _=Xme(n,p,o);f&&Qme(f,p,o),a||await Kme(l),s(`cone-bootstrapped`),f&&ehe(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await the(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=zme({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 ihe({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 ihe(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)}ahe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function ahe(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[X7]}const G9=`x-bypass-llm-proxy`;function ohe(e,t,n){return t?(r,i)=>{if(!she(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 she(e,t,n){if(lhe(e,t))return!0;let r=n?.()??null;return r?che(e,r,t):!1}function che(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 lhe(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 uhe(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 dhe=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(!fhe(e)||e.source!==`panel`)return;let t=e.payload;phe(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 fhe(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 phe(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 mhe=class extends u9{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 hhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new dhe({transport:t,processManager:i,createShell:(a,o)=>new mhe(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??vt,getLeaderStatus:e.webhook?.getLeaderStatus??Sn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function ghe(e){let t=new _he(e);return t.start(),{stop:()=>t.dispose()}}var _he=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(!vhe(e)||e.source!==`panel`)return;let t=e.payload;if(yhe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(bhe(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 dn(`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 dn(`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(xhe(e.type),e.requestId,new dn(`EACCES`,`vfs-rpc-host has no writable backend wired`),She(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 dn(`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 dn(`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 dn(`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 vhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function yhe(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 bhe(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 xhe(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 She(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof dn?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Che(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ohe(e.bind(globalThis),t,whe)}function whe(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function The(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 Ehe=uhe(e=>khe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Ehe.handle(e.data)});function Dhe(e){let t=Tee(e.pageBuildId,`6.74.1-mt2ylz1p`);return()=>{t&&Mr(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.74.1-mt2ylz1p`)}}function Ohe(e){Che(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),JW(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),The(e.localStorageSeed??{}),e.flagFloat&&Ka(e.flagFloat)}async function khe(e){Cee(e.instanceId);let t=Dhe(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Ohe(e),Pr().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Dee(e.kernelPort),a=new o_(r),o=o_.createCallbacks(a),c=new Oee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new Ca(c);Y9=await rhe({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(ka(i));let m=await jhe({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){Ahe(e.kernelPort,t)}}function Ahe(e,t){wee(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 jhe(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=hhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=ghe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Mhe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Mhe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-tfN1ILpq.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|