sliccy 6.78.8 → 6.79.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node-server/_shared/agent-wire-types.d.ts +11 -0
- package/dist/node-server/_shared/agent-wire-types.d.ts.map +1 -1
- package/dist/ui/.vite/manifest.json +117 -117
- package/dist/ui/assets/{account-store-DIDzpPfu.js → account-store-B92t9dbf.js} +1 -1
- package/dist/ui/assets/{account-store-CGg4IRNz.js → account-store-gfOTEDJm.js} +1 -1
- package/dist/ui/assets/{adobe-DTECrLVF.js → adobe-BfW87L1b.js} +1 -1
- package/dist/ui/assets/{adobe-B1EK_oO4.js → adobe-DJfO3x00.js} +1 -1
- package/dist/ui/assets/{apply-layout-UZb4u-Rg.js → apply-layout-D01Trc9l.js} +1 -1
- package/dist/ui/assets/{apps-DWjiZ0kF.js → apps-BwAyOelR.js} +1 -1
- package/dist/ui/assets/{azure-openai-DcrE1RM7.js → azure-openai-D9JsQfDX.js} +1 -1
- package/dist/ui/assets/{azure-openai-CboXxsBt.js → azure-openai-DY1XliXg.js} +1 -1
- package/dist/ui/assets/{cerebras-_RzwK58K.js → cerebras-L7at1trb.js} +1 -1
- package/dist/ui/assets/{cerebras-DGkQZhOd.js → cerebras-UDp8S0HF.js} +1 -1
- package/dist/ui/assets/{connect-surface-EIYkkN95.js → connect-surface-Cjf5vpE9.js} +1 -1
- package/dist/ui/assets/{fs-sM5DA1P8.js → fs-DRf2UNRP.js} +2 -2
- package/dist/ui/assets/{fs-BzNq8WOs.js → fs-QvKcM1y9.js} +1 -1
- package/dist/ui/assets/{github-copilot-Bc0lZD_Q.js → github-copilot-CAyblv29.js} +1 -1
- package/dist/ui/assets/{github-copilot-DY_Exgo7.js → github-copilot-DQUs_Cu6.js} +1 -1
- package/dist/ui/assets/{github-install-DMwWIT2K.js → github-install-CdvlpkjZ.js} +1 -1
- package/dist/ui/assets/{github-B-tNwtwp.js → github-oLuiXr5U.js} +2 -2
- package/dist/ui/assets/{github-CVN-aZvc.js → github-uJ20WoIV.js} +1 -1
- package/dist/ui/assets/{github-zip-DGBpuH4e.js → github-zip-DluIBUmq.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-BxobmOGu.js → js-realm-worker-BOYBWbOZ.js} +1 -1
- package/dist/ui/assets/{kernel-worker-BAAqC2yH.js → kernel-worker-DohhM8Ng.js} +30 -30
- package/dist/ui/assets/{local-llm-DD0rgmOS.js → local-llm-9n1b6XFh.js} +1 -1
- package/dist/ui/assets/{local-llm-Cq-sA5a1.js → local-llm-CL0LbvPc.js} +1 -1
- package/dist/ui/assets/{main-CjlfA6UW.js → main-CMu5nfXH.js} +3 -3
- package/dist/ui/assets/{mount-DbcfIsRM.js → mount-CA4MJmwU.js} +2 -2
- package/dist/ui/assets/{mount-Bj9sXHpb.js → mount-DKToD2O6.js} +1 -1
- package/dist/ui/assets/{mount-recovery-CEMrCBeT.js → mount-recovery-IeWjtnGl.js} +1 -1
- package/dist/ui/assets/{new-session-DOGFVyBv.js → new-session-CzhB-zHt.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DGuqAAFx.js → oauth-bootstrap-Gs5HX3e1.js} +2 -2
- package/dist/ui/assets/{openai-codex-BlB6wBiM.js → openai-codex-Bp9KZF_w.js} +1 -1
- package/dist/ui/assets/{openai-codex-fZK3192e.js → openai-codex-ChUFecwE.js} +1 -1
- package/dist/ui/assets/{openrouter-DsoUR7vM.js → openrouter-CRTavJY6.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BFbIoJgQ.js → openrouter-oauth-Bv2gMtnx.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-B7CfpZ-w.js → openrouter-oauth-Bwpl-0As.js} +1 -1
- package/dist/ui/assets/{openrouter-BoD15pzS.js → openrouter-w4AEwhMT.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-Dug4-Jzh.js → panel-rpc-handlers-CWU69FNj.js} +2 -2
- package/dist/ui/assets/{provider-PgQtZuIe.js → provider-CflcvITG.js} +1 -1
- package/dist/ui/assets/{provider-C7EGnRQK.js → provider-Vy5D4ebA.js} +2 -2
- package/dist/ui/assets/{provider-settings-Dn3J_lDH.js → provider-settings-DVze_FfU.js} +1 -1
- package/dist/ui/assets/{provider-settings-D_7BVY9G.js → provider-settings-_JNmYpT_.js} +1 -1
- package/dist/ui/assets/provider-store-access-DVFbKtR3.js +1 -0
- package/dist/ui/assets/{provider-store-access-CEUODTKR.js → provider-store-access-YJgLY0Aq.js} +2 -2
- package/dist/ui/assets/{providers-Dh5vkt52.js → providers-Bsz4jBpd.js} +2 -2
- package/dist/ui/assets/{providers-D1-3j_sk.js → providers-CDa657V5.js} +1 -1
- package/dist/ui/assets/{quick-llm-DtWlzqiU.js → quick-llm-CDgogXnj.js} +1 -1
- package/dist/ui/assets/{recovery-screen-FF84NyPW.js → recovery-screen-CfQxo-mg.js} +1 -1
- package/dist/ui/assets/{redirect-uri-CZZ6y3QA.js → redirect-uri-DHI820pd.js} +1 -1
- package/dist/ui/assets/{session-freezer-D7dmjlAQ.js → session-freezer-CCytzcyn.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-iCmkR7fI.js → setup-feature-flags-remote-Dy23J2lH.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-DaqQrwbD.js → setup-standalone-prelude-DevMxj0q.js} +1 -1
- package/dist/ui/assets/{setup-sudo-ClB3hKEc.js → setup-sudo-CSyUfKTX.js} +2 -2
- package/dist/ui/assets/{skills-BNGZSb7F.js → skills-CN522iKp.js} +1 -1
- package/dist/ui/assets/slicc-version-JE_x90rv.js +1 -0
- package/dist/ui/assets/{store-CYuCsDip.js → store-BcwDrsU-.js} +1 -1
- package/dist/ui/assets/{store-Cs_UC1hR.js → store-Cehy36To.js} +1 -1
- package/dist/ui/assets/{sudo-CUpHyb_t.js → sudo-CJVsuTSZ.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-yB5b3-05.js → upgrade-detection-CwBF5Q1G.js} +1 -1
- package/dist/ui/assets/{wc-extension-BYa0ltd6.js → wc-extension-W00zRwUc.js} +2 -2
- package/dist/ui/assets/{wc-follower-DV86yWfW.js → wc-follower-4Bh13i6U.js} +3 -3
- package/dist/ui/assets/wc-live-DG1YJfY_.js +41 -0
- package/dist/ui/assets/{wc-nav-TB44dMqh.js → wc-nav-C8hLrIbu.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-DtrxC7I5.js → wc-onboarding-ZWDIx9yo.js} +2 -2
- package/dist/ui/assets/{wc-placeholder--yMy4p9f.js → wc-placeholder-BiadsnDI.js} +2 -2
- package/dist/ui/assets/{wc-settings-DBjEAMdL.js → wc-settings-Dj1Dl_Ly.js} +2 -2
- package/dist/ui/assets/{wc-shell-CVQVZVtx.js → wc-shell-BQCj2id-.js} +3 -3
- package/dist/ui/assets/{wc-sprinkles-BNCDGEcf.js → wc-sprinkles-DK5pOUOJ.js} +2 -2
- package/dist/ui/assets/{wc-tray-nGzfHbqm.js → wc-tray-B0stpW0N.js} +2 -2
- package/dist/ui/assets/{xai-grok-B4fefNry.js → xai-grok-DXIjMbHs.js} +1 -1
- package/dist/ui/assets/{xai-grok-B21mYRT0.js → xai-grok-df20BMeq.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-l0LcqBXr.js +0 -1
- package/dist/ui/assets/slicc-version-Cf2HkeaS.js +0 -1
- package/dist/ui/assets/wc-live-CMtiIQDD.js +0 -41
|
@@ -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-D1-3j_sk.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-n2pCvcgW.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-DIDzpPfu.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 ree}from"./transform-messages-DEFauvrq.js";import{l as Ut,m as Wt}from"./bedrock-camp-B0KF_4RS.js";import{t as Gt}from"./__vite-browser-external-5eBdwsFd.js";import{n as Kt,t as qt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Jt}from"./image-markers-CdcIBWOf.js";import{a as Yt,i as Xt,r as Zt}from"./tool-ui-DRnUkp2g.js";import{a as Qt,i as $t,o as en,r as tn,t as nn}from"./agent-message-to-chat-ChAiEgvC.js";import{a as rn,i as an,n as on,o as sn,r as cn,t as ln}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as un}from"./types-idfTVsM8.js";import{a as dn,i as fn,n as pn,o as mn,r as hn,s as gn}from"./mount-Bj9sXHpb.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-CEMrCBeT.js";import{a as aee,c as oee,i as bn,n as see,o as cee,r as lee,s as xn}from"./lick-urls-AW0BSaf4.js";import{C as Sn,D as Cn,E as wn,S as Tn,_ as En,a as Dn,b as On,d as kn,g as An,h as jn,m as Mn,n as Nn,o as Pn,r as Fn,s as In,t as Ln,u as Rn,w as zn,y as Bn}from"./db-DATxPCUz.js";import{a as Vn,i as Hn,n as Un,r as Wn}from"./tray-runtime-config-B1LF8Kd4.js";import{n as Gn,r as Kn,t as qn}from"./slicc-version-Cf2HkeaS.js";import{a as Jn,c as Yn,d as Xn,i as Zn,l as Qn,n as $n,o as er,s as tr,t as nr,u as rr}from"./lick-manager-BJhAu_iX.js";import{a as ir,n as ar,r as or}from"./fs-BzNq8WOs.js";import{a as sr,c as cr,i as lr,l as ur,n as dr,o as H,r as fr,s as pr}from"./cost-command-Be2VSQE-.js";import{_ as mr,a as hr,b as gr,c as _r,d as vr,f as yr,g as br,h as xr,i as uee,l as Sr,m as Cr,n as dee,o as fee,p as pee,r as wr,s as mee,u as hee,v as gee,y as Tr}from"./skills-BNGZSb7F.js";import{n as _ee,t as vee}from"./llm-session-id-BZyXP_j2.js";import{n as yee,r as bee}from"./frozen-archive-format--7sONywg.js";import{i as xee,r as See}from"./browser-2rCVqcqy.js";import{a as Er,i as Dr,n as Cee,r as wee,t as Tee}from"./telemetry-BwapcULJ.js";import{n as Or,t as kr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Eee,i as Ar,r as jr,t as Mr}from"./git-config-DA8M5e8O.js";import{a as Nr,c as Pr,i as Fr,o as Ir,r as Lr,s as Rr,t as zr}from"./script-catalog-Bt94D0RP.js";import{t as Br}from"./process-manager-unCzdHp3.js";import{A as Vr,C as Hr,O as Ur,_ as Wr,a as Gr,b as Kr,c as qr,d as Jr,f as Yr,g as Xr,h as Zr,i as Qr,k as $r,l as ei,m as ti,n as ni,o as ri,p as ii,r as ai,s as oi,t as si,u as ci,v as li,x as ui,y as di}from"./shared-DqziuFis.js";import{n as fi,t as pi}from"./esbuild-wasm-C_e51T2J.js";import{n as mi,t as hi}from"./wasm-compiler-Ct7QZURL.js";import{_ as gi,a as _i,c as vi,f as yi,g as bi,h as xi,l as Si,m as Ci,n as wi,p as Ti,r as Ei,u as Di,v as Oi,y as ki}from"./github-zip-DGBpuH4e.js";import{a as Ai,c as ji,d as Mi,f as Ni,i as Pi,l as Fi,n as Ii,o as Li,p as Ri,r as zi,s as Bi,u as Vi}from"./github-install-DMwWIT2K.js";import{n as Hi,t as Ui}from"./magick-wasm-DVJe3sB9.js";import{a as Wi,c as Gi,i as Ki,l as qi,n as Ji,o as Yi,r as Xi,s as Zi,t as Qi,u as $i}from"./installer-DW4F27JY.js";import{t as ea}from"./local-llm-Cq-sA5a1.js";import{t as ta}from"./client-BTUV7dbh.js";import{t as na}from"./redirect-uri-CZZ6y3QA.js";var ra=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 ia(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 aa=r(`cdp`);var oa=class{ws=null;nextId=1;_superseded=!1;pending=new ra;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,aa.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(aa.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(),aa.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),aa.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 ia(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;aa.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(aa.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;aa.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,aa.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):aa.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 sa=r(`har-recorder`);var ca=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}`),sa.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=>{sa.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 la(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return sa.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 sa.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)),sa.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 sa.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 la(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){sa.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return sa.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ua=`(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-CDa657V5.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-n2pCvcgW.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-B92t9dbf.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 ree}from"./transform-messages-DEFauvrq.js";import{l as Ut,m as Wt}from"./bedrock-camp-B0KF_4RS.js";import{t as Gt}from"./__vite-browser-external-5eBdwsFd.js";import{n as Kt,t as qt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Jt}from"./image-markers-CdcIBWOf.js";import{a as Yt,i as Xt,r as Zt}from"./tool-ui-DRnUkp2g.js";import{a as Qt,i as $t,o as en,r as tn,t as nn}from"./agent-message-to-chat-ChAiEgvC.js";import{a as rn,i as an,n as on,o as sn,r as cn,t as ln}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as un}from"./types-idfTVsM8.js";import{a as dn,i as fn,n as pn,o as mn,r as hn,s as gn}from"./mount-DKToD2O6.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-IeWjtnGl.js";import{a as aee,c as oee,i as bn,n as see,o as cee,r as lee,s as xn}from"./lick-urls-AW0BSaf4.js";import{C as Sn,D as Cn,E as wn,S as Tn,_ as En,a as Dn,b as On,d as kn,g as An,h as jn,m as Mn,n as Nn,o as Pn,r as Fn,s as In,t as Ln,u as Rn,w as zn,y as Bn}from"./db-DATxPCUz.js";import{a as Vn,i as Hn,n as Un,r as Wn}from"./tray-runtime-config-B1LF8Kd4.js";import{n as Gn,r as Kn,t as qn}from"./slicc-version-JE_x90rv.js";import{a as Jn,c as Yn,d as Xn,i as Zn,l as Qn,n as $n,o as er,s as tr,t as nr,u as rr}from"./lick-manager-BJhAu_iX.js";import{a as ir,n as ar,r as or}from"./fs-QvKcM1y9.js";import{a as sr,c as cr,i as lr,l as ur,n as dr,o as H,r as fr,s as pr}from"./cost-command-Be2VSQE-.js";import{_ as mr,a as hr,b as gr,c as _r,d as vr,f as yr,g as br,h as xr,i as uee,l as Sr,m as Cr,n as dee,o as fee,p as pee,r as wr,s as mee,u as hee,v as gee,y as Tr}from"./skills-CN522iKp.js";import{n as _ee,t as vee}from"./llm-session-id-BZyXP_j2.js";import{n as yee,r as bee}from"./frozen-archive-format--7sONywg.js";import{i as xee,r as See}from"./browser-2rCVqcqy.js";import{a as Er,i as Dr,n as Cee,r as wee,t as Tee}from"./telemetry-BwapcULJ.js";import{n as Or,t as kr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Eee,i as Ar,r as jr,t as Mr}from"./git-config-DA8M5e8O.js";import{a as Nr,c as Pr,i as Fr,o as Ir,r as Lr,s as Rr,t as zr}from"./script-catalog-Bt94D0RP.js";import{t as Br}from"./process-manager-unCzdHp3.js";import{A as Vr,C as Hr,O as Ur,_ as Wr,a as Gr,b as Kr,c as qr,d as Jr,f as Yr,g as Xr,h as Zr,i as Qr,k as $r,l as ei,m as ti,n as ni,o as ri,p as ii,r as ai,s as oi,t as si,u as ci,v as li,x as ui,y as di}from"./shared-DqziuFis.js";import{n as fi,t as pi}from"./esbuild-wasm-C_e51T2J.js";import{n as mi,t as hi}from"./wasm-compiler-Ct7QZURL.js";import{_ as gi,a as _i,c as vi,f as yi,g as bi,h as xi,l as Si,m as Ci,n as wi,p as Ti,r as Ei,u as Di,v as Oi,y as ki}from"./github-zip-DluIBUmq.js";import{a as Ai,c as ji,d as Mi,f as Ni,i as Pi,l as Fi,n as Ii,o as Li,p as Ri,r as zi,s as Bi,u as Vi}from"./github-install-CdvlpkjZ.js";import{n as Hi,t as Ui}from"./magick-wasm-DVJe3sB9.js";import{a as Wi,c as Gi,i as Ki,l as qi,n as Ji,o as Yi,r as Xi,s as Zi,t as Qi,u as $i}from"./installer-DW4F27JY.js";import{t as ea}from"./local-llm-CL0LbvPc.js";import{t as ta}from"./client-BTUV7dbh.js";import{t as na}from"./redirect-uri-DHI820pd.js";var ra=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 ia(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 aa=r(`cdp`);var oa=class{ws=null;nextId=1;_superseded=!1;pending=new ra;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,aa.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(aa.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(),aa.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),aa.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 ia(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;aa.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(aa.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;aa.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,aa.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):aa.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 sa=r(`har-recorder`);var ca=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}`),sa.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=>{sa.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 la(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return sa.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 sa.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)),sa.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 sa.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 la(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){sa.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return sa.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const ua=`(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 _g(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 vg(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function yg(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 bg(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 xg(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 Sg(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 Cg(e,t){let n=mg(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 wg(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Cg(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 Tg(e,t){let n=Cg(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 Eg(e){let t=pg[e.type];return e.type===`session-reload`?hg(e,t):e.type===`upgrade`?gg(e,t):e.type===`cherry`?_g(e,t):e.type===`preview`?vg(e,t):e.type===`workflow`?yg(e,t):e.type===`bash`?bg(e,t):e.type===`sudo-request`?xg(e,t):e.type===`navigate`?Tg(e,t):e.type===`webhook`?wg(e,t):e.type===`discovery`?Sg(e,t):Cg(e,t)}const Dg=new Map;function Og(e){let t=Dg.get(e.id);t&&(Dg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const kg=`slicc-sprinkle-routes`;function Ag(){try{let e=localStorage.getItem(kg);return e?JSON.parse(e):{}}catch{return{}}}function jg(e){try{localStorage.setItem(kg,JSON.stringify(e))}catch{}}function Mg(e){return Ag()[e]}function Ng(e,t){let n=Ag();n[e]=t,jg(n)}function Pg(e){let t=Ag();delete t[e],jg(t)}function Fg(){return Ag()}function Ig(e){switch(e){case`initializing`:return`creating`;case`processing`:return`running`;case`error`:return`failed`;case`ready`:return`ready`;default:return`creating`}}function Lg(e){if(vh(e))return{root:`/workspace`,memoryPath:`/workspace/CLAUDE.md`,scratch:`/tmp`};let t=`/scoops/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:t}}function Rg(e,t){let n=vh(e);return{id:e.jid,parentId:e.parentJid,name:e.name,folder:e.folder,status:Ig(t?.status),display:{role:n?`primary`:`child`,label:e.assistantLabel},workspace:Lg(e),policy:xh(e),completion:Sh(e)}}var zg=class{id;host;constructor(e,t){this.id=e,this.host=t}record(){let e=this.host.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);return e}get descriptor(){return Rg(this.record(),this.host.getScoopTabState(this.id))}send(e){let t=this.record();return this.host.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t.assistantLabel,[],e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.host.observeScoop(this.id,{onStatusChange:t=>e({type:`status`,status:Ig(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.host.stopScoop(this.id)}close(){return this.host.unregisterScoop(this.id)}async snapshot(){let e=this.host.getScoopContext(this.id);return{descriptor:this.descriptor,messages:e?e.getAgentMessages():[],contextFill:e?e.getContextFill():0}}};function Bg(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,isCone:n,type:n?`cone`:`scoop`,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...e.config?{config:e.config,configSchemaVersion:2}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{}};return n||(i.trigger=`@${r}`),i}var Vg=class{host;runtimes=new Map;constructor(e){this.host=e}async create(e){if(e.parentId!==null&&!this.host.getScoop(e.parentId))throw Error(`Parent work unit not found: ${e.parentId}`);let t=Bg(e);return await this.host.registerScoop(t),this.get(t.jid).descriptor}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){if(!this.host.getScoop(e))return this.runtimes.delete(e),null;let t=this.host.getLiveUnit?.(e);if(t)return t;let n=this.runtimes.get(e);return n||(n=new zg(e,this.host),this.runtimes.set(e,n)),n}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return Ch(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return wh(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async close(e){let t=this.get(e);if(t){for(let t of this.getChildren(e))await this.close(t.descriptor.id);await t.close(),this.runtimes.delete(e)}}};function Hg(e){let t=vh(e);return e.isCone=t,e.type=t?`cone`:`scoop`,t&&(e.trigger=void 0,e.requiresTrigger=!1,e.assistantLabel=e.assistantLabel||`sliccy`),e}const Ug=`cone`;function Wg(e){return`session-${e.folder}`}function Gg(e){return e.toLowerCase().normalize(`NFKD`).replace(/\p{M}+/gu,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`cone`}function Kg(e,t){let n=new Set;for(let e of t)n.add(e.folder);if(!n.has(`cone`))return Ug;let r=`cone-${Gg(e)}`;if(!n.has(r))return r;for(let e=2;;e++){let t=`${r}-${e}`;if(!n.has(t))return t}}function qg(e){return vh(e)?`cone`:`scoop`}function Jg(e){return vh(e)?`cone`:e.name??e.folder}const Yg=r(`kernel-agent-event-stream`);var Xg=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){Yg.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}-${Zg()}`,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`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress});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 Zg(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Qg=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=$g(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:vh(e),parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=wh(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function $g(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 e_={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function t_(){return{...e_}}function n_(){let e=t_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(xn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const r_=new Set;function i_(e){return r_.add(e),()=>{r_.delete(e)}}function a_(){return o_(aee(),t_())}function o_(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 s_=`__slicc_binary__`;function c_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[s_]===`b64`&&typeof t.data==`string`}function l_(e){if(e instanceof Uint8Array)return{[s_]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(l_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=l_(r);return t}return e}function u_(e){if(c_(e))return f(e.data);if(Array.isArray(e))return e.map(u_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=u_(r);return t}return e}const d_=r(`panel-transport`);function f_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function p_(){return{onMessage:e=>{let t=(t,n,r)=>(f_(t)&&e(u_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=l_(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)||d_.error(`Offscreen → panel transport send failed`,{error:t})})}}}const m_=r(`kernel-bridge`);function h_(){return globalThis}function g_(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 __=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Qg;agentEventStream=new Xg;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=p_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new cg;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-${v_()}`;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)=>{en.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{en.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})},onToolProgress:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r})},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=tn(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:v_(),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=$t(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Qt(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.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Wg(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],a_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...a_()};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=g_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Mg(e),s=o?a.find(e=>e.name===o||e.folder===o||e.folder===`${o}-scoop`):void 0;if(s||=wh(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Eg({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\`\`\``,u={id:c,chatJid:s.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:l,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(s.jid).push({id:c,role:`user`,content:l,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(s.jid),await this.orchestrator.handleMessage(u)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=wh(this.orchestrator.getScoops())[0];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=Wg(t);this.sessionStore.saveMessages(n,e).catch(e=>{m_.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?wh(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:Jg(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})),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=Wg(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t});return}}catch(e){m_.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=Kg(e,this.orchestrator.getScoops()),n=t===Ug,r={...Bg({parentId:null,name:e,folder:t}),assistantLabel:n?`sliccy`:e};await this.orchestrator.registerScoop(r),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(r)})}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:y_(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:Jg(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:y_(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=Wg(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}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=Wg(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){m_.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}-${v_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Jg(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Og(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=h_()[Mh];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(),n=t.find(t=>t.jid===e);if(n&&vh(n)){if(wh(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);for(let e of[...r,n])this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Wg({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e){let t=this.getConeJid()??void 0;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=h_().__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=h_().__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`){Xt.markMounted(t);return}try{await Xt.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}),Xt.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 v_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function y_(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 Cg(e,t){let n=mg(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 wg(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Cg(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 Tg(e,t){let n=Cg(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 Eg(e){let t=pg[e.type];return e.type===`session-reload`?hg(e,t):e.type===`upgrade`?gg(e,t):e.type===`cherry`?_g(e,t):e.type===`preview`?vg(e,t):e.type===`workflow`?yg(e,t):e.type===`bash`?bg(e,t):e.type===`sudo-request`?xg(e,t):e.type===`navigate`?Tg(e,t):e.type===`webhook`?wg(e,t):e.type===`discovery`?Sg(e,t):Cg(e,t)}const Dg=new Map;function Og(e){let t=Dg.get(e.id);t&&(Dg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const kg=`slicc-sprinkle-routes`;function Ag(){try{let e=localStorage.getItem(kg);return e?JSON.parse(e):{}}catch{return{}}}function jg(e){try{localStorage.setItem(kg,JSON.stringify(e))}catch{}}function Mg(e){return Ag()[e]}function Ng(e,t){let n=Ag();n[e]=t,jg(n)}function Pg(e){let t=Ag();delete t[e],jg(t)}function Fg(){return Ag()}function Ig(e){switch(e){case`initializing`:return`creating`;case`processing`:return`running`;case`error`:return`failed`;case`ready`:return`ready`;default:return`creating`}}function Lg(e){if(vh(e))return{root:`/workspace`,memoryPath:`/workspace/CLAUDE.md`,scratch:`/tmp`};let t=`/scoops/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:t}}function Rg(e,t){let n=vh(e);return{id:e.jid,parentId:e.parentJid,name:e.name,folder:e.folder,status:Ig(t?.status),display:{role:n?`primary`:`child`,label:e.assistantLabel},workspace:Lg(e),policy:xh(e),completion:Sh(e)}}var zg=class{id;host;constructor(e,t){this.id=e,this.host=t}record(){let e=this.host.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);return e}get descriptor(){return Rg(this.record(),this.host.getScoopTabState(this.id))}send(e){let t=this.record();return this.host.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t.assistantLabel,[],e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.host.observeScoop(this.id,{onStatusChange:t=>e({type:`status`,status:Ig(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.host.stopScoop(this.id)}close(){return this.host.unregisterScoop(this.id)}async snapshot(){let e=this.host.getScoopContext(this.id);return{descriptor:this.descriptor,messages:e?e.getAgentMessages():[],contextFill:e?e.getContextFill():0}}};function Bg(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,isCone:n,type:n?`cone`:`scoop`,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...e.config?{config:e.config,configSchemaVersion:2}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{}};return n||(i.trigger=`@${r}`),i}var Vg=class{host;runtimes=new Map;constructor(e){this.host=e}async create(e){if(e.parentId!==null&&!this.host.getScoop(e.parentId))throw Error(`Parent work unit not found: ${e.parentId}`);let t=Bg(e);return await this.host.registerScoop(t),this.get(t.jid).descriptor}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){if(!this.host.getScoop(e))return this.runtimes.delete(e),null;let t=this.host.getLiveUnit?.(e);if(t)return t;let n=this.runtimes.get(e);return n||(n=new zg(e,this.host),this.runtimes.set(e,n)),n}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return Ch(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return wh(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async close(e){let t=this.get(e);if(t){for(let t of this.getChildren(e))await this.close(t.descriptor.id);await t.close(),this.runtimes.delete(e)}}};function Hg(e){let t=vh(e);return e.isCone=t,e.type=t?`cone`:`scoop`,t&&(e.trigger=void 0,e.requiresTrigger=!1,e.assistantLabel=e.assistantLabel||`sliccy`),e}const Ug=`cone`;function Wg(e){return`session-${e.folder}`}function Gg(e){return e.toLowerCase().normalize(`NFKD`).replace(/\p{M}+/gu,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`cone`}function Kg(e,t){let n=new Set;for(let e of t)n.add(e.folder);if(!n.has(`cone`))return Ug;let r=`cone-${Gg(e)}`;if(!n.has(r))return r;for(let e=2;;e++){let t=`${r}-${e}`;if(!n.has(t))return t}}function qg(e){return vh(e)?`cone`:`scoop`}function Jg(e){return vh(e)?`cone`:e.name??e.folder}const Yg=r(`kernel-agent-event-stream`);var Xg=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){Yg.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}-${Zg()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=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`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function Zg(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Qg=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=$g(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:vh(e),parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=wh(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function $g(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 e_={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function t_(){return{...e_}}function n_(){let e=t_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(xn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const r_=new Set;function i_(e){return r_.add(e),()=>{r_.delete(e)}}function a_(){return o_(aee(),t_())}function o_(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 s_=`__slicc_binary__`;function c_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[s_]===`b64`&&typeof t.data==`string`}function l_(e){if(e instanceof Uint8Array)return{[s_]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(l_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=l_(r);return t}return e}function u_(e){if(c_(e))return f(e.data);if(Array.isArray(e))return e.map(u_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=u_(r);return t}return e}const d_=r(`panel-transport`);function f_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function p_(){return{onMessage:e=>{let t=(t,n,r)=>(f_(t)&&e(u_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=l_(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)||d_.error(`Offscreen → panel transport send failed`,{error:t})})}}}const m_=r(`kernel-bridge`);function h_(){return globalThis}function g_(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 __=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Qg;agentEventStream=new Xg;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=p_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new cg;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-${v_()}`;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,i)=>{en.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{en.has(n)||e.bufferToolEnd(t,n,r,i,a)},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})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=tn(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??v_(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=$t(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Qt(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(Wg(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],a_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...a_()};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=g_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Mg(e),s=o?a.find(e=>e.name===o||e.folder===o||e.folder===`${o}-scoop`):void 0;if(s||=wh(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Eg({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\`\`\``,u={id:c,chatJid:s.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:l,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(s.jid).push({id:c,role:`user`,content:l,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(s.jid),await this.orchestrator.handleMessage(u)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=wh(this.orchestrator.getScoops())[0];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=Wg(t);this.sessionStore.saveMessages(n,e).catch(e=>{m_.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?wh(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:Jg(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})),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=Wg(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t});return}}catch(e){m_.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=Kg(e,this.orchestrator.getScoops()),n=t===Ug,r={...Bg({parentId:null,name:e,folder:t}),assistantLabel:n?`sliccy`:e};await this.orchestrator.registerScoop(r),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(r)})}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:y_(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:Jg(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:y_(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=Wg(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}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=Wg(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){m_.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}-${v_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?Jg(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Og(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=h_()[Mh];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(),n=t.find(t=>t.jid===e);if(n&&vh(n)){if(wh(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);for(let e of[...r,n])this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=Wg({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e){let t=this.getConeJid()??void 0;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=h_().__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=h_().__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`){Xt.markMounted(t);return}try{await Xt.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}),Xt.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 v_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function y_(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 b_=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function x_(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(b_.map(e=>S_(i,e,t,r)))).filter(e=>e!==null)}async function S_(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||!C_(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function C_(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 w_=r(`navigation-watcher`);function T_(e,t){return tr(e,t)}var E_=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}=T_(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=rr(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 x_(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){w_.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){w_.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){w_.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){w_.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){w_.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){w_.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){w_.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};function D_(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var O_=`# /etc/llmstxtignore — llms.txt discovery suppression
|
|
893
893
|
#
|
|
894
894
|
# One advertising hostname or glob per line. Matching is case-insensitive.
|
|
@@ -5426,7 +5426,7 @@ except BaseException:
|
|
|
5426
5426
|
`)}}function uz(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=fz(e.stdin??``,o),c=ez(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:Vr},version:`v${Vr}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new sz(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var dz=class extends hP.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 sz){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 fz(e,t){return new dz(e,t)}function pz(e){if(e===``)return[];let t=e.split(`
|
|
5427
5427
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function mz(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function hz(e){return new TextDecoder(`utf-8`).decode(vN(e))}function gz(e){if(e&&typeof e.write==`function`)return e}var _z=class extends lP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=pz(hz(mz(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 sz&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function vz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=gz(e.output)}else r=t,i=gz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new _z(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:_z,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var yz=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`?`: ${bz(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 bz(e){try{return JSON.stringify(e)}catch{return String(e)}}function xz(e){return new Promise(t=>setTimeout(t,e))}function Sz(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 Cz(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 wz(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function Tz(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 Ez(e){if(wz(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 Dz(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 Oz(e){let t=e.sleep??xz;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=Sz(n.baseUrl,o,s.params),l=Cz(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=Dz(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 Ez(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 Ez(m).catch(()=>null);throw new yz(m.status,m.statusText,c,e)}let h=Tz(m.headers.get(`retry-after`)),g=500*2**a;await t(h===null?g:h)}if(f){let e=await Ez(f).catch(()=>null);throw new yz(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 kz(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 Az(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`,kz(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 jz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Az(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 Mz(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 Nz(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:Mz(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Pz(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:Mz(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Mz(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Mz(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Nz(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Fz(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 Iz(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 Lz(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 Pz(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=Fz(c),d=Iz(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function Rz(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 zz(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=Rz(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 Bz(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 Vz(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 Vz(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:Hz(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:Hz(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:Hz(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 Hz(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 Uz(e){return{findTab:t=>e.call(`browser`,`findTab`,[Gz(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,Kz(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Rz(t),Wz(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Rz(t),Wz(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Rz(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Rz(t),n]),fetch:(t,n,r={})=>Lz(n,r).then(n=>e.call(`browser`,`evalAsync`,[Rz(t),n])),websocket:zz(e)}}function Wz(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 Gz(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 Kz(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function qz(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function Jz(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:qz(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function Yz(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 Xz(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Zz(e){return e==null?[]:Array.isArray(e)?e:[e]}function Qz(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:Xz(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,Yz(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,Yz(r)]),receiveFeatureReport:async t=>Xz((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 $z(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>Qz(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[Zz(t)]))[0];if(!n)throw Error(`No device selected.`);return Qz(e,n)}}}function eB(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 tB=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 };`)}},nB=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=eB(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 tB(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 tB(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?.())}},rB=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 nB(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()}},iB=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 nB(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 rB(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 aB(e){let t=async t=>new iB(e),n=async(t,n)=>new iB(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const oB=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`]),sB={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 cB(e,t){let n=sB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function lB(e){return{...e,time:az,fmt:YN,pool:tz}}function uB(e,t){return e?.startsWith(`/`)?oz(e):t}function dB(e){return e.includes(`require`)||e.includes(`import`)}async function fB(e,t,n,r){return dB(t)?e.call(`module`,`buildGraph`,[t,uB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function pB(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 mB(e){return{playwright:aB(e)}}function hB(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:vB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=gB(t,n,r,i,c);if(a.hit)return a;if(oB.has(t))throw cB(e,t);if($r.has(t))throw bB(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]):_B(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=oz(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`&&pB(o.exports),o.exports}return{require:e=>p(t.entryMap,e)}}function gB(e,t,n,r,i){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:mF}:e===`crypto`?{hit:!0,value:nF}: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:sP}:e===`assert/strict`?{hit:!0,value:oP}:e===`util`?{hit:!0,value:jP}:e===`events`?{hit:!0,value:uP}:e===`os`?{hit:!0,value:rF}:e===`tty`?{hit:!0,value:hF}:e===`stream`?{hit:!0,value:hP}:e===`url`?{hit:!0,value:vF}:e===`zlib`?{hit:!0,value:QR}:e===`readline`&&i?{hit:!0,value:i}:e===`readline/promises`&&i?{hit:!0,value:i.promises}:{hit:!1}}function _B(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 vB(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 yB={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function bB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${yB[t]||``}`)}async function xB(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";
|
|
5428
5428
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof sz?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function SB(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?Yz(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,Yz(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function CB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>SB(e,t)),request:async t=>SB(e,await e.call(`serial`,`request`,[Zz(t)]))}}function wB(e,t){let n=t.handle,r=e=>({status:e.status,data:Xz(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,Yz(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,Yz(r)])}}function TB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>wB(e,t)),request:async t=>wB(e,await e.call(`usb`,`request`,[Zz(t)]))}}function EB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function DB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function OB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function kB(e){let t=EB(e.argv[1]??``),n=OB(t,`references`),r=OB(t,`assets`),i=OB(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)+`
|
|
5429
|
-
`),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 ${DB(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 AB=new Map,jB=new Map;function MB(e){let t=crypto.randomUUID();return AB.set(t,e),t}function NB(e){return AB.get(e)??null}function PB(e,t){if(!AB.has(e))return t.abort(),()=>{};let n=jB.get(e);return n||(n=new Set,jB.set(e,n)),n.add(t),()=>{let n=jB.get(e);n&&(n.delete(t),n.size===0&&jB.delete(e))}}function FB(e){AB.delete(e);let t=jB.get(e);if(t){jB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function IB(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 LB(e){let t=NB(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 IB(e)}}function RB(e){return`slicc-sync-fs-`+e}const zB=`sync-fs-ack`,BB=`sync-fs-res`,VB=6e5,HB=5e3,UB=`exec`;function WB(e){return e.channel===UB}function GB(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 KB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,VB)}async function qB(e){let t=NB(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=GB(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()},KB(e.timeoutMs,VB)),o=PB(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`}:IB(e)}finally{clearTimeout(a),o()}}function JB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function YB(e){let t=ZB(e);if(QB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw JB(`EIO`,e.label);$B(t,e.label)}function XB(e){let t=YB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw JB(`EIO`,e.label)}}function ZB(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 JB(`EIO`,e.label)}return t}function QB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function $B(e,t){throw JB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function eV(e){return(t,n,r)=>{let i=XB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:UB})),timeoutMs:n+HB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw JB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function tV(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 nV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??eV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&tV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=KB(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 rV(e,t){return JB(e,`sync-fs bridge, '${t}'`)}function iV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function aV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:iV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return YB(r(`GET`,e))},writeFile(e,t){YB(r(`POST`,e,t))},stat(e){let t=XB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=XB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=XB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw rV(`EIO`,e);return t},exists(e){let t=XB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw rV(`EIO`,e);return t},mkdir(e){YB(r(`POST`,e,void 0,`mkdir`))},rm(e){YB(r(`POST`,e,void 0,`rm`))}}}const oV=new TextEncoder,sV=new TextDecoder;function cV(e){if(!e.ok)return{status:4,payload:oV.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:oV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function lV(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(sV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(sV.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 uV(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 dV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function fV(e,t,n={}){let{header:r,window:i}=uV(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 JB(`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 JB(`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 JB(`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 JB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return lV(f,d)}}}function pV(e,t){return JB(e,`sync-sab bridge, '${t}'`)}function mV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function hV(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 pV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw pV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw pV(`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(!mV(t))throw pV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!mV(t))throw pV(`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 pV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw pV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function gV(e){return(t,n,r)=>{let i=e.call({...t,channel:UB},n+HB,r);if(!i.ok)throw JB(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 JB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function _V(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 gN(r)}function vV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function yV(e,t){return t?hV(t):e.syncFsToken?aV(e.syncFsToken):void 0}function bV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return fV(e.syncSab,t)}function xV(e,t,n,r,i){let a=bV(e,t),o=yV(e,a);if(Object.assign(r,IN(n,e.cwd,o,i)),e.syncFsToken)return nV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:gV(a)}:{}})}function SV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Gn().version,writable:!1,enumerable:!1,configurable:!1})}function CV(e,t,n){let r=zN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:LN({writeStdout:t,writeStderr:n,exit:e=>{throw new sz(e)},color:r})}}function wV(e,t,n){return{readStdinBytes:()=>vN(e.stdin??``),writeStdout:t,writeStderr:n}}function TV(e){return{usbBridge:TB(e),serialBridge:CB(e),hidBridge:$z(e)}}async function EV(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=lz(i,a),s=uz(e,i,a),{colorApi:c,cliApi:l}=CV(!!e.env?.NO_COLOR,i,a),u=new DM(t),d=wV(e,i,a),f=AN(u,C,d),p=await _V(u,e.cwd,vV(e,a)),m=xV(e,t,p,f,d),h=Jz(u,p,e.cwd,a),g=jz(h,{cwd:e.cwd}),_=kB({argv:e.argv,fs:f,exec:h}),v=Uz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=TV(u),S=Oz({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 Bz(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=lB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=oz(T),D=await fB(u,e.code,e.cwd,T),O=hB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:BP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:mB(u),nodeReadline:vz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;SV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await xB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await DV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await OV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function DV(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 OV(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 kV(){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 AV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=kV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&EV(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 jV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=kV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&RM(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 MV=AV(),NV=jV();function PV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?IV():NV({kind:e,ctx:t}):typeof Worker<`u`?FV():MV({kind:e,ctx:t})}function FV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return LV(new Worker(new URL(`/assets/js-realm-worker-BxobmOGu.js`,``+import.meta.url),{type:`module`}))}function IV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return LV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function LV(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 RV(){if(Yr())return decodeURIComponent(Zr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function zV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function BV(e){return e instanceof Error?e.message:String(e)}function VV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function HV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:VV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function UV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:VV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const WV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,GV=/\bimport\s*\.\s*meta\b/g;function KV(e,t){let n=JSON.stringify(t);return e.replace(WV,n).replace(GV,`({ url: ${n} })`)}async function qV(e,t,n,r){let i=await e();return i.transpileModule(KV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function JV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>fi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ci(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Kr(e))return e;let a=zV(t),o;try{return await HV(n,e,t,a)}catch(e){o=e}try{return await qV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${BV(o)}; typescript fallback: ${BV(e)}`)}}}function YV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>fi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ci(t));return async({source:e,filename:t})=>{if(!Kr(e)&&!di(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?zV(t):void 0,o=i?t:`[eval].js`,s;try{return await UV(n,e,t,a)}catch(e){s=e}try{return await qV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${BV(s)}; typescript fallback: ${BV(e)}`)}}}function XV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5429
|
+
`),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 ${DB(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 AB=new Map,jB=new Map;function MB(e){let t=crypto.randomUUID();return AB.set(t,e),t}function NB(e){return AB.get(e)??null}function PB(e,t){if(!AB.has(e))return t.abort(),()=>{};let n=jB.get(e);return n||(n=new Set,jB.set(e,n)),n.add(t),()=>{let n=jB.get(e);n&&(n.delete(t),n.size===0&&jB.delete(e))}}function FB(e){AB.delete(e);let t=jB.get(e);if(t){jB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function IB(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 LB(e){let t=NB(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 IB(e)}}function RB(e){return`slicc-sync-fs-`+e}const zB=`sync-fs-ack`,BB=`sync-fs-res`,VB=6e5,HB=5e3,UB=`exec`;function WB(e){return e.channel===UB}function GB(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 KB(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,VB)}async function qB(e){let t=NB(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=GB(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()},KB(e.timeoutMs,VB)),o=PB(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`}:IB(e)}finally{clearTimeout(a),o()}}function JB(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function YB(e){let t=ZB(e);if(QB(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw JB(`EIO`,e.label);$B(t,e.label)}function XB(e){let t=YB(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw JB(`EIO`,e.label)}}function ZB(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 JB(`EIO`,e.label)}return t}function QB(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function $B(e,t){throw JB(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function eV(e){return(t,n,r)=>{let i=XB({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:UB})),timeoutMs:n+HB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw JB(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function tV(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 nV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??eV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&tV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=KB(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 rV(e,t){return JB(e,`sync-fs bridge, '${t}'`)}function iV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function aV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:iV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return YB(r(`GET`,e))},writeFile(e,t){YB(r(`POST`,e,t))},stat(e){let t=XB(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=XB(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw rV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=XB(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw rV(`EIO`,e);return t},exists(e){let t=XB(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw rV(`EIO`,e);return t},mkdir(e){YB(r(`POST`,e,void 0,`mkdir`))},rm(e){YB(r(`POST`,e,void 0,`rm`))}}}const oV=new TextEncoder,sV=new TextDecoder;function cV(e){if(!e.ok)return{status:4,payload:oV.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:oV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function lV(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(sV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(sV.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 uV(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 dV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function fV(e,t,n={}){let{header:r,window:i}=uV(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 JB(`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 JB(`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 JB(`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 JB(`EIO`,a)}}finally{Atomics.store(r,0,0)}return lV(f,d)}}}function pV(e,t){return JB(e,`sync-sab bridge, '${t}'`)}function mV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function hV(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 pV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw pV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw pV(`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(!mV(t))throw pV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!mV(t))throw pV(`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 pV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw pV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function gV(e){return(t,n,r)=>{let i=e.call({...t,channel:UB},n+HB,r);if(!i.ok)throw JB(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 JB(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function _V(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 gN(r)}function vV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function yV(e,t){return t?hV(t):e.syncFsToken?aV(e.syncFsToken):void 0}function bV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return fV(e.syncSab,t)}function xV(e,t,n,r,i){let a=bV(e,t),o=yV(e,a);if(Object.assign(r,IN(n,e.cwd,o,i)),e.syncFsToken)return nV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:gV(a)}:{}})}function SV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Gn().version,writable:!1,enumerable:!1,configurable:!1})}function CV(e,t,n){let r=zN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:LN({writeStdout:t,writeStderr:n,exit:e=>{throw new sz(e)},color:r})}}function wV(e,t,n){return{readStdinBytes:()=>vN(e.stdin??``),writeStdout:t,writeStderr:n}}function TV(e){return{usbBridge:TB(e),serialBridge:CB(e),hidBridge:$z(e)}}async function EV(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=lz(i,a),s=uz(e,i,a),{colorApi:c,cliApi:l}=CV(!!e.env?.NO_COLOR,i,a),u=new DM(t),d=wV(e,i,a),f=AN(u,C,d),p=await _V(u,e.cwd,vV(e,a)),m=xV(e,t,p,f,d),h=Jz(u,p,e.cwd,a),g=jz(h,{cwd:e.cwd}),_=kB({argv:e.argv,fs:f,exec:h}),v=Uz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=TV(u),S=Oz({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 Bz(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=lB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=oz(T),D=await fB(u,e.code,e.cwd,T),O=hB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:BP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:mB(u),nodeReadline:vz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;SV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await xB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await DV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await OV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function DV(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 OV(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 kV(){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 AV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=kV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&EV(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 jV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=kV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&RM(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 MV=AV(),NV=jV();function PV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?IV():NV({kind:e,ctx:t}):typeof Worker<`u`?FV():MV({kind:e,ctx:t})}function FV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return LV(new Worker(new URL(`/assets/js-realm-worker-BOYBWbOZ.js`,``+import.meta.url),{type:`module`}))}function IV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return LV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function LV(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 RV(){if(Yr())return decodeURIComponent(Zr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function zV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function BV(e){return e instanceof Error?e.message:String(e)}function VV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function HV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:VV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function UV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:VV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const WV=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,GV=/\bimport\s*\.\s*meta\b/g;function KV(e,t){let n=JSON.stringify(t);return e.replace(WV,n).replace(GV,`({ url: ${n} })`)}async function qV(e,t,n,r){let i=await e();return i.transpileModule(KV(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function JV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>fi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ci(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Kr(e))return e;let a=zV(t),o;try{return await HV(n,e,t,a)}catch(e){o=e}try{return await qV(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${BV(o)}; typescript fallback: ${BV(e)}`)}}}function YV(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>fi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>ci(t));return async({source:e,filename:t})=>{if(!Kr(e)&&!di(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?zV(t):void 0,o=i?t:`[eval].js`,s;try{return await UV(n,e,t,a)}catch(e){s=e}try{return await qV(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${BV(s)}; typescript fallback: ${BV(e)}`)}}}function XV(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5430
5430
|
`);return t===-1?``:e.slice(t+1)}function ZV(e){return zt(e).dir}const QV=[`node`,`require`,`default`],$V=[`node`,`import`,`default`],eH=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,tH=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,nH=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,rH=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,iH=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function aH(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function oH(e){let t=ui(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!aH(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(eH,`require`,`require`),r(tH,`import`,`import`),r(nH,`import`,`import`),r(rH,`import`,`export`),r(iH,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function sH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=XV(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 cH(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??QV,s=e.importConditions??$V,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 sH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=ZV(e),p={};for(let{specifier:t,kind:i}of oH(n)){let n;try{n=await Hr(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 Hr(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 lH(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Ur.has(e)||oB.has(e))}async function uH(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 oH(t))if(lH(e))try{let t=await cH({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?$V:QV,requireConditions:QV,importConditions:$V});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&&(Kr(t)||di(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 dH(){return globalThis.navigator?.hid??null}function fH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function pH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&fH(e)===fH(t)&&!!e.productName}var mH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(pH(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 hH=null;function gH(){return hH||=new mH,hH}const _H=4194304;function vH(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 yH(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function bH(e){e.opened||await e.open()}function xH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${_H}-byte (4 MiB) v1 limit`)}function SH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function CH(e,t){return(await t.getDevices()).map(t=>vH(e.register(t),t))}async function wH(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>vH(e.register(t),t))}function TH(e,t){return vH(t,yH(e,t))}async function EH(e,t){await yH(e,t).open()}async function DH(e,t){await yH(e,t).close()}async function OH(e,t,n,r){xH(r.byteLength,`send report payload`);let i=yH(e,t);await bH(i),await i.sendReport(n,r)}async function kH(e,t,n,r){xH(r.byteLength,`send feature report payload`);let i=yH(e,t);await bH(i),await i.sendFeatureReport(n,r)}async function AH(e,t,n){let r=yH(e,t);return await bH(r),{reportId:n,bytes:SH(await r.receiveFeatureReport(n))}}async function jH(e,t,n){let r=yH(e,t);await bH(r);let i=e=>{n({reportId:e.reportId,bytes:SH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const MH=6e4;function NH(){return an()}function PH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),MH);rn(`hid-device`,e??[],void 0,{timeoutMs:MH}).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 FH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var IH=class{registry;constructor(e){this.registry=e}hid(){let e=dH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return CH(this.registry,this.hid())}async request(e){if(NH()){let t=await PH(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=>vH(this.registry.register(e),e))}return wH(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(TH(this.registry,e))}open(e){return EH(this.registry,e)}close(e){return DH(this.registry,e)}sendReport(e,t,n){return OH(this.registry,e,t,FH(n))}sendFeatureReport(e,t,n){return kH(this.registry,e,t,FH(n))}async receiveFeatureReport(e,t){let n=await AH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return jH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},LH=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:FH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:FH(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 RH(e,t){return e&&dH()?new IH(gH()):t?new LH(t):null}function zH(e){return async function(t,n){let r=t instanceof Request?t:null,i=BH(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=HH(r?.headers,n?.headers),s=await GH(n,r,a,o);s.defaultContentType&&!UH(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 BH(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function VH(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 HH(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=VH(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function UH(e,t){return WH(e,t)!==void 0}function WH(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function GH(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=JH(e.body,n);return{body:await KH(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=WH(r,`content-type`)??``,a=e&&(!i||!d(i));return{body:n.byteLength===0?void 0:a?YH(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function KH(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 YH(e);if(e instanceof ArrayBuffer)return YH(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return YH(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return YH(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 qH(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function JH(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!qH(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function YH(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 XH(){return globalThis.navigator?.serial??null}var ZH=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 QH=null;function $H(){return QH||=new ZH,QH}const eU=4194304;function tU(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 nU(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function rU(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function iU(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 aU(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return tU(n,e.get(n))})}async function oU(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return tU(i,e.get(i))}function sU(e,t){return tU(t,nU(e,t))}async function cU(e,t,n){let r=nU(e,t);await r.port.open(n),r.opened=!0}async function lU(e,t){let n=nU(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 uU(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 dU(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 fU(e,t,n){let r=nU(e,t),i=Math.min(n.maxBytes??4194304,eU),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=iU(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=uU(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=rU(c,a.value);let e=u();if(e)return e}}return c}async function pU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${eU}-byte (4 MiB) v1 limit`);return await dU(nU(e,t)).write(n),n.length}async function mU(e,t){return nU(e,t).port.getSignals()}async function hU(e,t,n){await nU(e,t).port.setSignals(n)}const gU=6e4;function _U(){return an()}function vU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),gU);rn(`serial-port`,e??[],void 0,{timeoutMs:gU}).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 yU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var bU=class{registry;constructor(e){this.registry=e}serial(){let e=XH();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return aU(this.registry,this.serial())}async request(e){if(_U()){let t=await vU(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 tU(r,this.registry.get(r))}return oU(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(sU(this.registry,e))}open(e,t){return cU(this.registry,e,t)}close(e){return lU(this.registry,e)}read(e,t){return fU(this.registry,e,t)}write(e,t){return pU(this.registry,e,t)}getSignals(e){return mU(this.registry,e)}setSignals(e,t){return hU(this.registry,e,t)}},xU=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?yU(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:yU(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 SU(e,t){return e&&XH()?new bU($H()):t?new xU(t):null}function CU(){return globalThis.navigator?.usb??null}function wU(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var TU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(wU(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 EU=null;function DU(){return EU||=new TU,EU}const OU=4194304;function kU(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 AU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function jU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${OU}-byte (4 MiB) v1 limit`)}function MU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function NU(e,t){return(await t.getDevices()).map(t=>kU(e.register(t),t))}async function PU(e,t,n){let r=await t.requestDevice({filters:n});return kU(e.register(r),r)}function FU(e,t){return kU(t,AU(e,t))}async function IU(e,t){await AU(e,t).open()}async function LU(e,t){await AU(e,t).close()}async function RU(e,t,n){await AU(e,t).selectConfiguration(n)}async function zU(e,t,n){await AU(e,t).claimInterface(n)}async function BU(e,t,n){await AU(e,t).releaseInterface(n)}async function VU(e,t,n,r){jU(r,`control-in length`);let i=await AU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?MU(i.data):new ArrayBuffer(0)}}async function HU(e,t,n,r){jU(r.byteLength,`control-out payload`);let i=await AU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function UU(e,t,n,r){jU(r,`transfer-in length`);let i=await AU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?MU(i.data):new ArrayBuffer(0)}}async function WU(e,t,n,r){jU(r.byteLength,`transfer-out payload`);let i=await AU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function GU(e,t){await AU(e,t).reset()}const KU=6e4;function qU(){return an()}function JU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),KU);rn(`usb-device`,e??[],void 0,{timeoutMs:KU}).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 YU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var XU=class{registry;constructor(e){this.registry=e}usb(){let e=CU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return NU(this.registry,this.usb())}async request(e){if(qU()){let t=await JU(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 kU(this.registry.register(n),n)}return PU(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(FU(this.registry,e))}open(e){return IU(this.registry,e)}close(e){return LU(this.registry,e)}selectConfig(e,t){return RU(this.registry,e,t)}claim(e,t){return zU(this.registry,e,t)}release(e,t){return BU(this.registry,e,t)}async controlIn(e,t,n){let r=await VU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return HU(this.registry,e,t,YU(n))}async transferIn(e,t,n){let r=await UU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return WU(this.registry,e,t,YU(n))}reset(e){return GU(this.registry,e)}},ZU=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:YU(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:YU(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function QU(e,t){return e&&CU()?new XU(DU()):t?new ZU(t):null}function $U(e,t,n,r={}){let{header:i,window:a}=uV(t),o=new Map,s=!1,c=r.dispatch??(e=>WB(e)?qB(e):LB(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}=cV(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 eW=r(`realm-host`);function tW(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?MB({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;nW(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?$U(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&FB(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 nW(e,t,n,r,i,a){try{let o=await rW(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=KW(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 rW(e,t,n,r,i){switch(e.channel){case`vfs`:return lW(e.op,e.args,t);case`exec`:return SW(e.op,e.args,t,i);case`fetch`:return EW(e.op,e.args,t);case`browser`:return AW(e.op,e.args,iW(n),n);case`usb`:return UW(e.op,e.args,oW(n));case`serial`:return WW(e.op,e.args,sW(n));case`hid`:return GW(e.op,e.args,cW(n),r);case`module`:return OW(e.op,e.args,t);case`wasm`:return kW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function iW(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 aW(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 oW(e){if(e.usbBackend)return e.usbBackend;let t=QU(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function sW(e){if(e.serialBackend)return e.serialBackend;let t=SU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function cW(e){if(e.hidBackend)return e.hidBackend;let t=RH(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function lW(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 vW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await yW(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const uW=10485760;function dW(e){return e.fileCount>=500||e.totalBytes>=uW}function fW(e){return e.entries.length>=2e4}async function pW(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 mW(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 hW(e,t,n,r,i){if(n>1048576||dW(r)||r.totalBytes+n>uW){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 gW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function gW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await pW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function _W(e,t,n){if(fW(n))return;let r=[t];for(;r.length>0;){if(fW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await mW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await pW(e,t,r,n):a.isFile&&await hW(e,t,a.size,n,r)}}async function vW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await _W(e,t,n),t!==`/tmp`&&await _W(e,`/tmp`,n),{entries:n.entries}}async function yW(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 bW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),xW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function SW(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 wW(t,n,r);if(e===`kill`)return TW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function CW(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 wW(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??{};CW(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 TW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&bW.has(r)?r:`SIGTERM`;xW.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 EW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?zH(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 DW(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 OW(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=DW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return uH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:JV({ipk:s}),transpileEntry:YV({ipk:s})})}async function kW(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 hi(e=>n.fs.readFileBuffer(e),i)}async function AW(e,t,n,r){switch(e){case`findTab`:return NW(n,t[0]??{});case`ensureTab`:{let e=t[0];return PW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return FW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return FW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return zW(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return BW(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await aW(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return aW(r).update(e,n)}case`wsClose`:{let e=t[0];return aW(r).close(e)}case`wsList`:return aW(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 RW(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function jW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function MW(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=jW()?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){eW.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function NW(e,t){let n=await MW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=VW(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 PW(e,t,n){let r=await MW(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=HW(t);if(e){let t=r.find(t=>HW(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function FW(e,t,n,r){return e.withTab(t,async()=>IW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function IW(e){if(typeof e!=`string`)return e;let t=LW(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=LW(t);if(typeof e==`object`&&e)return e}return t}return e}function LW(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 RW(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(){
|
|
5431
5431
|
try {
|
|
5432
5432
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -5443,7 +5443,7 @@ except BaseException:
|
|
|
5443
5443
|
})()`,{returnByValue:!0}))return})}async function zW(e,t,n){return e.withTab(t,async()=>{let t=((await e.sendCDP(`Network.getCookies`)).cookies??[]).find(e=>e.name===n);return t&&typeof t.value==`string`?t.value:null})}async function BW(e,t,n){return e.withTab(t,async()=>{let t=await e.evaluate(`(function(){try{var v=window.localStorage.getItem(${JSON.stringify(n)});return v===null?null:String(v);}catch(e){return null;}})()`,{returnByValue:!0});return t==null?null:typeof t==`string`?t:String(t)})}function VW(e){try{return new URL(e).hostname}catch{return null}}function HW(e){try{return new URL(e).origin}catch{return null}}async function UW(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`reset`:return n.reset(t[0]);case`selectConfig`:return n.selectConfig(t[0],t[1]);case`claim`:return n.claim(t[0],t[1]);case`release`:return n.release(t[0],t[1]);case`controlIn`:return n.controlIn(t[0],t[1],t[2]);case`controlOut`:return n.controlOut(t[0],t[1],t[2]);case`transferIn`:return n.transferIn(t[0],t[1],t[2]);case`transferOut`:return n.transferOut(t[0],t[1],t[2]);default:throw Error(`realm-host: unknown usb op '${e}'`)}}async function WW(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0],t[1]);case`close`:return n.close(t[0]);case`read`:{let e=t[1]??{};return n.read(t[0],e)}case`write`:return n.write(t[0],t[1]);case`getSignals`:return n.getSignals(t[0]);case`setSignals`:return n.setSignals(t[0],t[1]);default:throw Error(`realm-host: unknown serial op '${e}'`)}}async function GW(e,t,n,r){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`sendReport`:return n.sendReport(t[0],t[1],t[2]);case`sendFeatureReport`:return n.sendFeatureReport(t[0],t[1],t[2]);case`receiveFeatureReport`:return n.receiveFeatureReport(t[0],t[1]);case`subscribeInputReports`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=await n.subscribeInputReports(e,t=>{let n=t.bytes instanceof Uint8Array?t.bytes:new Uint8Array(t.bytes),i={type:`realm-event`,channel:`hid-input-report`,payload:{handle:e,reportId:t.reportId,bytes:n}};r.pushEvent(i,[n.buffer])});return r.subscriptions.set(e,i),!0}case`unsubscribeInputReports`:{let e=t[0],n=r.subscriptions.get(e);return!n||(r.subscriptions.delete(e),await n(),!0)}default:throw Error(`realm-host: unknown hid op '${e}'`)}}function KW(e){if(e instanceof Uint8Array)return[e.buffer];if(e&&typeof e==`object`){let t=e;if(t.body instanceof Uint8Array)return[t.body.buffer];if(t.bytes instanceof Uint8Array)return[t.bytes.buffer]}return[]}async function qW(e){let t=e.procKind??`jsh`,n=e.pm.spawn({kind:t,argv:e.argv,cwd:e.cwd,env:e.env,owner:e.owner,ppid:e.ppid}),r;try{r=await e.realmFactory({kind:e.kind,ctx:e.ctx})}catch(t){let r=t instanceof Error?t.message:String(t);return e.pm.exit(n.pid,1),{stdout:``,stderr:`realm-runner: ${r}\n`,exitCode:1}}let i=r.isolatedThread?JW(e.syncSabBytes):void 0,a=tW(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:!!e.syncFsBridgeEnabled||i!==void 0,...i?{syncSab:i}:{}});return new Promise(t=>{let o=!1,s=null,c=null,l=null,u=null,d=()=>{c&&r.controlPort.removeEventListener(`message`,c),r.removeEventListener&&(l&&r.removeEventListener(`error`,l),u&&r.removeEventListener(`messageerror`,u)),s?.(),a.dispose()},f=(i,a)=>{if(!o){o=!0,d();try{r.terminate()}catch{}e.pm.exit(n.pid,a),t(i)}};c=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;f({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;f({stdout:``,stderr:t.message+`
|
|
5444
5444
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
5445
5445
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
5446
|
-
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function JW(e){if(dV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let YW=!1;function XW(e){YW=e}function ZW(){return YW}const QW=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function $W(e){let t=e;if(t.length===0)return``;let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return QW.decode(n)}function eG(e){return e}const tG=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function nG(e){return tG[e]??null}function rG(e,t){let n=nG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let iG=null;function aG(e){let t=iG;return iG=e,t}async function oG(){if(!iG)return{};try{return await iG()??{}}catch{return{}}}function sG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-DIDzpPfu.js`).then(e=>e.r);return rG(t(),e())}}async function cG(e,t,n,r,i={}){return await n.fs.exists(e)?lG(await n.fs.readFile(e),[`node`,e,...t],n,r,{...i,filename:e}):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function lG(e,t,n,r,i={}){let a=i.realmFactory??uG(),o=r?.processManager??pG()??fG(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await qW({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await oG(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:eG(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:ZW()})}function uG(){return typeof Worker<`u`||typeof document<`u`?PV():AV()}let dG=null;function fG(){return dG||=new Br,dG}function pG(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function mG(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var hG=class{aggregator=null;now;explicitSink;scrubLabel;ids=new Map;seq=0;constructor(e={}){this.now=e.now??Date.now,this.explicitSink=e.sink,this.scrubLabel=e.scrubLabel}allocateId(e=`p`){return this.seq+=1,`${e}-${this.seq}`}hasSink(){return this.resolveSink()!==null}setAggregator(e){this.aggregator=e}emit(e){let t=this.aggregator;if(t&&e.id!==t.id)return t.onChild(e),!0;let n=this.resolveSink();if(!n)return e.phase===`end`&&this.ids.delete(e.id),!1;let r=this.ids.get(e.id);if(e.phase===`update`){if(!r)return!1;let t=this.now();return t-r.lastUpdateAt<250?!1:(r.lastUpdateAt=t,this.deliver(r,n,e),!0)}if(e.phase===`start`){let t={lastUpdateAt:-1/0,rawLabel:e.label,label:this.scrubbed(e.label),tail:Promise.resolve()};return this.ids.set(e.id,t),this.deliver(t,n,e),!0}return r?(this.ids.delete(e.id),this.deliver(r,n,e),!0):!1}resolveSink(){if(this.explicitSink)return this.explicitSink;let e=Yt();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?gG(this.scrubLabel,e):e}deliver(e,t,n){n.label!==e.rawLabel&&(e.rawLabel=n.label,e.label=this.scrubbed(n.label));let{label:r}=e;if(typeof r==`string`){let e=_G(r);t(e===n.label?n:{...n,label:e});return}e.tail=e.tail.then(async()=>{let i=await r;e.label=i,t({...n,label:_G(i)})})}};async function gG(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function _G(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function vG(e,t){return t.length?`${e} ${t.join(` `)}`:e}function yG(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function bG(e,t=Date.now){let n=new Map,r=e=>n.get(e)?.[0];return{start(r,i){if(!e.hasSink())return;let a={id:e.allocateId(`net`),label:yG(r),startedAt:t()},o=n.get(r);o?o.push(a):n.set(r,[a]),e.emit({id:a.id,label:a.label,fraction:i===void 0?void 0:0,done:0,total:i,unit:`bytes`,phase:`start`})},chunk(n,i,a){let o=r(n);if(!o)return;let s,c;if(a!==void 0&&a>0){s=Math.min(1,i/a);let e=t()-o.startedAt;i>0&&(c=Math.max(0,e/i*(a-i)))}e.emit({id:o.id,label:o.label,fraction:s,etaMs:c,done:i,total:a,unit:`bytes`,phase:`update`})},end(t){let r=n.get(t),i=r?.shift();r&&r.length===0&&n.delete(t),i&&e.emit({id:i.id,label:i.label,fraction:1,etaMs:0,unit:`bytes`,phase:`end`})}}}const xG={timeout:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`)&&e[t]!==`--`;)[`-k`,`--kill-after`,`-s`,`--signal`].includes(e[t])&&(t+=1),t+=1;return e[t]===`--`&&(t+=1),t+1},env:e=>{let t=0;for(;t<e.length&&(e[t].startsWith(`-`)||e[t].includes(`=`));)t+=1;return t},nohup:()=>0,nice:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`);)t+=1;return t}},SG=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function CG(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function wG(e,t){switch(e.type){case`CommandSubstitution`:return FG(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=wG(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function TG(e,t){let n=0;for(let r of e.parts){let e=wG(r,t);if(e===null)return null;n+=e}return n}function EG(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=TG(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=TG(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=CG(e.name);if(r===null||SG.has(r))return null;if(!t.has(r))return n;n+=1;let i=xG[r];if(i){let r=e.args.map(CG);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(SG.has(a))return null;t.has(a)&&(n+=1)}return n}function DG(e){let t=typeof e.start==`number`?e.start:Number(e.start),n=typeof e.end==`number`?e.end:Number(e.end);if(!Number.isFinite(t)||!Number.isFinite(n)){let t=String(e.start),n=String(e.end);return t.length!==1||n.length!==1?null:Math.abs(n.charCodeAt(0)-t.charCodeAt(0))+1}let r=Math.abs(e.step??1)||1;return Math.floor(Math.abs(n-t)/r)+1}function OG(e){if(e.parts.length!==1||e.parts[0].type!==`CommandSubstitution`)return null;let t=e.parts[0].body;if(t.statements.length!==1)return null;let n=t.statements[0];if(n.pipelines.length!==1||n.pipelines[0].commands.length!==1)return null;let r=n.pipelines[0].commands[0];if(r.type!==`SimpleCommand`||!r.name||CG(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=CG(e);return t===null?NaN:Number(t)});if(i.some(e=>!Number.isFinite(e)))return null;let a=1,o=1,s;if(i.length===1)[s]=i;else if(i.length===2)[a,s]=i;else if(i.length===3)[a,o,s]=i;else return null;if(o===0)return null;let c=Math.floor((s-a)/o)+1;return c>0?c:0}function kG(e){let t=0;for(let n of e){let e=n.type===`Word`?AG(n.word):DG(n);if(e===null)return null;t+=e}return t}function AG(e){let t=OG(e);if(t!==null)return t;let n=1;for(let t of e.parts)switch(t.type){case`Literal`:case`SingleQuoted`:case`Escaped`:break;case`DoubleQuoted`:if(t.parts.some(e=>e.type!==`Literal`&&e.type!==`Escaped`))return null;break;case`BraceExpansion`:{let e=kG(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function jG(e){let t=0;for(let n of e){let e=AG(n);if(e===null)return null;t+=e}return t}function MG(e,t){let n=0;for(let r of e){let e=PG(r,t);if(e===null)return null;n+=e}return n}function NG(e,t){switch(e.type){case`SimpleCommand`:return EG(e,t);case`For`:{if(!e.words)return null;let n=jG(e.words),r=MG(e.body,t);return n===null||r===null?null:e.words.filter(e=>OG(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return MG(e.body,t);case`FunctionDef`:return 0;default:return null}}function PG(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=NG(e,t);if(r===null)return null;n+=r}return n}function FG(e,t){return MG(e.statements,t)}function IG(e,t){let n=FG(e,t);return{totalSteps:n!==null&&n>0?n:null}}function LG(e){return e.split(`
|
|
5446
|
+
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function JW(e){if(dV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let YW=!1;function XW(e){YW=e}function ZW(){return YW}const QW=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function $W(e){let t=e;if(t.length===0)return``;let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return QW.decode(n)}function eG(e){return e}const tG=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function nG(e){return tG[e]??null}function rG(e,t){let n=nG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let iG=null;function aG(e){let t=iG;return iG=e,t}async function oG(){if(!iG)return{};try{return await iG()??{}}catch{return{}}}function sG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r);return rG(t(),e())}}async function cG(e,t,n,r,i={}){return await n.fs.exists(e)?lG(await n.fs.readFile(e),[`node`,e,...t],n,r,{...i,filename:e}):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function lG(e,t,n,r,i={}){let a=i.realmFactory??uG(),o=r?.processManager??pG()??fG(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await qW({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await oG(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:eG(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:ZW()})}function uG(){return typeof Worker<`u`||typeof document<`u`?PV():AV()}let dG=null;function fG(){return dG||=new Br,dG}function pG(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function mG(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var hG=class{aggregator=null;now;explicitSink;scrubLabel;ids=new Map;seq=0;constructor(e={}){this.now=e.now??Date.now,this.explicitSink=e.sink,this.scrubLabel=e.scrubLabel}allocateId(e=`p`){return this.seq+=1,`${e}-${this.seq}`}hasSink(){return this.resolveSink()!==null}setAggregator(e){this.aggregator=e}emit(e){let t=this.aggregator;if(t&&e.id!==t.id)return t.onChild(e),!0;let n=this.resolveSink();if(!n)return e.phase===`end`&&this.ids.delete(e.id),!1;let r=this.ids.get(e.id);if(e.phase===`update`){if(!r)return!1;let t=this.now();return t-r.lastUpdateAt<250?!1:(r.lastUpdateAt=t,this.deliver(r,n,e),!0)}if(e.phase===`start`){let t={lastUpdateAt:-1/0,rawLabel:e.label,label:this.scrubbed(e.label),tail:Promise.resolve()};return this.ids.set(e.id,t),this.deliver(t,n,e),!0}return r?(this.ids.delete(e.id),this.deliver(r,n,e),!0):!1}resolveSink(){if(this.explicitSink)return this.explicitSink;let e=Yt();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?gG(this.scrubLabel,e):e}deliver(e,t,n){n.label!==e.rawLabel&&(e.rawLabel=n.label,e.label=this.scrubbed(n.label));let{label:r}=e;if(typeof r==`string`){let e=_G(r);t(e===n.label?n:{...n,label:e});return}e.tail=e.tail.then(async()=>{let i=await r;e.label=i,t({...n,label:_G(i)})})}};async function gG(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function _G(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function vG(e,t){return t.length?`${e} ${t.join(` `)}`:e}function yG(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function bG(e,t=Date.now){let n=new Map,r=e=>n.get(e)?.[0];return{start(r,i){if(!e.hasSink())return;let a={id:e.allocateId(`net`),label:yG(r),startedAt:t()},o=n.get(r);o?o.push(a):n.set(r,[a]),e.emit({id:a.id,label:a.label,fraction:i===void 0?void 0:0,done:0,total:i,unit:`bytes`,phase:`start`})},chunk(n,i,a){let o=r(n);if(!o)return;let s,c;if(a!==void 0&&a>0){s=Math.min(1,i/a);let e=t()-o.startedAt;i>0&&(c=Math.max(0,e/i*(a-i)))}e.emit({id:o.id,label:o.label,fraction:s,etaMs:c,done:i,total:a,unit:`bytes`,phase:`update`})},end(t){let r=n.get(t),i=r?.shift();r&&r.length===0&&n.delete(t),i&&e.emit({id:i.id,label:i.label,fraction:1,etaMs:0,unit:`bytes`,phase:`end`})}}}const xG={timeout:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`)&&e[t]!==`--`;)[`-k`,`--kill-after`,`-s`,`--signal`].includes(e[t])&&(t+=1),t+=1;return e[t]===`--`&&(t+=1),t+1},env:e=>{let t=0;for(;t<e.length&&(e[t].startsWith(`-`)||e[t].includes(`=`));)t+=1;return t},nohup:()=>0,nice:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`);)t+=1;return t}},SG=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function CG(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function wG(e,t){switch(e.type){case`CommandSubstitution`:return FG(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=wG(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function TG(e,t){let n=0;for(let r of e.parts){let e=wG(r,t);if(e===null)return null;n+=e}return n}function EG(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=TG(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=TG(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=CG(e.name);if(r===null||SG.has(r))return null;if(!t.has(r))return n;n+=1;let i=xG[r];if(i){let r=e.args.map(CG);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(SG.has(a))return null;t.has(a)&&(n+=1)}return n}function DG(e){let t=typeof e.start==`number`?e.start:Number(e.start),n=typeof e.end==`number`?e.end:Number(e.end);if(!Number.isFinite(t)||!Number.isFinite(n)){let t=String(e.start),n=String(e.end);return t.length!==1||n.length!==1?null:Math.abs(n.charCodeAt(0)-t.charCodeAt(0))+1}let r=Math.abs(e.step??1)||1;return Math.floor(Math.abs(n-t)/r)+1}function OG(e){if(e.parts.length!==1||e.parts[0].type!==`CommandSubstitution`)return null;let t=e.parts[0].body;if(t.statements.length!==1)return null;let n=t.statements[0];if(n.pipelines.length!==1||n.pipelines[0].commands.length!==1)return null;let r=n.pipelines[0].commands[0];if(r.type!==`SimpleCommand`||!r.name||CG(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=CG(e);return t===null?NaN:Number(t)});if(i.some(e=>!Number.isFinite(e)))return null;let a=1,o=1,s;if(i.length===1)[s]=i;else if(i.length===2)[a,s]=i;else if(i.length===3)[a,o,s]=i;else return null;if(o===0)return null;let c=Math.floor((s-a)/o)+1;return c>0?c:0}function kG(e){let t=0;for(let n of e){let e=n.type===`Word`?AG(n.word):DG(n);if(e===null)return null;t+=e}return t}function AG(e){let t=OG(e);if(t!==null)return t;let n=1;for(let t of e.parts)switch(t.type){case`Literal`:case`SingleQuoted`:case`Escaped`:break;case`DoubleQuoted`:if(t.parts.some(e=>e.type!==`Literal`&&e.type!==`Escaped`))return null;break;case`BraceExpansion`:{let e=kG(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function jG(e){let t=0;for(let n of e){let e=AG(n);if(e===null)return null;t+=e}return t}function MG(e,t){let n=0;for(let r of e){let e=PG(r,t);if(e===null)return null;n+=e}return n}function NG(e,t){switch(e.type){case`SimpleCommand`:return EG(e,t);case`For`:{if(!e.words)return null;let n=jG(e.words),r=MG(e.body,t);return n===null||r===null?null:e.words.filter(e=>OG(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return MG(e.body,t);case`FunctionDef`:return 0;default:return null}}function PG(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=NG(e,t);if(r===null)return null;n+=r}return n}function FG(e,t){return MG(e.statements,t)}function IG(e,t){let n=FG(e,t);return{totalSteps:n!==null&&n>0?n:null}}function LG(e){return e.split(`
|
|
5447
5447
|
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var RG=class{plan;emitter;label;now;id;steps=0;startedAt;finished=!1;children=new Map;constructor(e,t,n,r=Date.now){this.plan=e,this.emitter=t,this.label=n,this.now=r,this.id=t.allocateId(`script`),this.startedAt=r(),this.emitter.setAggregator(this),this.publish(`start`)}stepDone(){this.finished||(this.steps+=1,this.publish(`update`))}onChild(e){if(!this.finished){if(e.phase===`end`){this.children.delete(e.id);return}this.children.set(e.id,{fraction:e.fraction,label:e.label}),(e.fraction!==void 0||e.phase===`start`)&&this.publish(`update`)}}end(){this.finished||(this.finished=!0,this.emitter.setAggregator(null),this.emitter.emit({id:this.id,label:this.label,fraction:1,etaMs:0,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:`end`}))}fraction(){let e=[...this.children.values()].at(-1)?.fraction,t=this.plan.totalSteps;if(t===null)return e;let n=e??0;return Math.min(1,(this.steps+n)/t)}publish(e){let t=this.fraction(),n=this.now()-this.startedAt,r=t!==void 0&&t>0&&t<1?Math.max(0,n/t*(1-t)):t===1?0:void 0,i=[...this.children.values()].at(-1);this.emitter.emit({id:this.id,label:i?`${this.label} · ${i.label}`:this.label,fraction:t,etaMs:r,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:e})}};const zG=globalThis.setTimeout.bind(globalThis);function BG(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function VG(e,t={}){let n=t.now??Date.now,r=t.setTimeout??zG,i=t.isAborted??(()=>!1),a=t.label??BG,o=e=>new Promise(t=>r(t,e));return async t=>{let r=Math.max(0,t),s=e.allocateId(`sleep`),c=a(r),l=n();e.emit({id:s,label:c,fraction:0,etaMs:r,done:0,total:r,unit:`ms`,phase:`start`});try{let t=0;for(;t<r;){if(i())return;if(await o(Math.min(250,r-t)),t=n()-l,t<r){let n=Math.min(1,t/r);e.emit({id:s,label:c,fraction:n,etaMs:Math.max(0,r-t),done:Math.min(t,r),total:r,unit:`ms`,phase:`update`})}}}finally{e.emit({id:s,label:c,fraction:1,etaMs:0,done:r,total:r,unit:`ms`,phase:`end`})}}}const HG=globalThis.setTimeout.bind(globalThis);function UG(e){let t=/^(\d+(?:\.\d+)?|\.\d+)([smhd]?)$/.exec(e.trim());return t?Number(t[1])*({"":1e3,s:1e3,m:6e4,h:36e5,d:864e5}[t[2]]??1e3):null}function WG(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`--`)return t+1<e.length?t+1:-1;if(!n.startsWith(`-`))return t;[`-k`,`--kill-after`,`-s`,`--signal`].includes(n)&&(t+=1),t+=1}return-1}function GG(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??HG;return{...e,async execute(n,a){let o=WG(n),s=o>=0?UG(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=vG(e.name,n),u=r(),d=!0,f=()=>{if(!d)return;let e=r()-u,n=Math.min(1,e/s);t.emit({id:c,label:l,fraction:n,etaMs:Math.max(0,s-e),done:Math.min(e,s),total:s,unit:`ms`,phase:`update`}),e<s&&i(f,250)};t.emit({id:c,label:l,fraction:0,etaMs:s,done:0,total:s,unit:`ms`,phase:`start`}),i(f,250);try{return await e.execute(n,a)}finally{d=!1,t.emit({id:c,label:l,fraction:1,etaMs:0,done:s,total:s,unit:`ms`,phase:`end`})}}}}const KG=new Set(`sleep,echo,printf,true,false,test,[,cd,pwd,export,unset,set,shift,local,return,break,continue,exit,:,read,let,declare,typeset,readonly,eval,exec,source,.,alias,unalias,type,command,builtin,wait,trap,basename,dirname,seq,expr`.split(`,`));function qG(e,t,n={}){if((n.skip??KG).has(e.name))return e;let r=e.name;return{...e,async execute(n,i){if(!t.hasSink())return e.execute(n,i);let a=t.allocateId(`cmd`),o=vG(r,n);t.emit({id:a,label:o,phase:`start`});try{return await e.execute(n,i)}finally{t.emit({id:a,label:o,phase:`end`})}}}}function JG(e){return hr(`sudo`,e)}async function YG(e,t){let n=e.trim();if(!n||hee(xr(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:JG(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}function XG(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function ZG(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function QG(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0,installAll:ZG(e.installAll)},affinity:{apps:XG(e.apps),tasks:XG(e.tasks),role:XG(e.role),purpose:XG(e.purpose)},priority:n}})}const $G={apps:3,tasks:2,role:1,purpose:1};function eK(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*$G.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*$G.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=$G.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=$G.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function tK(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.installAll?t+=` --all`:e.skill&&(t+=` --skill ${e.skill}`),t}async function nK(e){let t=new Set;try{let n=await e.readDir(bi);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}function rK(e){return{purpose:e.purpose??``,role:e.role??``,tasks:Array.isArray(e.tasks)?e.tasks:[],apps:Array.isArray(e.apps)?e.apps:[],name:e.name??``,company:typeof e.company==`string`?e.company:void 0}}function iK(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function aK(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}async function oK(e,t){try{let n=iK(t);if(!n)return[];let r=await e(`${gi}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?QG(Lt(r.body).data):[]}catch{return[]}}async function sK(e){let t;try{t=await e(Oi,{headers:{Accept:`application/json`}})}catch(e){throw Error(Di(e,Oi))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return QG(Lt(t.body).data)}function cK(e,t,n){let r=e.entry.source;if(r.skill){let e=n.get(r.skill);return e?{skillPath:e,skillName:r.skill}:r.path?{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:r.skill}:{error:`skill "${r.skill}" not found in ${t}`}}if(r.path)return{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:e.entry.name};let i=n.get(e.entry.name);return i?{skillPath:i,skillName:e.entry.name}:{error:`skill "${e.entry.name}" not found in ${t} and no explicit path provided`}}async function lK(e,t,n,r,i,a,o,s,c){let l=e.entry.source,u=l.path.replace(/^\/|\/$/g,``),d=o<s?` (~${Math.round((s-o)*(Date.now()-c)/o/1e3)}s remaining)`:``,f=[];for(let[e,t]of r)(t===u||t.startsWith(`${u}/`))&&f.push({name:e,path:t});if(f.length===0){let n=`no skills found under "${l.path}" in ${t}`;return{results:[{ok:!1,name:e.entry.name,error:n}],line:`[${o}/${s}] Failed "${e.entry.name}" bundle from ${t}: ${n}${d}\n`}}let p=Date.now(),m=0,h=0,g=[];for(let e of f){if(i.has(e.name))continue;let t=await Li(e.path,e.name,n,a,!1);t.ok?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.error}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${o}/${s}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${o}/${s}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${o}/${s}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function uK(e,t,n,r,i,a,o,s,c,l){let u=e.entry.source,d=s<c?` (~${Math.round((c-s)*(Date.now()-l)/s/1e3)}s remaining)`:``,f=await zi(n,r,i,u.path);if(f.error)return{results:[{ok:!1,name:e.entry.name,error:f.error}],line:`[${s}/${c}] Failed "${e.entry.name}" bundle from ${t}: ${f.error}${d}\n`};let p=Date.now(),m=0,h=0,g=[];for(let e of f.skills){if(a.has(e.name))continue;let t=await Ii(n,r,e.path,e.name,o,i,!1);t.exitCode===0?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.stderr.trim()}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${s}/${c}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${s}/${c}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${s}/${c}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function dK(e,t,n,r,i,a,o,s){let c=new Map;for(let e of Object.keys(n))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``);c.set(t.split(`/`).pop()||t,t)}let l=[],u=``;for(let d of t){let t=d.entry.source;if(t.installAll&&t.path){r.count++;let t=await lK(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=cK(d,e,c);if(`error`in f){l.push({ok:!1,name:d.entry.name,error:f.error}),r.count++;let t=r.count<i?` (~${Math.round((i-r.count)*(Date.now()-a)/r.count/1e3)}s remaining)`:``;u+=`[${r.count}/${i}] Failed "${d.entry.name}" from ${e}: ${f.error}${t}\n`;continue}let{skillPath:p,skillName:m}=f,h=Date.now(),g=await Li(p,m,n,s,!1);r.count++;let _=((Date.now()-h)/1e3).toFixed(1),v=(Date.now()-a)/r.count,y=Math.round((i-r.count)*v/1e3),b=r.count<i?` (~${y}s remaining)`:``;g.ok?(l.push({ok:!0,name:m}),u+=`[${r.count}/${i}] Installed "${m}" from ${e} (${_}s)${b}\n`):(l.push({ok:!1,name:m,error:g.error}),u+=`[${r.count}/${i}] Failed "${m}" from ${e}: ${g.error}${b}\n`)}return{errors:[],results:l,output:u}}async function fK(e,t,n,r,i,a,o,s,c,l){let u=await Si(c),d=[],f=``;for(let c of t){let t=c.entry.source;i.count++;let p=i.count<a?` (~${Math.round((a-i.count)*(Date.now()-o)/i.count/1e3)}s remaining)`:``;if(t.installAll&&t.path){let t=await uK(c,e,n,r,u,s,l,i.count,a,o);d.push(...t.results),f+=t.line;continue}let m=t.path?t.path.replace(/^\/|\/$/g,``):c.entry.name,h=t.skill||c.entry.name,g=await Ii(n,r,m,h,l,u,!1);g.exitCode===0?(f+=`[${i.count}/${a}] Installed "${h}" from ${e}${p}\n`,d.push({ok:!0,name:h})):(f+=`[${i.count}/${a}] Failed "${h}" from ${e}: ${g.stderr.trim()}${p}\n`,d.push({ok:!1,name:h,error:g.stderr.trim()}))}return{errors:[],results:d,output:f}}function pK(e,t,n){let r=``;for(let i of e){if(i.status===`rejected`){t.push(`upskill: unexpected error: ${i.reason}`);continue}r+=i.value.output;for(let e of i.value.errors)t.push(e);for(let e of i.value.results)e.ok?n.push(e.name):e.error&&t.push(`upskill: ${e.error}`)}return r}async function mK(e,t,n){let r=Date.now(),i=(e,t=[])=>({installedNames:[],errors:t,skipped:e,log:``,elapsedSeconds:(Date.now()-r)/1e3}),a=null;if(n)a=rK(n);else try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);a=rK(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([sK(t),oK(t,a.company),nK(e)]);o=aK(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${Oi}: ${e instanceof Error?e.message:String(e)}`])}let c=eK(o,a).filter(e=>!s.has(e.entry.name));if(c.length===0)return i(`all-installed`);let l=new Map;for(let e of c){let t=e.entry.source.repo,n=l.get(t);n?n.push(e):l.set(t,[e])}let u=c.length,d={count:0},f=[],p=[],m=``;m=pK(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await Ei(a,o,t);return c.status===`error`?fK(n,i,a,o,d,u,r,s,t,e):dK(n,i,_i(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await ji(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function hK(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let gK,_K;async function vK(e){if(gK)return gK;if(_K!==void 0)return _K;_K=(async()=>{let t;try{t=await e(xi,{headers:{Accept:`application/json`}})}catch(e){throw Error(Di(e,xi))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=Lt(t.body),r=Array.isArray(n)?n:n.skills??[];return gK=r,r})();try{return await _K}catch(e){throw _K=void 0,e}}async function yK(e,t){let n=await vK(t),r=e.trim().toLowerCase();return r?n.filter(e=>[e.title??``,e.name??``,e.description??``,e.hostname??``,...e.tags??[]].join(` `).toLowerCase().includes(r)).map(e=>({name:e.slug,displayName:e.title||e.name||e.task||e.slug,summary:e.description||``,source:`browseSh`,qualityScore:null,installHint:`upskill browse:${e.hostname}/${e.task}`,sourceRepo:e.hostname})):[]}const bK=/^[A-Za-z0-9._-]+$/;function xK(e){return!e||e===`.`||e===`..`?!1:bK.test(e)}function SK(e){let t;if(e.startsWith(`browse:`))t=e.slice(7);else{let n=e.match(/^https:\/\/browse\.sh\/skills\/([^/?#]+)\/([^/?#]+?)\/?$/);n&&(t=`${n[1]}/${n[2]}`)}if(!t)return null;let n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n),i=t.slice(n+1);if(!r||!i||i.includes(`/`)||!xK(r)||!xK(i))return null;let a=hK(r);return xK(a)?{hostname:a,task:i}:null}function CK(e,t){let n=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(n)for(let e of n[1].split(/\r?\n/)){let n=e.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!n||n[1]!==t)continue;let r=n[2].trim();return(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))&&(r=r.slice(1,-1)),r||void 0}}function wK(e,t){let n=e.updated?` · updated ${e.updated}`:``;return[`> [!NOTE] **Imported from browse.sh** — original slug: \`${t}\``,`>`,"> **SLICC adaptation:** use `playwright-cli` — you are running inside the user's real browser session, so the bot-detection workarounds the upstream skill assumes are usually unnecessary.",`>`,`> Source: <https://browse.sh/skills/${t}>${n}`].join(`
|
|
5448
5448
|
`)}function TK(e){return e.replace(/(?:^|\n)> \[!NOTE\] \*\*Imported from browse\.sh\*\*[\s\S]*?(?:\n\n|$)/,`
|
|
5449
5449
|
`)}function EK(e,t){let n=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return n?`${n[1]}${n[2]||`
|
|
@@ -5550,7 +5550,7 @@ Examples:
|
|
|
5550
5550
|
skill list
|
|
5551
5551
|
skill info bluebubbles
|
|
5552
5552
|
skill read bluebubbles
|
|
5553
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5553
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-CN522iKp.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${kK()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:jK(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5554
5554
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:MK(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
|
|
5555
5555
|
`,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+`
|
|
5556
5556
|
`,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 FK=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&Yn(e),error:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters`,apply:(e,t)=>{e.branch=t}},{names:[`--from`],validate:e=>Pi(e)!==null,error:`upskill: --from requires a GitHub source (owner/repo, owner/repo@branch, or a github.com URL)`,apply:(e,t)=>{e.from=t}},{names:[`--path`,`-p`],validate:e=>Qn(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 IK(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=FK.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 LK(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function RK(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 zK(e,t,n,r){let i=await RK(e,t);return Ti(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?LK(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function BK(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await zK(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 Ci(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 VK(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 Si(t),d=await Ni(s,c,o.ref,u,!0);if(d&&r.sha===d&&await HK(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await UK(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 BK(e,`${bi}/${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 JK(e,{changes:h,writes:g,removals:_}),await Ri(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 HK(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 UK(e,t,n,r,i,a,o){let s=await Ei(e,t,a,i??`main`);if(s.status===`ok`){let i=_i(s.files),a=n||WK(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:qK(i,a),path:a}}try{return{files:KK(GK(await wi(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 WK(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 GK(e){return new Map([...e].filter(([e])=>vi(e)))}function KK(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function qK(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);vi(e)&&r.set(e,i)}return KK(r)}async function JK(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 YK(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 DK(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${bi}/${n}/SKILL.md`,u=await RK(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&TK(new TextDecoder().decode(u))===TK(c.content);if(LK(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${bi}/${n}`,{recursive:!0}),await e.writeFile(l,d),await Ri(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function XK(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 ZK(e,t,n,r){let i=Pi(t);return i?{version:1,kind:`github`,source:`${i.owner}/${i.repo}`,skill:e,ref:r??i.branch,path:n??i.path,installed:new Date().toISOString()}:null}async function QK(e,t,n){if(t.length===0)return{targets:await Vi(e),missing:[]};let r=[],i=[];for(let a of t){let t=await Mi(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?ZK(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 $K(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
@@ -5584,7 +5584,7 @@ Nothing to update — all skills are current.
|
|
|
5584
5584
|
`,{stdout:s,stderr:``,exitCode:0}}function pq(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5585
5585
|
`,exitCode:1}:Yn(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
|
|
5586
5586
|
`,exitCode:1}}function mq(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`||!Qn(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
|
|
5587
|
-
`,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=pq(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 hq(e){let t=await(await import(`./skills-
|
|
5587
|
+
`,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=pq(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 hq(e){let t=await(await import(`./skills-CN522iKp.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${kK()}`,stderr:``,exitCode:0}:{stdout:jK(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function gq(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-CN522iKp.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 Mi(n,t),a=i?Fi(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:MK(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+`
|
|
5588
5588
|
`,stderr:``,exitCode:0}}async function _q(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 Li(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 vq(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 Ii(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 yq(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await Ii(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 bq(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 xq(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await Si(r),l=await zi(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:bq(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:bq(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 Ei(i,a,r,o);if(e.status===`ok`){let r=await Ni(i,a,o,c),s=await _q(u,i,a,_i(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 vq(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await yq(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 ji()),{stdout:p,stderr:m,exitCode:+!!m}}async function Sq(e,t,n,r){switch(e[0]){case`tabs`:return dq(t,n,r,e.includes(`--json`));case`recommendations`:return fq(t,n,e.includes(`--install`));case`update`:case`upgrade`:return tq(e.slice(1),t,n);case`list`:return hq(t);case`info`:case`read`:return gq(e[0],e[1],t);case`search`:return wq(e,n);default:return null}}function Cq(e,t,n){return H(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return NK();let a=await Sq(r,e,t,n);if(a)return a;let o=mq(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return NK();if(o.sourceRef.startsWith(`tessl:`))return Tq(o.sourceRef,o.force,e,t);let s=SK(o.sourceRef);if(s)return OK(s.hostname,s.task,e,t,o.force);let c=Pi(o.sourceRef);return c?xq(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 wq(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?oq(a,t,i):NK()}async function Tq(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5589
5589
|
`,exitCode:1};let a=await rq(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await Si(r);return Ii(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function Eq(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5590
5590
|
|
|
@@ -6987,7 +6987,7 @@ Common base URLs:
|
|
|
6987
6987
|
llama.cpp http://localhost:8080/v1
|
|
6988
6988
|
vLLM http://localhost:8000/v1
|
|
6989
6989
|
Jan http://localhost:1337/v1
|
|
6990
|
-
`}function _oe(){return H(Z6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:goe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
6990
|
+
`}function _oe(){return H(Z6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:goe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-DVze_FfU.js`),{verifyConnection:a}=await import(`./local-llm-CL0LbvPc.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(Z6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6991
6991
|
`,exitCode:1};let c=await a(s,t(Z6)??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(`
|
|
6992
6992
|
`)+`
|
|
6993
6993
|
`,exitCode:1}}if(o===`discover`){let e=n(Z6)??``;return i(Z6,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(`
|
|
@@ -7031,20 +7031,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
7031
7031
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
7032
7032
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
7033
7033
|
short name resolves on the PATH.
|
|
7034
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return t8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return t8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return t8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
7034
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return t8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return t8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return t8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-Cehy36To.js`).then(e=>e.r);if(await a(i,t.fs))return t8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BTUV7dbh.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 woe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>o8(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 Uoe(i,t);let m=await l8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-CflcvITG.js`);e({name:i,serverUrl:r,auth:u})}return e8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${$6}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
7035
7035
|
`)+`
|
|
7036
|
-
`)}async function woe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
7037
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
7036
|
+
`)}async function woe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r),c=await Voe(r.oauthFetchImpl),l=r.oauthLauncher??await s8(),u=await i(e,n,c);Q6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await na(),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 Toe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return e8(`usage: mcp list
|
|
7037
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-CflcvITG.js`);await n();let{listServers:r}=await import(`./store-Cehy36To.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return e8("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 e8(n8(o))}function n8(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(`
|
|
7038
7038
|
`)+`
|
|
7039
7039
|
`}async function Eoe(e,t){if(wZ(e))return e8(`usage: mcp search <query>
|
|
7040
7040
|
|
|
7041
7041
|
Case-insensitive substring search across the cached tools of every
|
|
7042
7042
|
registered MCP server. Matches tool name OR description and prints a
|
|
7043
7043
|
table of (server, tool, description, match-field) rows.
|
|
7044
|
-
`);if(e.length===0)return t8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
7045
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
7044
|
+
`);if(e.length===0)return t8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-CflcvITG.js`);await i();let{listServers:a}=await import(`./store-Cehy36To.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return e8("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 e8(`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,Doe(e.description),e.match]);return e8(n8(l))}function Doe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Ooe(e,t){if(e.length===0||wZ(e))return e.length===0?t8(`mcp delete: expected <name>`):e8(`usage: mcp delete <name>
|
|
7045
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-CflcvITG.js`);await r(n);let{deleteServer:a}=await import(`./store-Cehy36To.js`).then(e=>e.r),o=await a(n,t.fs);await Woe(n,t),await Goe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){Q6.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?t8(`mcp delete: no server, alias, or account found for "${n}"`):e8([`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(`
|
|
7046
7046
|
`)+`
|
|
7047
|
-
`)}async function koe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?t8(`mcp invoke: expected <name>`):e8(joe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
7047
|
+
`)}async function koe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?t8(`mcp invoke: expected <name>`):e8(joe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-CflcvITG.js`);await i(n);let{getServer:a}=await import(`./store-Cehy36To.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return t8(`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 e8(Moe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return t8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=Aoe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return e8(Noe(n,l));let p=Poe(d,l.inputSchema);if(!p.ok)return t8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BTUV7dbh.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>o8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=Roe(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function Aoe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=r8(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=r8(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 r8(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 joe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
7048
7048
|
|
|
7049
7049
|
mcp invoke <name> List tools on <name>.
|
|
7050
7050
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -7074,7 +7074,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
7074
7074
|
|
|
7075
7075
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
7076
7076
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
7077
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
7077
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-CflcvITG.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-Cehy36To.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return t8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BTUV7dbh.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>o8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return t8(`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 l8(n,d,t);return e8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function Boe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return e8(`usage: mcp auth <name> [--silent | --interactive]
|
|
7078
7078
|
|
|
7079
7079
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
7080
7080
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7086,7 +7086,7 @@ Options:
|
|
|
7086
7086
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7087
7087
|
directly. Use after revoking a refresh token or
|
|
7088
7088
|
when the AS no longer accepts the cached one.
|
|
7089
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return t8(`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 t8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7089
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return t8(`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 t8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-CflcvITG.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-Cehy36To.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return t8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return t8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return t8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-CDa657V5.js`).then(e=>e.r),f=d(u);if(!f)return t8(`mcp auth: provider "${u}" is not registered`);if(a)return await a8(r,f,t);if(!f.onSilentRenew)return i?t8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await a8(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 t8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);Q6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?e8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?t8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await a8(r,f,t)}async function a8(e,t,n){if(!t.onOAuthLogin)return t8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await s8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?e8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):t8(`mcp auth: interactive login for "${e}" did not complete`)}async function o8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-CDa657V5.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){Q6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function s8(){let{createOAuthLauncher:e}=await import(`./oauth-service-Bbrrl8Mr.js`);return e()}async function Voe(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-n2pCvcgW.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 c8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-QvKcM1y9.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 Hoe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7090
7090
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7091
7091
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7092
7092
|
const escape = (s) => {
|
|
@@ -7100,7 +7100,7 @@ const r = await exec(cmd);
|
|
|
7100
7100
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7101
7101
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7102
7102
|
process.exit(r.exitCode || 0);
|
|
7103
|
-
`}async function Uoe(e,t){let n=await c8(t.fs);await n.mkdir($6,{recursive:!0}),await n.writeFile(`${$6}/${e}.jsh`,Hoe(e)),t.scriptCatalog?.invalidateJsh()}async function Woe(e,t){let n=await c8(t.fs),r=`${$6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Q6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Goe(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
7103
|
+
`}async function Uoe(e,t){let n=await c8(t.fs);await n.mkdir($6,{recursive:!0}),await n.writeFile(`${$6}/${e}.jsh`,Hoe(e)),t.scriptCatalog?.invalidateJsh()}async function Woe(e,t){let n=await c8(t.fs),r=`${$6}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){Q6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function Goe(e,t){let{removeAppSprinkles:n}=await import(`./apps-BwAyOelR.js`);await n(e,t.fs)}async function l8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-BwAyOelR.js`);return(await r(e,t,n.fs)).length}catch(t){return Q6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function u8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function d8(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 Koe(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 qoe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function Joe(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 Yoe(e){let t=[`total: ${d8(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(`${d8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${Koe(e)}`)}return`${t.join(`
|
|
7104
7104
|
`)}\n`}function Xoe(e={}){return H(`meminfo`,async t=>{let n=Joe(t);if(`error`in n)return u8(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
7105
7105
|
|
|
7106
7106
|
Usage:
|
|
@@ -7126,7 +7126,7 @@ Options:
|
|
|
7126
7126
|
-h, --help Show this help message
|
|
7127
7127
|
`}function ese(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function m8(e){return`$${e.toFixed(2)}`}const tse=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function nse(e){let t=`${e.id} ${e.name??``}`;return!tse.test(t)}function rse(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 ise(e){let t=new Map;for(let n of e){let e=rse(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function ase(e,t,n,r,i){let a=i?Qoe(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 ose(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=`${m8(e.cost.input)} / ${m8(e.cost.output)}`,a=`${ese(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(`
|
|
7128
7128
|
`)+`
|
|
7129
|
-
`}function sse(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-
|
|
7129
|
+
`}function sse(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-DVze_FfU.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:$oe(),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.
|
|
7130
7130
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await Zoe(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(nse);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>ase(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=ise(n)),w.push(...n),!l){let t=i(e);T.push(ose(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7131
7131
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7132
7132
|
`);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(`
|
|
@@ -7166,7 +7166,7 @@ Examples:
|
|
|
7166
7166
|
oauth-domain add adobe '*.da.live'
|
|
7167
7167
|
oauth-domain list adobe
|
|
7168
7168
|
oauth-domain remove adobe admin.da.live
|
|
7169
|
-
`}function _se(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:g8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
7169
|
+
`}function _se(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:g8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-DVze_FfU.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(`
|
|
7170
7170
|
`)+`
|
|
7171
7171
|
`,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)
|
|
7172
7172
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7238,7 +7238,7 @@ Examples:
|
|
|
7238
7238
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7239
7239
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7240
7240
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7241
|
-
`}function wse(){return H(`oauth-token`,Tse)}async function Tse(e,t){let n=await import(`./account-store-
|
|
7241
|
+
`}function wse(){return H(`oauth-token`,Tse)}async function Tse(e,t){let n=await import(`./account-store-B92t9dbf.js`).then(e=>e.r),r=await import(`./providers-CDa657V5.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Cse(),stderr:``,exitCode:0};if(e.includes(`--list`))return Hse(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return Fse(e);if(e.includes(`--renew`))return Ise(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return Lse(e,t);let i=Ese(e);if(!i.ok)return i.result;let a=Dse(e),o=Ose(e,n,r);if(!o.ok)return o.result;let s=kse(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await Ase(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return jse(o.value,s.value,i.value,n.getOAuthAccountInfo)}function Ese(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:w8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function Dse(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function Ose(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:w8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(v8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>v8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:w8(`oauth-token: no OAuth providers configured`)}}function v8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function kse(e,t){let n=t(e);return n?v8(n)?{ok:!0,value:n}:{ok:!1,result:w8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:w8(`oauth-token: unknown provider "${e}"`)}}async function Ase(e,t,n,r){let i=n(e);return i&&!i.expired?y8(e,i,r):!i?.expired||!t.onSilentRenew||!await Pse(t.onSilentRenew)?null:y8(e,n(e),r)}function y8(e,t,n){return n&&!Sse(t?.scopes,n)?null:b8(e,t?.maskedValue)}function b8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:w8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function jse(e,t,n,r){try{let i=await Mse(e,t,n);return i.error?i.error:Nse(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),w8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),w8(`oauth-token: login failed: ${n}`))}}async function Mse(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-Bbrrl8Mr.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:w8(`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-Bbrrl8Mr.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:w8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function Nse(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),w8(`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?b8(e,r.maskedValue):r?.token?w8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),w8(`oauth-token: login completed but no token was saved`))}async function Pse(e){try{return await e()!==null}catch{return!1}}function x8(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 Fse(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-CDa657V5.js`).then(e=>e.r),o=x8(e,n,i,a);if(!o)return w8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return w8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return w8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return w8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return w8(`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 Ise(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-B92t9dbf.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-CDa657V5.js`).then(e=>e.r),a=x8(e,t,r,i);if(!a)return w8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return w8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return w8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${S8(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: ${S8(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(`
|
|
7242
7242
|
`)+`
|
|
7243
7243
|
`,stderr:``,exitCode:+!u}}function S8(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 Lse(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-BIKnTjZm.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-Bbrrl8Mr.js`),i=await Rse(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return w8(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return w8(`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}:w8(`oauth-token: intercept timed out or was cancelled`)}function Rse(e,t){let n=e.indexOf(`--from-file`);return n>=0?zse(e[n+1],t):Bse(e)}async function zse(e,t){if(!e)return{ok:!1,result:w8(`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:w8(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function Bse(e){let t=C8(e,`--authorize-url`),n=C8(e,`--redirect-pattern`);if(!t)return{ok:!1,result:w8(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:w8(`oauth-token: --redirect-pattern is required`)};let r=Vse(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 Vse(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:w8(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:w8(`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 C8(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function w8(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function Hse(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7244
7244
|
`,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(`
|
|
@@ -7356,7 +7356,7 @@ Examples:
|
|
|
7356
7356
|
plugin list
|
|
7357
7357
|
plugin info my-plugin
|
|
7358
7358
|
plugin remove my-plugin
|
|
7359
|
-
`}function bce(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return B8(yce());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Sce(i,a,e);case`list`:case`ls`:return await Ece(i,e);case`info`:return await Dce(i,e);case`validate`:return await Oce(i,a,e);case`remove`:case`rm`:case`delete`:return await kce(i,e);default:return V8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return V8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function H8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
7359
|
+
`}function bce(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return B8(yce());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Sce(i,a,e);case`list`:case`ls`:return await Ece(i,e);case`info`:return await Dce(i,e);case`validate`:return await Oce(i,a,e);case`remove`:case`rm`:case`delete`:return await kce(i,e);default:return V8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return V8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function H8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-QvKcM1y9.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 U8(e,t,n){let r=Ace(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-CdvlpkjZ.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 xce(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function W8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${z8}/${t.map(xce).join(`--`)}`}async function G8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-DluIBUmq.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 K8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Sce(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return B8(`usage: plugin install <path|repo>
|
|
7360
7360
|
|
|
7361
7361
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
7362
7362
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -7367,19 +7367,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
7367
7367
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
7368
7368
|
standard skills discovery, and each supported streamable-http MCP server
|
|
7369
7369
|
is registered in the MCP store as "<plugin>:<server>".
|
|
7370
|
-
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return V8(`plugin install: expected <path|repo>`);let i=await H8(n),a=await U8(r[0],t,i);if(a.kind===`error`)return V8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return V8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=W8(a.ref),s=a.ref.display;let e=await G8(a.ref,o,i,n.fetch);if(e)return V8(`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 K8(i,o),V8(`plugin install: plugin at ${s??o} was rejected:\n${q8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
7370
|
+
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return V8(`plugin install: expected <path|repo>`);let i=await H8(n),a=await U8(r[0],t,i);if(a.kind===`error`)return V8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return V8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=W8(a.ref),s=a.ref.display;let e=await G8(a.ref,o,i,n.fetch);if(e)return V8(`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 K8(i,o),V8(`plugin install: plugin at ${s??o} was rejected:\n${q8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-BcwDrsU-.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await K8(i,o),V8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await Tce(u,n),g=await wce(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),B8(Cce(u,h,g,s??o,l.diagnostics))}function Cce(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:`,q8(i)),c.join(`
|
|
7371
7371
|
`)+`
|
|
7372
|
-
`}async function wce(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-
|
|
7373
|
-
`);let{listInstalledPlugins:n}=await import(`./store-
|
|
7372
|
+
`}async function wce(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-Cehy36To.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 Tce(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-Cehy36To.js`).then(e=>e.r),{McpClient:a}=await import(`./client-BTUV7dbh.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 Ece(e,t){if(e.includes(`--help`)||e.includes(`-h`))return B8(`usage: plugin list
|
|
7373
|
+
`);let{listInstalledPlugins:n}=await import(`./store-BcwDrsU-.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return B8("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 B8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
|
|
7374
7374
|
`)+`
|
|
7375
7375
|
`)}async function Dce(e,t){if(e.length===0||wZ(e))return e.length===0?V8(`plugin info: expected <name>`):B8(`usage: plugin info <name>
|
|
7376
|
-
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-
|
|
7376
|
+
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-BcwDrsU-.js`),i=await r(n,t.fs);if(!i)return V8(`plugin info: no installed plugin named "${n}"`);let a=await H8(t),{loadPluginFromDirectory:o}=await import(`./loader-sgPDMLWT.js`),s=await o(a,i.root);if(!s.ok)return V8(`plugin info: plugin at ${i.root} no longer loads:\n${q8(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:`,q8(s.diagnostics)),B8(u.join(`
|
|
7377
7377
|
`)+`
|
|
7378
7378
|
`)}async function Oce(e,t,n){if(e.length===0||wZ(e))return e.length===0?V8(`plugin validate: expected <path|repo>`):B8(`usage: plugin validate <path|repo>
|
|
7379
7379
|
`);let r=await H8(n),i=await U8(e[0],t,r);if(i.kind===`error`)return V8(`plugin validate: ${i.message}`);let a,o=null;if(i.kind===`github`){if(!n.fetch)return V8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);o=`/tmp/.plugin-validate/${W8(i.ref).split(`/`).pop()}`;let e=await G8(i.ref,o,r,n.fetch);if(e)return V8(`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 K8(r,o)}if(!c.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${q8(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:`,q8(c.diagnostics)),B8(d.join(`
|
|
7380
7380
|
`)+`
|
|
7381
7381
|
`)}async function kce(e,t){if(e.length===0||wZ(e))return e.length===0?V8(`plugin remove: expected <name>`):B8(`usage: plugin remove <name>
|
|
7382
|
-
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-
|
|
7382
|
+
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-BcwDrsU-.js`),a=await r(n,t.fs);if(!a)return V8(`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-Cehy36To.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(`${z8}/`);return s&&await K8(await H8(t),a.root),B8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
|
|
7383
7383
|
`)+`
|
|
7384
7384
|
`)}function Ace(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 q8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
7385
7385
|
`)}const J8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],jce=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Mce={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function Nce(e={}){return H(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return Gce();let n=e.processManager??Pce();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -8991,9 +8991,9 @@ pass --wait to block and print the full result.
|
|
|
8991
8991
|
`)}async function ahe(e,t){let n=rhe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return w9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:ihe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function ohe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return D9(n,t.getScoops);if(i.jid===t.scoop.jid)return{content:`Cannot feed yourself.`,isError:!0};if(i.parentJid===null)return{content:`Cannot feed a cone (root unit).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),w9.info(`Fed scoop`,{target:i.folder,promptLength:r.length}),{content:`Task sent to ${i.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function she(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>the(t,e.getScoopTabState)).join(`
|
|
8992
8992
|
`)}`}}function che({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,allowedCommands:o,thinkingLevel:s,backgroundAfterSeconds:c,parentJid:l}){return{name:e,folder:t,trigger:`@${t}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},visiblePaths:i??[`/workspace/`],writablePaths:a??[`/scoops/${t}/`,`/shared/`],...o?{allowedCommands:o}:{},...s?{thinkingLevel:s}:{},...c===void 0?{}:{backgroundAfterSeconds:c}},configSchemaVersion:2,parentJid:l}}async function lhe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return w9.error(`Auto-feed failed`,{name:n,error:t}),{content:`Scoop "${n}" created as "${r}" but the initial task could not be sent: ${t}. Use feed_scoop to retry.`,isError:!0}}return{content:`Scoop "${n}" created as "${r}" and task sent. It is now working on it.`}}async function uhe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c,background_after:l}=e,u=Qme(c);if(!u.ok)return{content:u.content,isError:u.isError};let d=$me(l);if(!d.ok)return{content:d.content,isError:!0};let f=ehe(r,t.resolveModelSelection);if(!f.ok)return{content:f.content,isError:f.isError};let p=Zme(n);try{let e=che({name:n,folder:p,model:f.modelId,modelProviderId:f.providerId,visiblePaths:a,writablePaths:o,allowedCommands:s,thinkingLevel:u.level,backgroundAfterSeconds:d.seconds,parentJid:t.scoop.jid}),r=await t.onScoopScoop(e);return w9.info(`Scoop created`,{name:n,folder:p}),i&&t.onFeedScoop?lhe(r,i,n,p,t.onFeedScoop):{content:`Scoop "${n}" created as "${p}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function dhe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return D9(n,t.getScoops);if(r.jid===t.scoop.jid)return{content:`Cannot drop yourself.`,isError:!0};if(r.parentJid===null)return{content:`Cannot drop a cone (root unit).`,isError:!0};try{return await t.onDropScoop(r.jid),w9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function O9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function k9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function fhe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return O9();let{resolved:r,unknown:i}=T9(n,t.getScoops);return r.length===0?k9(i):(t.onMuteScoops(r.map(e=>e.jid)),w9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function phe(e,t){if(e.length===0)return[`No stashed completions.`];let n=[``,`Stashed completions:`];for(let r of e){let e=t.get(r.jid)??r.jid;n.push(`--- ${e} ---`),r.notificationPath&&n.push(`VFS path: ${r.notificationPath}`),n.push(r.summary)}return n}async function mhe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return O9();let{resolved:r,unknown:i}=T9(n,t.getScoops);if(r.length===0)return k9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);w9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...phe(s,o)),{content:c.join(`
|
|
8993
8993
|
`)}}function hhe(e,t){return!Array.isArray(e)||e.length===0?O9():t!==void 0&&(typeof t!=`number`||!Number.isFinite(t)||t<0)?{content:`timeout_ms must be a non-negative finite number (or omitted).`,isError:!0}:null}function ghe(e,t,n,r){return`scoop_wait scheduled for: ${e}${r===void 0?` (no timeout)`:` (timeout: ${r}ms)`}.${t.length>0?` Unknown (skipped): ${t.join(`, `)}.`:``}${n?` Dropped before schedule (skipped): ${n}.`:``} Continue with other work — a 'scoop-wait' lick will be delivered when all listed scoops complete or the timeout fires.`}async function _he(e,t){let{scoop_names:n,timeout_ms:r}=e,i=hhe(n,r);if(i)return i;let{resolved:a,unknown:o}=T9(n,t.getScoops);if(a.length===0)return k9(o);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return w9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:ghe(u,o,d,r)}}function vhe(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`:e.persistError?`Approved (always) but could NOT persist a rule (${e.persistError}). The current action is allowed; future occurrences will prompt again.`:`Approved (always) — no persistable rule applied for this request.`:`Approved (once) — the current action proceeds; future ones will prompt again.`}async function yhe(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(w9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:vhe(e,!!r)}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_confirm failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function bhe(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(w9.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_dismiss failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function xhe(e){let t=e.onListSudoRequests();return t.length===0?{content:`No pending sudo requests.`}:{content:`Pending sudo requests:\n${t.map(t=>{let n=e.getScoops().find(e=>e.jid===t.scoopJid)?.folder??t.scoopJid,r=t.request.suggestedPattern?` (suggested: ${t.request.suggestedPattern})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
|
|
8994
|
-
`)}`}}async function She(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),w9.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function Che(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>nhe(t,e)}}function whe(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...E9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>ahe(t,e)}}function The(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>ohe(t,e)}}function Ehe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>she(e)}}function Dhe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...kh],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`}},required:[`name`]},execute:t=>uhe(t,e)}}function Ohe(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>dhe(t,e)}}function khe(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>fhe(t,e)}}function Ahe(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>mhe(t,e)}}function jhe(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to wait for (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>_he(t,e)}}function Mhe(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>yhe(t,e)}}function Nhe(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>bhe(t,e)}}function Phe(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>xhe(e)}}function Fhe(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>She(t,e)}}function Ihe(e){let t=[],n=xh(e.scoop);return vh(e.scoop)||(t.push(Che(e)),e.onSudoRequest&&t.push(whe(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(The(e)),t.push(Ehe(e)),e.onScoopScoop&&t.push(Dhe(e)),e.onDropScoop&&t.push(Ohe(e)),e.onMuteScoops&&t.push(khe(e)),e.onUnmuteScoops&&t.push(Ahe(e)),e.onScheduleScoopWait&&t.push(jhe(e)),e.onSudoResolve&&(t.push(Mhe(e)),t.push(Nhe(e))),e.onListSudoRequests&&t.push(Phe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Fhe(e))),t}const A9=r(`scoop-context`);function j9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!ree(t).includes(`xhigh`)?`high`:e}function Lhe(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function Rhe(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function M9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function N9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function zhe(e,t,n){return e?{...n}:{...n,HOME:`/scoops/${t}/home`,USER:t,PATH:[`/usr/bin`,`/scoops/${t}/workspace/skills`,`/scoops/${t}/workspace/bin`,...Nr].join(`:`)}}var Bhe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;sessionPersistTimer=null;promptTurnCount=0;boundExceededNote=null;wallClockBoundTimer=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;liveBashJobPids=new Set;sessionStore=null;sessionId;sessionCreatedAt=0;imageRecoveryActive=!1;compactFn=null;getCompactionApiKey=null;overflowRecoveryAttempted=!1;overflowRecoveryActive=!1;overflowRecoveryPromise=null;overflowRecoveryEscalated=!1;coneJid;unit;ownerKind;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.unit=Rg(e),this.ownerKind=qg(e),this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,{policy:t}=this.unit,n=t.approvalAuthority===`user`,r=this.scoop.folder,i=this.callbacks.onSudoRequest,a=n||!i?e.getBroker():{requestApproval:e=>i(e)},o=n?()=>e.getPolicy():()=>e.getPolicyForScoop(r),s=t.sudoDefaultDisposition,c=e.getShellConfig(),l=t.persistCommandGrants?c.persistCommandGrant:async()=>{};return{broker:a,getPolicy:o,defaultDisposition:s,shellConfig:{...c,broker:a,getPolicy:o,defaultDisposition:s,persistCommandGrant:l}}}async initShellAndSkills(){let e=this.unit.workspace.root,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.unit.policy.filesystem.kind===`full-workspace`&&await yx(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await rS(),i=this.buildSudoWiring(),a=i?uee(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs,o=zhe(this.unit.policy.filesystem.kind===`full-workspace`,this.scoop.folder,r);return this.shell=new u9({fs:a,cwd:e,env:Object.keys(o).length>0?o:void 0,browserAPI:t,webhook:{hasLocalNodeServer:vt,getLeaderStatus:bn},jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>this.unit.display.role===`child`,sudo:i?.shellConfig,scrubProgressLabel:St(),processManager:this.processManager??void 0,processOwner:{kind:this.ownerKind,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),A9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await hx(n,this.skillsDir)}}async buildTools(e){let t=Ihe({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,resolveModelSelection:ke,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...qme(e),Vme(this.shell,this.fs,this.unit.workspace.scratch,{defaultBackgroundAfterSeconds:this.scoop.config?.backgroundAfterSeconds,targetScoop:this.unit.display.role===`child`?this.scoop.folder:void 0,jobHost:{spawn:e=>this.spawnBashJob(e)},scrubOutput:St(),fireLick:e=>{let t=globalThis.__slicc_lick_handler;if(!t){A9.warn(`No lick handler for background bash completion`,{folder:this.scoop.folder});return}t(e)}}),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:St()};return this.processManager?Je(n,{processManager:this.processManager,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Je(n,void 0,r)}async loadMemories(){let e=this.unit.workspace.memoryPath,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.unit.policy.canWriteSharedMemory)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=bt(e.messages);return this.sessionCreatedAt=e.createdAt,A9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){A9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}getModelApiKey(){let e=this.scoop.config?.modelProviderId;return e?tee(e):ct()}async buildSessionHelpers(e){let t=await vee(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?Wt(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):Wt(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=()=>this.getModelApiKey()??void 0,a=this.unit.policy.canWriteSharedMemory&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:this.getModelApiKey()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:Ve({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:i,headers:r,onMemoryUpdates:a,shouldExtractMemories:()=>!Ma(`agentic-memory`),onCompactionStateChange:e=>{this.callbacks.onCompactionStateChange?.(e)}}),getCompactionApiKey:i}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);A9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!this.getModelApiKey()){A9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId,o=this.scoop.config?.modelProviderId,s=a?L(a,o):he(),c=this.unit.display.role===`primary`?`Cone`:`Scoop "${this.scoop.name}"`;if(console.log(`[model] ${c} using model: ${s.id} (provider: ${s.provider})`),o&&(s.id!==a||!_e(s,o)))throw Error(`Configured model ${o}:${a} resolved to ${s.provider}:${s.id}; refusing to run on a different model`);!o&&a&&s.id!==a&&A9.warn(`Configured scoop model did not resolve; using resolved model instead`,{folder:this.scoop.folder,configuredModelId:a,resolvedModelId:s.id});let l=this.buildSystemPrompt(i,r,t),u=await this.restoreSession(),{streamWithSessionId:d,compactFn:f,getCompactionApiKey:p}=await this.buildSessionHelpers(s);if(this.disposed)return;this.compactFn=f,this.getCompactionApiKey=p;let m=j9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,s);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new lh({initialState:{model:s,tools:n,systemPrompt:l,messages:u,thinkingLevel:m},getApiKey:()=>this.getModelApiKey()??void 0,transformContext:f,streamFn:d,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),A9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);A9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=this.scoop.config?.modelProviderId??``;try{e||=ne()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t,n=!1){let r=this.agent.state?.isStreaming??!1;if(this.isProcessing||r){A9.info(`Queueing prompt via ${n?`steer`:`followUp`} while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:r});let i={role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()};return n?this.agent.steer(i):this.agent.followUp(i),!0}return!1}spawnBashJob(e){let t=this.processManager;if(!t)return null;let n=e=>{this.liveBashJobPids.delete(e)},r=t.spawn({kind:`shell`,argv:[`bash`,`-c`,e],cwd:this.unit.workspace.root,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},ppid:this.currentTurnProcess?.pid});return this.liveBashJobPids.add(r.pid),{pid:r.pid,signal:r.abort.signal,kill:()=>{n(r.pid),t.signal(r.pid,`SIGKILL`)},exit:e=>{n(r.pid),t.exit(r.pid,e)}}}reapBashJobs(){let e=this.processManager;if(!e||this.liveBashJobPids.size===0)return;let t=[...this.liveBashJobPids];this.liveBashJobPids.clear(),A9.info(`Reaping background bash jobs on dispose`,{folder:this.scoop.folder,pids:t});for(let n of t)e.signal(n,`SIGKILL`)}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.unit.workspace.root,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return Rhe(e)?(A9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),Dr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return Ha(e)?(A9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),Wa(this.unit.completion.mode===`interactive`),Dr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!M9(e)||t>=n)return!1;let a=r*2**(t-1);return A9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await N9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;A9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),Dr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.wallClockBoundTimer!==null&&(clearTimeout(this.wallClockBoundTimer),this.wallClockBoundTimer=null),this.boundExceededNote!==null&&(this.callbacks.onError(`agent run terminated: ${this.boundExceededNote}`),this.boundExceededNote=null),(n||r.aborted)&&this.persistSessionNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n,r){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{if(await e.prompt(t,n),this.disposed||r.aborted)return null;let i=this.overflowRecoveryPromise;return i!==null&&(await i,this.overflowRecoveryPromise===i&&(this.overflowRecoveryPromise=null),this.disposed||r.aborted)?null:this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:!await this.handleRetryableError(a,t,n,r,i)&&(A9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:M9(a)}),!!(t<n&&(await N9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[],n){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t,n?.steer))return;let r=this.agent;this.promptAbortController?.abort();let i=new AbortController;this.promptAbortController=i;let a=i.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflowRecoveryAttempted=!1,this.overflowRecoveryActive=!1,this.overflowRecoveryPromise=null,this.overflowRecoveryEscalated=!1;let o=this.registerTurnProcess(e,i);this.currentTurnProcess=o,this.armRunBounds();let s=null;try{if(s=await this.runAgentWithRetries(r,e,t,a),s&&!this.disposed&&!a.aborted){this.handleExhaustedRetries(s,3);return}!this.disposed&&!a.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(i,o,s,a)}}armRunBounds(){this.promptTurnCount=0,this.boundExceededNote=null;let e=this.scoop.config?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockBoundTimer=setTimeout(()=>{this.wallClockBoundTimer=null,this.tripRunBound(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.promptTurnCount+=1}enforceTurnBoundOnStart(){let e=this.scoop.config?.maxTurns;typeof e==`number`&&e>0&&this.promptTurnCount>=e&&this.tripRunBound(`turn bound (${e}) exceeded`)}tripRunBound(e){this.boundExceededNote!==null||this.disposed||(this.boundExceededNote=e,this.setStatus(`error`),this.stop())}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?L(this.scoop.config.modelId,this.scoop.config.modelProviderId):he();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=he();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=j9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,A9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await hx(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.unit.workspace.memoryPath;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,A9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=j9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(kh.includes(e))return e;A9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.persistSessionNow(),this.disposed=!0,this.wallClockBoundTimer!==null&&(clearTimeout(this.wallClockBoundTimer),this.wallClockBoundTimer=null),this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.reapBashJobs(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId?this.callbacks.onToolUIDone?.(n.requestId):n.type===`progress`&&n.progress&&this.callbacks.onToolProgress?.(e.toolName,n.progress)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8994
|
+
`)}`}}async function She(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),w9.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function Che(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>nhe(t,e)}}function whe(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...E9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>ahe(t,e)}}function The(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>ohe(t,e)}}function Ehe(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>she(e)}}function Dhe(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...kh],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`}},required:[`name`]},execute:t=>uhe(t,e)}}function Ohe(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>dhe(t,e)}}function khe(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>fhe(t,e)}}function Ahe(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>mhe(t,e)}}function jhe(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to wait for (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>_he(t,e)}}function Mhe(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>yhe(t,e)}}function Nhe(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>bhe(t,e)}}function Phe(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>xhe(e)}}function Fhe(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>She(t,e)}}function Ihe(e){let t=[],n=xh(e.scoop);return vh(e.scoop)||(t.push(Che(e)),e.onSudoRequest&&t.push(whe(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(The(e)),t.push(Ehe(e)),e.onScoopScoop&&t.push(Dhe(e)),e.onDropScoop&&t.push(Ohe(e)),e.onMuteScoops&&t.push(khe(e)),e.onUnmuteScoops&&t.push(Ahe(e)),e.onScheduleScoopWait&&t.push(jhe(e)),e.onSudoResolve&&(t.push(Mhe(e)),t.push(Nhe(e))),e.onListSudoRequests&&t.push(Phe(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Fhe(e))),t}const A9=r(`scoop-context`);function j9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!ree(t).includes(`xhigh`)?`high`:e}function Lhe(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function Rhe(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function M9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function N9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function zhe(e,t,n){return e?{...n}:{...n,HOME:`/scoops/${t}/home`,USER:t,PATH:[`/usr/bin`,`/scoops/${t}/workspace/skills`,`/scoops/${t}/workspace/bin`,...Nr].join(`:`)}}var Bhe=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;sessionPersistTimer=null;promptTurnCount=0;boundExceededNote=null;wallClockBoundTimer=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;liveBashJobPids=new Set;sessionStore=null;sessionId;sessionCreatedAt=0;imageRecoveryActive=!1;compactFn=null;getCompactionApiKey=null;overflowRecoveryAttempted=!1;overflowRecoveryActive=!1;overflowRecoveryPromise=null;overflowRecoveryEscalated=!1;coneJid;unit;ownerKind;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.unit=Rg(e),this.ownerKind=qg(e),this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,{policy:t}=this.unit,n=t.approvalAuthority===`user`,r=this.scoop.folder,i=this.callbacks.onSudoRequest,a=n||!i?e.getBroker():{requestApproval:e=>i(e)},o=n?()=>e.getPolicy():()=>e.getPolicyForScoop(r),s=t.sudoDefaultDisposition,c=e.getShellConfig(),l=t.persistCommandGrants?c.persistCommandGrant:async()=>{};return{broker:a,getPolicy:o,defaultDisposition:s,shellConfig:{...c,broker:a,getPolicy:o,defaultDisposition:s,persistCommandGrant:l}}}async initShellAndSkills(){let e=this.unit.workspace.root,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.unit.policy.filesystem.kind===`full-workspace`&&await yx(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await rS(),i=this.buildSudoWiring(),a=i?uee(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs,o=zhe(this.unit.policy.filesystem.kind===`full-workspace`,this.scoop.folder,r);return this.shell=new u9({fs:a,cwd:e,env:Object.keys(o).length>0?o:void 0,browserAPI:t,webhook:{hasLocalNodeServer:vt,getLeaderStatus:bn},jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>this.unit.display.role===`child`,sudo:i?.shellConfig,scrubProgressLabel:St(),processManager:this.processManager??void 0,processOwner:{kind:this.ownerKind,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),A9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await hx(n,this.skillsDir)}}async buildTools(e){let t=Ihe({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,resolveModelSelection:ke,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...qme(e),Vme(this.shell,this.fs,this.unit.workspace.scratch,{defaultBackgroundAfterSeconds:this.scoop.config?.backgroundAfterSeconds,targetScoop:this.unit.display.role===`child`?this.scoop.folder:void 0,jobHost:{spawn:e=>this.spawnBashJob(e)},scrubOutput:St(),fireLick:e=>{let t=globalThis.__slicc_lick_handler;if(!t){A9.warn(`No lick handler for background bash completion`,{folder:this.scoop.folder});return}t(e)}}),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:St()};return this.processManager?Je(n,{processManager:this.processManager,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):Je(n,void 0,r)}async loadMemories(){let e=this.unit.workspace.memoryPath,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.unit.policy.canWriteSharedMemory)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=bt(e.messages);return this.sessionCreatedAt=e.createdAt,A9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){A9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}getModelApiKey(){let e=this.scoop.config?.modelProviderId;return e?tee(e):ct()}async buildSessionHelpers(e){let t=await vee(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?Wt(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):Wt(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=()=>this.getModelApiKey()??void 0,a=this.unit.policy.canWriteSharedMemory&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:this.getModelApiKey()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:Ve({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:i,headers:r,onMemoryUpdates:a,shouldExtractMemories:()=>!Ma(`agentic-memory`),onCompactionStateChange:e=>{this.callbacks.onCompactionStateChange?.(e)}}),getCompactionApiKey:i}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);A9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!this.getModelApiKey()){A9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId,o=this.scoop.config?.modelProviderId,s=a?L(a,o):he(),c=this.unit.display.role===`primary`?`Cone`:`Scoop "${this.scoop.name}"`;if(console.log(`[model] ${c} using model: ${s.id} (provider: ${s.provider})`),o&&(s.id!==a||!_e(s,o)))throw Error(`Configured model ${o}:${a} resolved to ${s.provider}:${s.id}; refusing to run on a different model`);!o&&a&&s.id!==a&&A9.warn(`Configured scoop model did not resolve; using resolved model instead`,{folder:this.scoop.folder,configuredModelId:a,resolvedModelId:s.id});let l=this.buildSystemPrompt(i,r,t),u=await this.restoreSession(),{streamWithSessionId:d,compactFn:f,getCompactionApiKey:p}=await this.buildSessionHelpers(s);if(this.disposed)return;this.compactFn=f,this.getCompactionApiKey=p;let m=j9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,s);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new lh({initialState:{model:s,tools:n,systemPrompt:l,messages:u,thinkingLevel:m},getApiKey:()=>this.getModelApiKey()??void 0,transformContext:f,streamFn:d,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),A9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);A9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=this.scoop.config?.modelProviderId??``;try{e||=ne()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t,n=!1){let r=this.agent.state?.isStreaming??!1;if(this.isProcessing||r){A9.info(`Queueing prompt via ${n?`steer`:`followUp`} while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:r});let i={role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()};return n?this.agent.steer(i):this.agent.followUp(i),!0}return!1}spawnBashJob(e){let t=this.processManager;if(!t)return null;let n=e=>{this.liveBashJobPids.delete(e)},r=t.spawn({kind:`shell`,argv:[`bash`,`-c`,e],cwd:this.unit.workspace.root,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},ppid:this.currentTurnProcess?.pid});return this.liveBashJobPids.add(r.pid),{pid:r.pid,signal:r.abort.signal,kill:()=>{n(r.pid),t.signal(r.pid,`SIGKILL`)},exit:e=>{n(r.pid),t.exit(r.pid,e)}}}reapBashJobs(){let e=this.processManager;if(!e||this.liveBashJobPids.size===0)return;let t=[...this.liveBashJobPids];this.liveBashJobPids.clear(),A9.info(`Reaping background bash jobs on dispose`,{folder:this.scoop.folder,pids:t});for(let n of t)e.signal(n,`SIGKILL`)}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.unit.workspace.root,owner:{kind:this.ownerKind,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return Rhe(e)?(A9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),Dr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return Ha(e)?(A9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),Wa(this.unit.completion.mode===`interactive`),Dr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!M9(e)||t>=n)return!1;let a=r*2**(t-1);return A9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await N9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;A9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),Dr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.wallClockBoundTimer!==null&&(clearTimeout(this.wallClockBoundTimer),this.wallClockBoundTimer=null),this.boundExceededNote!==null&&(this.callbacks.onError(`agent run terminated: ${this.boundExceededNote}`),this.boundExceededNote=null),(n||r.aborted)&&this.persistSessionNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n,r){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{if(await e.prompt(t,n),this.disposed||r.aborted)return null;let i=this.overflowRecoveryPromise;return i!==null&&(await i,this.overflowRecoveryPromise===i&&(this.overflowRecoveryPromise=null),this.disposed||r.aborted)?null:this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:!await this.handleRetryableError(a,t,n,r,i)&&(A9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:M9(a)}),!!(t<n&&(await N9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[],n){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t,n?.steer))return;let r=this.agent;this.promptAbortController?.abort();let i=new AbortController;this.promptAbortController=i;let a=i.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflowRecoveryAttempted=!1,this.overflowRecoveryActive=!1,this.overflowRecoveryPromise=null,this.overflowRecoveryEscalated=!1;let o=this.registerTurnProcess(e,i);this.currentTurnProcess=o,this.armRunBounds();let s=null;try{if(s=await this.runAgentWithRetries(r,e,t,a),s&&!this.disposed&&!a.aborted){this.handleExhaustedRetries(s,3);return}!this.disposed&&!a.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(i,o,s,a)}}armRunBounds(){this.promptTurnCount=0,this.boundExceededNote=null;let e=this.scoop.config?.maxWallClockMs;typeof e==`number`&&Number.isFinite(e)&&e>0&&(this.wallClockBoundTimer=setTimeout(()=>{this.wallClockBoundTimer=null,this.tripRunBound(`wall-clock bound (${e} ms) exceeded`)},e))}recordCompletedTurn(){this.promptTurnCount+=1}enforceTurnBoundOnStart(){let e=this.scoop.config?.maxTurns;typeof e==`number`&&e>0&&this.promptTurnCount>=e&&this.tripRunBound(`turn bound (${e}) exceeded`)}tripRunBound(e){this.boundExceededNote!==null||this.disposed||(this.boundExceededNote=e,this.setStatus(`error`),this.stop())}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?L(this.scoop.config.modelId,this.scoop.config.modelProviderId):he();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=he();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=j9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,A9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await hx(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.unit.workspace.memoryPath;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,A9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=j9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(kh.includes(e))return e;A9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.persistSessionNow(),this.disposed=!0,this.wallClockBoundTimer!==null&&(clearTimeout(this.wallClockBoundTimer),this.wallClockBoundTimer=null),this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.reapBashJobs(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId?this.callbacks.onToolUIDone?.(n.requestId):n.type===`progress`&&n.progress&&this.callbacks.onToolProgress?.(e.toolName,n.progress,e.toolCallId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8995
8995
|
`);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
|
|
8996
|
-
`);Dr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}shouldRecoverFromOverflow(e){return!this.imageRecoveryActive&&Io(e)}hasActiveRecovery(){return this.imageRecoveryActive||this.overflowRecoveryActive}handleAgentEndEvent(e,t){if(!(this.disposed||t?.aborted)){if(e.length>0){let n=e[e.length-1];if(n.role===`assistant`&&n.errorMessage){let r=n.errorMessage;if(!this.hasActiveRecovery()&&Lhe(r)){this.recoverFromImageError(e);return}if(this.shouldRecoverFromOverflow(n)){this.recoverFromOverflow(e,t);return}if(!this.hasActiveRecovery()&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=r;return}this.imageRecoveryActive=!1,this.overflowRecoveryActive=!1,Dr(`llm`,r),this.callbacks.onError(r)}else this.imageRecoveryActive=!1,this.overflowRecoveryActive=!1,n.role===`assistant`&&(this.overflowRecoveryAttempted=!1)}this.persistSessionNow(e)}}persistSessionNow(e){this.sessionPersistTimer!==null&&(clearTimeout(this.sessionPersistTimer),this.sessionPersistTimer=null);let t=this.agent?.state?.messages??e??[];!this.sessionStore||t.length===0||this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{A9.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}schedulePersistSession(){this.disposed||!this.sessionStore||this.sessionPersistTimer===null&&(this.sessionPersistTimer=setTimeout(()=>{this.sessionPersistTimer=null,this.disposed||this.persistSessionNow()},1e3))}handleAgentEvent(e,t){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e),this.schedulePersistSession();break;case`message_end`:if(e.message.role===`assistant`){let t=e.message;t.errorMessage||(this.overflowRecoveryAttempted=!1);let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);n&&!this.didStreamDeltas&&this.callbacks.onResponse(n,!1)}this.schedulePersistSession();break;case`turn_start`:this.enforceTurnBoundOnStart();break;case`turn_end`:if(this.recordCompletedTurn(),e.message.role===`assistant`&&Io(e.message))break;this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages,t)}}recoverFromOverflow(e,t){let n=this.promptAbortController?.signal,r=t&&n?AbortSignal.any([t,n]):t??n;if(!this.agent||this.disposed||r?.aborted)return;if(this.overflowRecoveryAttempted){this.escalateOverflowRecovery(r);return}this.overflowRecoveryAttempted=!0,this.overflowRecoveryActive=!0,A9.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length});let i=this.agent,a=this.compactFn,o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&Io(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.getCompactionApiKey?.()){this.escalateOverflowRecovery(r,Error(`Compaction is unavailable`));return}this.overflowRecoveryPromise=this.compactAndResumeOverflow(i,a,c,r)}async compactAndResumeOverflow(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.disposed||r?.aborted||this.agent!==e)return;if(!nee(n,i)){this.escalateOverflowRecovery(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.callbacks.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.disposed||r?.aborted||this.agent!==e){t();return}e.continue().then(t).catch(e=>{!this.disposed&&!r?.aborted&&this.escalateOverflowRecovery(r,e),t()})},100)})}catch(e){!this.disposed&&!r?.aborted&&this.escalateOverflowRecovery(r,e)}finally{this.overflowRecoveryActive=!1}}escalateOverflowRecovery(e,t){if(this.overflowRecoveryActive=!1,this.disposed||e?.aborted||this.overflowRecoveryEscalated)return;this.overflowRecoveryEscalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;A9.error(`Context overflow recovery exhausted`,{folder:this.scoop.folder,error:n}),this.setStatus(`error`);let r=`Scoop "${this.scoop.name}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`;this.unit.completion.mode===`interactive`?this.callbacks.onError(r):this.callbacks.onFatalError?this.callbacks.onFatalError(r):this.callbacks.onError(r)}recoverFromImageError(e){if(this.agent){A9.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.imageRecoveryActive=!0,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{A9.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.imageRecoveryActive=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){A9.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.imageRecoveryActive=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.unit.policy.filesystem.kind===`full-workspace`?[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`,`/tmp`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.unit.workspace.memoryPath;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
8996
|
+
`);Dr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError,e.toolCallId)}shouldRecoverFromOverflow(e){return!this.imageRecoveryActive&&Io(e)}hasActiveRecovery(){return this.imageRecoveryActive||this.overflowRecoveryActive}handleAgentEndEvent(e,t){if(!(this.disposed||t?.aborted)){if(e.length>0){let n=e[e.length-1];if(n.role===`assistant`&&n.errorMessage){let r=n.errorMessage;if(!this.hasActiveRecovery()&&Lhe(r)){this.recoverFromImageError(e);return}if(this.shouldRecoverFromOverflow(n)){this.recoverFromOverflow(e,t);return}if(!this.hasActiveRecovery()&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=r;return}this.imageRecoveryActive=!1,this.overflowRecoveryActive=!1,Dr(`llm`,r),this.callbacks.onError(r)}else this.imageRecoveryActive=!1,this.overflowRecoveryActive=!1,n.role===`assistant`&&(this.overflowRecoveryAttempted=!1)}this.persistSessionNow(e)}}persistSessionNow(e){this.sessionPersistTimer!==null&&(clearTimeout(this.sessionPersistTimer),this.sessionPersistTimer=null);let t=this.agent?.state?.messages??e??[];!this.sessionStore||t.length===0||this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{A9.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}schedulePersistSession(){this.disposed||!this.sessionStore||this.sessionPersistTimer===null&&(this.sessionPersistTimer=setTimeout(()=>{this.sessionPersistTimer=null,this.disposed||this.persistSessionNow()},1e3))}handleAgentEvent(e,t){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args,e.toolCallId);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e),this.schedulePersistSession();break;case`message_end`:if(e.message.role===`assistant`){let t=e.message;t.errorMessage||(this.overflowRecoveryAttempted=!1);let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);n&&!this.didStreamDeltas&&this.callbacks.onResponse(n,!1)}this.schedulePersistSession();break;case`turn_start`:this.enforceTurnBoundOnStart();break;case`turn_end`:if(this.recordCompletedTurn(),e.message.role===`assistant`&&Io(e.message))break;this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages,t)}}recoverFromOverflow(e,t){let n=this.promptAbortController?.signal,r=t&&n?AbortSignal.any([t,n]):t??n;if(!this.agent||this.disposed||r?.aborted)return;if(this.overflowRecoveryAttempted){this.escalateOverflowRecovery(r);return}this.overflowRecoveryAttempted=!0,this.overflowRecoveryActive=!0,A9.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length});let i=this.agent,a=this.compactFn,o=i.state.messages,s=o[o.length-1],c=s?.role===`assistant`&&Io(s)?o.slice(0,-1):o;if(i.state.messages=c,!a||!i.state.model||!this.getCompactionApiKey?.()){this.escalateOverflowRecovery(r,Error(`Compaction is unavailable`));return}this.overflowRecoveryPromise=this.compactAndResumeOverflow(i,a,c,r)}async compactAndResumeOverflow(e,t,n,r){try{let i=await t(n,r,{force:!0});if(this.disposed||r?.aborted||this.agent!==e)return;if(!nee(n,i)){this.escalateOverflowRecovery(r,Error(`Forced compaction did not reduce the context`));return}e.state.messages=i,this.callbacks.onResponse(`Context window exceeded — compacting history and continuing...`,!1),await new Promise(t=>{setTimeout(()=>{if(this.disposed||r?.aborted||this.agent!==e){t();return}e.continue().then(t).catch(e=>{!this.disposed&&!r?.aborted&&this.escalateOverflowRecovery(r,e),t()})},100)})}catch(e){!this.disposed&&!r?.aborted&&this.escalateOverflowRecovery(r,e)}finally{this.overflowRecoveryActive=!1}}escalateOverflowRecovery(e,t){if(this.overflowRecoveryActive=!1,this.disposed||e?.aborted||this.overflowRecoveryEscalated)return;this.overflowRecoveryEscalated=!0;let n=t instanceof Error?t.message:t?String(t):void 0;A9.error(`Context overflow recovery exhausted`,{folder:this.scoop.folder,error:n}),this.setStatus(`error`);let r=`Scoop "${this.scoop.name}" context window was exceeded and could not be reduced. Re-delegate with a narrower task.`;this.unit.completion.mode===`interactive`?this.callbacks.onError(r):this.callbacks.onFatalError?this.callbacks.onFatalError(r):this.callbacks.onError(r)}recoverFromImageError(e){if(this.agent){A9.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.imageRecoveryActive=!0,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{A9.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.imageRecoveryActive=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){A9.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.imageRecoveryActive=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.unit.policy.filesystem.kind===`full-workspace`?[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`,`/tmp`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.unit.workspace.memoryPath;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
8997
8997
|
|
|
8998
8998
|
${this.unit.display.role===`primary`?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
|
|
8999
8999
|
Folder: ${this.scoop.folder}
|
|
@@ -9074,8 +9074,8 @@ ${e}
|
|
|
9074
9074
|
---
|
|
9075
9075
|
${i?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
9076
9076
|
${t}
|
|
9077
|
-
---`);let c=vx(n);return c&&(s+=c),s}};const P9=r(`scoop-lifecycle-manager`);var Vhe=class{deps;units=new Map;constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new $x(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??wh(t.values())[0]}rootOf(e){let t=this.deps.getScoops(),n=new Set,r=e;for(;r&&r.parentJid!==null&&!n.has(r.jid);)n.add(r.jid),r=t.get(r.parentJid);return r??wh(t.values())[0]}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 or))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context)if(n.tab?.status===`error`)P9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{P9.debug(`Context already exists`,{jid:e});return}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Rg(t).policy.filesystem,o=a.kind===`full-workspace`?r:new or(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new Bhe(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{P9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),P9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),P9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return P9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(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.getContext(e)}if(!o||!s){P9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),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();Hg(e),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.parentJid!==null&&Er(`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);if(n&&n.parentJid===null&&wh(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{P9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),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.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(){let e=this.getContexts();for(let t of e.values())t.updateModel();P9.info(`Model updated on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{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.getContext(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(),{policy:o,completion:s}=Rg(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),Er(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{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)},onToolProgress:(t,r)=>{n.onToolProgress?.(e,t,r)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:o.canResolveApprovals?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:o.canResolveApprovals?()=>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);if(P9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),Er(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Rg(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){P9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).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 Hhe=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}`);Er(`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.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);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=wn(Ln(On(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}: ${ph(e.content,e.attachments)}`).join(`
|
|
9078
|
-
`),l=s.flatMap(e=>mh(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=wn(Ln(On(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(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);F9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){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 Uhe=class{scoops=new Map;workUnits=new Vg(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Cx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Xx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Jx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Hx({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new Px({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Mn(e),saveMessage:e=>Tn(e)});lickRegistry=new Ex({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Hhe({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=>Tn(e),deleteMessage:e=>Dn(e),clearMessagesForScoop:e=>Fn(e),clearAllMessages:()=>Nn(),getMessagesSince:(e,t,n)=>jn(e,t,n),setState:(e,t)=>Cn(e,t)},isExternalLickChannel:fg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Vhe({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=>Sn(e),deleteScoop:e=>Pn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>nr(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 Bn(),this.sharedFs=await Ax(()=>ar.create({dbName:`slicc-fs`}),e),this.sessionStore=new _h,this.fsWatcher=new ir,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new Tv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new R_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new kx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Rn(),n=Object.values(t).find(e=>e.isCone)?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Hg(e),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await An(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Mx({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,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}lr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=Dv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=e.isCone?null:t??null;try{await Sn(e)}catch(t){I9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}migrateScoopConfig(e){if(e.parentJid===null)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=>$n(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)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return wh(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await ar.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await yx(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 Tv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new R_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new kx(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 Mn(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(fr)]}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 cg,t=this.sharedFs;return new Xy({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:mb(),snapshotStore:{read:e=>sb(t,e),write:(e,n)=>ob(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.78.8`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function Whe(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)=>Yhe(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),qhe(t,n);let f=a(o.ctx,l),p=Jhe(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`?Khe(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 Ghe(e){let t=Whe(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Khe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function qhe(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 Jhe(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 Yhe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Xhe(n,t,a?.args??[],r):e===`agent`?Zhe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Xhe(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 Zhe(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 Qhe=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 un(`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 un(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new un(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new un(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new un(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new un(`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 un(`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 un(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new un(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new un(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new un(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new un(`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 un(`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 ige(t);let n=this.pm.get(e);switch(t){case`status`:return $he(n);case`cmdline`:return ege(n);case`cwd`:return tge(n);case`stat`:return nge(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 $he(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${rge(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
|
+
---`);let c=vx(n);return c&&(s+=c),s}};const P9=r(`scoop-lifecycle-manager`);var Vhe=class{deps;units=new Map;constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new $x(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??wh(t.values())[0]}rootOf(e){let t=this.deps.getScoops(),n=new Set,r=e;for(;r&&r.parentJid!==null&&!n.has(r.jid);)n.add(r.jid),r=t.get(r.parentJid);return r??wh(t.values())[0]}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 or))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context)if(n.tab?.status===`error`)P9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{P9.debug(`Context already exists`,{jid:e});return}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Rg(t).policy.filesystem,o=a.kind===`full-workspace`?r:new or(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new Bhe(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{P9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),P9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),P9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return P9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(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.getContext(e)}if(!o||!s){P9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),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();Hg(e),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.parentJid!==null&&Er(`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);if(n&&n.parentJid===null&&wh(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{P9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),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.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(){let e=this.getContexts();for(let t of e.values())t.updateModel();P9.info(`Model updated on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{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.getContext(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(),{policy:o,completion:s}=Rg(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),Er(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:o.canResolveApprovals?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:o.canResolveApprovals?()=>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);if(P9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),Er(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Rg(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){P9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).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 Hhe=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}`);Er(`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.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);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=wn(Ln(On(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}: ${ph(e.content,e.attachments)}`).join(`
|
|
9078
|
+
`),l=s.flatMap(e=>mh(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=wn(Ln(On(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(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);F9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){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 Uhe=class{scoops=new Map;workUnits=new Vg(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new Cx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Xx({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Jx({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Hx({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new Px({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Mn(e),saveMessage:e=>Tn(e)});lickRegistry=new Ex({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Hhe({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=>Tn(e),deleteMessage:e=>Dn(e),clearMessagesForScoop:e=>Fn(e),clearAllMessages:()=>Nn(),getMessagesSince:(e,t,n)=>jn(e,t,n),setState:(e,t)=>Cn(e,t)},isExternalLickChannel:fg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Vhe({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=>Sn(e),deleteScoop:e=>Pn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>nr(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 Bn(),this.sharedFs=await Ax(()=>ar.create({dbName:`slicc-fs`}),e),this.sessionStore=new _h,this.fsWatcher=new ir,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new Tv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new R_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new kx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Rn(),n=Object.values(t).find(e=>e.isCone)?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Hg(e),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await An(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Mx({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,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}lr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=Dv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=e.isCone?null:t??null;try{await Sn(e)}catch(t){I9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}migrateScoopConfig(e){if(e.parentJid===null)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=>$n(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)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return wh(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await ar.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await yx(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 Tv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new R_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new kx(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 Mn(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(fr)]}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 cg,t=this.sharedFs;return new Xy({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:mb(),snapshotStore:{read:e=>sb(t,e),write:(e,n)=>ob(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.79.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function Whe(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)=>Yhe(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),qhe(t,n);let f=a(o.ctx,l),p=Jhe(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`?Khe(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 Ghe(e){let t=Whe(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Khe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function qhe(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 Jhe(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 Yhe(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Xhe(n,t,a?.args??[],r):e===`agent`?Zhe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Xhe(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 Zhe(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 Qhe=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 un(`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 un(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new un(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new un(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new un(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new un(`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 un(`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 un(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new un(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new un(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new un(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new un(`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 un(`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 ige(t);let n=this.pm.get(e);switch(t){case`status`:return $he(n);case`cmdline`:return ege(n);case`cwd`:return tge(n);case`stat`:return nge(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 $he(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${rge(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(`
|
|
9079
9079
|
`)+`
|
|
9080
9080
|
`}function ege(e){return e.argv.join(`\0`)+`\0`}function tge(e){return e.cwd+`
|
|
9081
9081
|
`}function nge(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -9084,4 +9084,4 @@ ${t}
|
|
|
9084
9084
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
9085
9085
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
9086
9086
|
`}}function age(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(RB(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(!NB(n.token))return;let a=i.get(n.id);if(a){r({type:zB,id:n.id}),a.result&&r({type:BB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:zB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:BB,id:n.id,...e})};(WB(n)?qB(n):LB(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 oge(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 sge(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 cge(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}lge(e,t)}function lge(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`):wh(r)[0],!i){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!F_(i)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:i.folder});return}e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let a=Eg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=oge(e),s=sge(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 uge(e,t,n,r,i){let a=new Br,o=new Uhe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,aG(sG()),W9().__slicc_browser=t,await n.bind(o,t);let s=cee(()=>n.emitTrayRuntimeStatus()),c=i_(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function dge(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Be2VSQE-.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-BJhAu_iX.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??cge,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function fge(e){wh(e.getScoops()).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,parentJid:null,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function pge(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Ghe({sharedFs:i,getConeJid:()=>t.getWorkUnits().resolveDefaultRoot()?.descriptor.id,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>lG(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>Z7().slice(10,22),splitResult:(e,t)=>Q7(e,t)})}async function mge(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))+`
|
|
9087
|
-
`,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 hge(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-DiPcVRfN.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 gge(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 E_(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})},_ge(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function _ge(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:()=>D_()}}function vge(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-CEMrCBeT.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 yge(){Kn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-yB5b3-05.js`);return e()})}function bge(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-yB5b3-05.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 xge(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 Sge(){return vt()}async function Cge(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);yge();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await uge(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?qh(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Qhe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await dge(l,e,o);s(`lick-manager-ready`),f&&pge({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await mge({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;Sge()&&(g=await hge(p,o,e.localLickWsUrl??null));let _=gge(n,p,o);f&&vge(f,p,o),a||await fge(l),s(`cone-bootstrapped`),f&&bge(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await xge(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=age({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 wge({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 wge(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)}Tge({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Tge(e){let t=W9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,aG(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[X7]}const G9=`x-bypass-llm-proxy`;function Ege(e,t,n){return t?(r,i)=>{if(!Dge(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 Dge(e,t,n){if(kge(e,t))return!0;let r=n?.()??null;return r?Oge(e,r,t):!1}function Oge(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 kge(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 Age(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 jge=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(!Mge(e)||e.source!==`panel`)return;let t=e.payload;Nge(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 Mge(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 Nge(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 Pge=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 Fge(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new jge({transport:t,processManager:i,createShell:(a,o)=>new Pge(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??vt,getLeaderStatus:e.webhook?.getLeaderStatus??bn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Ige(e){let t=new Lge(e);return t.start(),{stop:()=>t.dispose()}}var Lge=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(!Rge(e)||e.source!==`panel`)return;let t=e.payload;if(zge(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Bge(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 un(`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 un(`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(Vge(e.type),e.requestId,new un(`EACCES`,`vfs-rpc-host has no writable backend wired`),Hge(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 un(`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 un(`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 un(`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 Rge(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function zge(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 Bge(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 Vge(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 Hge(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof un?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Uge(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Ege(e.bind(globalThis),t,Wge)}function Wge(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Gge(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 Kge=Age(e=>Yge(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Kge.handle(e.data)});function qge(e){let t=Mee(e.pageBuildId,`6.78.8-mt4bsvxx`);return()=>{t&&Cee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.78.8-mt4bsvxx`)}}function Jge(e){Uge(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),XW(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),Gge(e.localStorageSeed??{}),e.flagFloat&&Ra(e.flagFloat)}async function Yge(e){Aee(e.instanceId);let t=qge(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Jge(e),Tee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Pee(e.kernelPort),a=new __(r),o=__.createCallbacks(a),c=new Fee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new ha(c);Y9=await Cge({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(xa(i));let m=await Zge({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){Xge(e.kernelPort,t)}}function Xge(e,t){jee(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 Zge(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=Fge({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Ige({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Qge(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Qge(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DvFwJX-M.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-n2pCvcgW.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())});
|
|
9087
|
+
`,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 hge(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-DiPcVRfN.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 gge(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 E_(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})},_ge(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function _ge(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:()=>D_()}}function vge(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-IeWjtnGl.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 yge(){Kn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-CwBF5Q1G.js`);return e()})}function bge(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CwBF5Q1G.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 xge(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 Sge(){return vt()}async function Cge(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);yge();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await uge(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?qh(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new Qhe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await dge(l,e,o);s(`lick-manager-ready`),f&&pge({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await mge({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;Sge()&&(g=await hge(p,o,e.localLickWsUrl??null));let _=gge(n,p,o);f&&vge(f,p,o),a||await fge(l),s(`cone-bootstrapped`),f&&bge(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await xge(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=age({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 wge({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 wge(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)}Tge({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Tge(e){let t=W9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,aG(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[X7]}const G9=`x-bypass-llm-proxy`;function Ege(e,t,n){return t?(r,i)=>{if(!Dge(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 Dge(e,t,n){if(kge(e,t))return!0;let r=n?.()??null;return r?Oge(e,r,t):!1}function Oge(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 kge(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 Age(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 jge=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(!Mge(e)||e.source!==`panel`)return;let t=e.payload;Nge(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 Mge(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 Nge(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 Pge=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 Fge(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new jge({transport:t,processManager:i,createShell:(a,o)=>new Pge(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??vt,getLeaderStatus:e.webhook?.getLeaderStatus??bn},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Ige(e){let t=new Lge(e);return t.start(),{stop:()=>t.dispose()}}var Lge=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(!Rge(e)||e.source!==`panel`)return;let t=e.payload;if(zge(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Bge(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 un(`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 un(`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(Vge(e.type),e.requestId,new un(`EACCES`,`vfs-rpc-host has no writable backend wired`),Hge(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 un(`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 un(`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 un(`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 Rge(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function zge(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 Bge(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 Vge(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 Hge(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof un?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Uge(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=Ege(e.bind(globalThis),t,Wge)}function Wge(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Gge(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 Kge=Age(e=>Yge(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Kge.handle(e.data)});function qge(e){let t=Mee(e.pageBuildId,`6.79.0-mt4flfh8`);return()=>{t&&Cee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.79.0-mt4flfh8`)}}function Jge(e){Uge(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),XW(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),Gge(e.localStorageSeed??{}),e.flagFloat&&Ra(e.flagFloat)}async function Yge(e){Aee(e.instanceId);let t=qge(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{Jge(e),Tee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Pee(e.kernelPort),a=new __(r),o=__.createCallbacks(a),c=new Fee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new ha(c);Y9=await Cge({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(xa(i));let m=await Zge({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){Xge(e.kernelPort,t)}}function Xge(e,t){jee(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 Zge(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=Fge({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Ige({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Qge(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Qge(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DvFwJX-M.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-n2pCvcgW.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())});
|