sliccy 6.75.0 → 6.76.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.
Files changed (80) hide show
  1. package/dist/node-server/_shared/tray-sync-protocol.d.ts +8 -0
  2. package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
  3. package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
  4. package/dist/ui/.vite/manifest.json +121 -121
  5. package/dist/ui/assets/{account-store-CCg1CJzw.js → account-store-BOO_CzoH.js} +1 -1
  6. package/dist/ui/assets/{account-store-BAHUpe_O.js → account-store-BxGdz4En.js} +1 -1
  7. package/dist/ui/assets/{adobe-B5anYUmN.js → adobe-BS726v5F.js} +1 -1
  8. package/dist/ui/assets/{adobe-PBpRc-Pi.js → adobe-DRIeZ7SH.js} +1 -1
  9. package/dist/ui/assets/{apply-layout-B8kIS7YS.js → apply-layout-8FDKkAyS.js} +1 -1
  10. package/dist/ui/assets/{apps-DgC8YSsY.js → apps-Dy99L1_j.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-CgnqAPXx.js → azure-openai-2PeEIEpE.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-B4mtH4TU.js → azure-openai-CSLwIPI9.js} +1 -1
  13. package/dist/ui/assets/{cerebras-BzOjDcuz.js → cerebras-Ba7Z9duV.js} +1 -1
  14. package/dist/ui/assets/{cerebras-Dn6vH1Am.js → cerebras-QV_fd2ps.js} +1 -1
  15. package/dist/ui/assets/{connect-surface-9ixjd_gD.js → connect-surface-CTu0wr2Y.js} +1 -1
  16. package/dist/ui/assets/{fs-DasQzCy9.js → fs-3kOP04jS.js} +2 -2
  17. package/dist/ui/assets/{fs-BFiiSgrN.js → fs-Boij2gPF.js} +1 -1
  18. package/dist/ui/assets/{github-66vl-5p7.js → github-BjNCMOTH.js} +1 -1
  19. package/dist/ui/assets/{github-i80FT0VN.js → github-DGwuCXij.js} +2 -2
  20. package/dist/ui/assets/{github-copilot-nQjXB4My.js → github-copilot-7vobYWUU.js} +1 -1
  21. package/dist/ui/assets/{github-copilot-DzTgycKp.js → github-copilot-DlzADrSr.js} +1 -1
  22. package/dist/ui/assets/{github-install-jWWA5n2X.js → github-install-B8nRAI8z.js} +1 -1
  23. package/dist/ui/assets/{github-zip-BZcI0-aZ.js → github-zip-7k6aGRi5.js} +1 -1
  24. package/dist/ui/assets/{js-realm-worker-BA0s-HAh.js → js-realm-worker-BH_Uhjou.js} +1 -1
  25. package/dist/ui/assets/{kernel-worker-CkkdqlLW.js → kernel-worker-COfVGbIN.js} +26 -26
  26. package/dist/ui/assets/{local-llm-Dqyuolju.js → local-llm-CDx8pQEL.js} +1 -1
  27. package/dist/ui/assets/{local-llm-BHq5S7yF.js → local-llm-Ca41QR9W.js} +1 -1
  28. package/dist/ui/assets/{main-BH06xKyx.js → main-CBjLDGjV.js} +3 -3
  29. package/dist/ui/assets/{mount-CcOQBZqW.js → mount-BNWucV-S.js} +2 -2
  30. package/dist/ui/assets/{mount-BAeT-dqA.js → mount-Dcl0CQrv.js} +1 -1
  31. package/dist/ui/assets/{mount-recovery-DkiFv5PY.js → mount-recovery-B1Eib3Wt.js} +1 -1
  32. package/dist/ui/assets/{new-session-BeeBJa-x.js → new-session-CGv5e7P7.js} +2 -2
  33. package/dist/ui/assets/{oauth-bootstrap-BCPhKNv_.js → oauth-bootstrap-DBbtYdzz.js} +2 -2
  34. package/dist/ui/assets/{openai-codex-DSNsEhFA.js → openai-codex-BTUlRTto.js} +1 -1
  35. package/dist/ui/assets/{openai-codex-D6W5LbqW.js → openai-codex-CZs8JRSw.js} +1 -1
  36. package/dist/ui/assets/{openrouter-CkAkCotu.js → openrouter-Bvd2Eqif.js} +1 -1
  37. package/dist/ui/assets/{openrouter-Cesy6scG.js → openrouter-DYhI1zom.js} +1 -1
  38. package/dist/ui/assets/{openrouter-oauth--wHqkP-e.js → openrouter-oauth-C6mgQiRV.js} +1 -1
  39. package/dist/ui/assets/{openrouter-oauth-CzV26DfT.js → openrouter-oauth-DK-5hp2X.js} +1 -1
  40. package/dist/ui/assets/{panel-rpc-handlers-fGp_asMJ.js → panel-rpc-handlers-BXCRWF2E.js} +2 -2
  41. package/dist/ui/assets/{provider-D1ZC9qXP.js → provider-DxVWgpTU.js} +2 -2
  42. package/dist/ui/assets/{provider-settings-8bWQwrlg.js → provider-settings-BWmqGvFK.js} +1 -1
  43. package/dist/ui/assets/{provider-settings-C-kxOcFq.js → provider-settings-DByKbVop.js} +1 -1
  44. package/dist/ui/assets/{provider-store-access-BQGH-0a1.js → provider-store-access-BQfEu3u9.js} +2 -2
  45. package/dist/ui/assets/provider-store-access-dlrRLglC.js +1 -0
  46. package/dist/ui/assets/{provider-BVorzuId.js → provider-xByUgvpM.js} +1 -1
  47. package/dist/ui/assets/{providers-D2Pn4dpP.js → providers-DH1Mhm__.js} +1 -1
  48. package/dist/ui/assets/{providers-DYHQ-0Q3.js → providers-Db_Doqrk.js} +2 -2
  49. package/dist/ui/assets/{quick-llm-B07FHVIT.js → quick-llm-nv9Pz0pZ.js} +1 -1
  50. package/dist/ui/assets/{recovery-screen-B99hXe7O.js → recovery-screen-0OnsBXuN.js} +1 -1
  51. package/dist/ui/assets/{redirect-uri-CbaLH4zl.js → redirect-uri-DVwxCbAH.js} +1 -1
  52. package/dist/ui/assets/{session-freezer-CLG57-ou.js → session-freezer-BVmmPVzM.js} +3 -3
  53. package/dist/ui/assets/{setup-feature-flags-remote-EWldaG4n.js → setup-feature-flags-remote-DCYtiT5O.js} +1 -1
  54. package/dist/ui/assets/{setup-standalone-prelude-CoD24Vpw.js → setup-standalone-prelude-C89-5Dtf.js} +1 -1
  55. package/dist/ui/assets/{setup-sudo-CtZ_V6iZ.js → setup-sudo-CHykhXbm.js} +2 -2
  56. package/dist/ui/assets/{skills-BmQBvY-R.js → skills-BKsLImdA.js} +1 -1
  57. package/dist/ui/assets/slicc-version-DV1WF_eM.js +1 -0
  58. package/dist/ui/assets/{store-CG5kLFp1.js → store-CEccVDd7.js} +1 -1
  59. package/dist/ui/assets/{store-DvmZZQcL.js → store-CgULlP3e.js} +1 -1
  60. package/dist/ui/assets/{sudo-BWBsX1fU.js → sudo-Bi--9XjE.js} +1 -1
  61. package/dist/ui/assets/{upgrade-detection-L9WqdkJi.js → upgrade-detection-Di65pY4y.js} +1 -1
  62. package/dist/ui/assets/{wc-extension-DnpJWzUr.js → wc-extension-CwbvHOae.js} +2 -2
  63. package/dist/ui/assets/{wc-follower-zprZWqU5.js → wc-follower-DfFkmNjM.js} +3 -3
  64. package/dist/ui/assets/{wc-live-BOX1g3dk.js → wc-live-C5Y8LMGm.js} +5 -5
  65. package/dist/ui/assets/{wc-nav-BWcsqFm7.js → wc-nav-D4I71uQu.js} +2 -2
  66. package/dist/ui/assets/{wc-onboarding-BJbUWr0L.js → wc-onboarding-UrMxL1c-.js} +2 -2
  67. package/dist/ui/assets/{wc-placeholder-ChVK7FyO.js → wc-placeholder-zxd8RVYO.js} +2 -2
  68. package/dist/ui/assets/{wc-settings-DhTfp9uX.js → wc-settings-BcpEli20.js} +2 -2
  69. package/dist/ui/assets/{wc-shell-C-MXjbsY.js → wc-shell-ClIw7Xp7.js} +2 -2
  70. package/dist/ui/assets/{wc-sprinkles-NfZXNGaq.js → wc-sprinkles-DmaQ6PZC.js} +2 -2
  71. package/dist/ui/assets/{wc-tray-DW6cH6mP.js → wc-tray-D8C4hzMc.js} +2 -2
  72. package/dist/ui/assets/wc-tray-scoops-CNqQ6-vb.js +5 -0
  73. package/dist/ui/assets/{xai-grok-m_-Csb4Y.js → xai-grok-C4yc6t0c.js} +1 -1
  74. package/dist/ui/assets/{xai-grok-VMDfxNzx.js → xai-grok-CTETAYca.js} +1 -1
  75. package/dist/ui/index.html +6 -6
  76. package/dist/ui/packages/webapp/index.html +6 -6
  77. package/package.json +1 -1
  78. package/dist/ui/assets/provider-store-access-BnHLvuWA.js +0 -1
  79. package/dist/ui/assets/slicc-version-D7-5Kk_B.js +0 -1
  80. package/dist/ui/assets/wc-tray-scoops-D4nhxf0m.js +0 -5
@@ -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-D2Pn4dpP.js";import{a as l,c as u,d,f,i as p,l as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-CWqWgyRG.js";import{a as x,i as S,n as C,r as w,s as T,t as E}from"./src-CcFD5QfS.js";import{$t as D,An as O,At as ee,Bt as te,Cn as k,Ct as A,D as ne,Dn as re,Dt as ie,E as ae,En as oe,Et as se,Fn as ce,Ft as le,Gt as ue,Ht as de,In as j,It as fe,Jt as pe,Kt as me,L as he,Ln as M,Lt as ge,M as _e,Mn as ve,Mt as ye,Nn as N,Nt as P,On as be,Ot as xe,Pn as F,Pt as Se,Q as I,Qt as Ce,R as L,Rn as R,Rt as we,Sn as Te,St as Ee,Tn as De,Tt as z,Ut as Oe,V as ke,Vt as Ae,Wt as je,X as Me,Xt as Ne,Y as Pe,Yt as Fe,Z as Ie,Zt as Le,_n as Re,_t as ze,an as Be,at as Ve,bn as He,bt as Ue,cn as We,ct as eee,dn as Ge,dt as Ke,en as qe,et as Je,fn as B,ft as Ye,gn as Xe,gt as Ze,h as tee,hn as Qe,ht as $e,in as et,it as tt,jn as nt,jt as rt,kn as it,kt as at,ln as ot,lt as st,m as ct,mn as lt,mt as ut,nn as dt,nt as ft,on as pt,ot as nee,pn as mt,pt as ht,qt as gt,rn as _t,rt as vt,sn as yt,st as bt,tn as xt,tt as St,un as Ct,ut as wt,vn as V,vt as Tt,w as Et,wn as Dt,wt as Ot,xn as kt,xt as At,yn as jt,yt as Mt,zt as Nt}from"./account-store-CCg1CJzw.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-BfNg24Ce.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-BAeT-dqA.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-DkiFv5PY.js";import{a as aee,c as oee,i as bn,n as see,o as xn,r as Sn,s as Cn}from"./lick-urls-DEfVsxzt.js";import{C as wn,D as Tn,E as En,S as Dn,_ as On,a as kn,b as An,d as jn,g as Mn,h as Nn,m as Pn,n as Fn,o as In,r as Ln,s as Rn,t as zn,u as Bn,w as Vn,y as Hn}from"./db-DATxPCUz.js";import{a as Un,i as Wn,n as Gn,r as Kn}from"./tray-runtime-config-BoItLnrD.js";import{n as qn,r as Jn,t as Yn}from"./slicc-version-D7-5Kk_B.js";import{a as Xn,c as Zn,d as Qn,i as $n,l as er,n as tr,o as nr,s as rr,t as ir,u as ar}from"./lick-manager-BJhAu_iX.js";import{a as or,n as sr,r as cr}from"./fs-BFiiSgrN.js";import{a as lr,c as ur,i as dr,l as fr,n as pr,o as H,r as mr,s as hr}from"./cost-command-AOg9dLn6.js";import{_ as gr,a as _r,b as vr,c as yr,d as br,f as xr,g as Sr,h as Cr,i as cee,l as wr,m as Tr,n as lee,o as uee,p as dee,r as Er,s as fee,u as pee,v as mee,y as Dr}from"./skills-BmQBvY-R.js";import{n as hee,t as gee}from"./llm-session-id-BZyXP_j2.js";import{n as _ee,r as vee}from"./frozen-archive-format--7sONywg.js";import{i as yee,r as bee}from"./browser-BAL8RehA.js";import{a as Or,i as kr,n as xee,r as See,t as Cee}from"./telemetry-BugxTkxX.js";import{n as Ar,t as jr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Mr,i as Nr,r as Pr,t as Fr}from"./git-config-DA8M5e8O.js";import{a as Ir,c as Lr,i as Rr,o as zr,r as Br,s as Vr,t as Hr}from"./script-catalog-Bt94D0RP.js";import{t as Ur}from"./process-manager-unCzdHp3.js";import{A as Wr,C as Gr,O as Kr,_ as qr,a as Jr,b as Yr,c as Xr,d as Zr,f as Qr,g as $r,h as ei,i as ti,k as ni,l as ri,m as ii,n as ai,o as oi,p as si,r as ci,s as li,t as ui,u as di,v as fi,x as pi,y as mi}from"./shared-DqziuFis.js";import{n as hi,t as gi}from"./esbuild-wasm-C_e51T2J.js";import{n as _i,t as vi}from"./wasm-compiler-Ct7QZURL.js";import{_ as yi,a as bi,c as xi,f as Si,g as Ci,h as wi,l as Ti,m as Ei,n as Di,p as Oi,r as ki,u as Ai,v as ji,y as Mi}from"./github-zip-BZcI0-aZ.js";import{a as Ni,c as Pi,d as Fi,f as Ii,i as Li,l as Ri,n as zi,o as Bi,p as Vi,r as Hi,s as Ui,u as Wi}from"./github-install-jWWA5n2X.js";import{n as Gi,t as Ki}from"./magick-wasm-DVJe3sB9.js";import{a as qi,c as Ji,i as Yi,l as Xi,n as Zi,o as Qi,r as $i,s as ea,t as ta,u as na}from"./installer-CyaKvN2m.js";import{t as ra}from"./local-llm-BHq5S7yF.js";import{t as ia}from"./client-BGJKiXya.js";import{t as aa}from"./redirect-uri-CbaLH4zl.js";var oa=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 sa(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 ca=r(`cdp`);var la=class{ws=null;nextId=1;_superseded=!1;pending=new oa;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,ca.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(ca.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(),ca.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),ca.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 sa(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;ca.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(ca.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;ca.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,ca.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):ca.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 ua=r(`har-recorder`);var da=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}`),ua.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=>{ua.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 fa(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ua.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 ua.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)),ua.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 ua.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 fa(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){ua.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ua.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const pa=`(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-DH1Mhm__.js";import{a as l,c as u,d,f,i as p,l as m,o as h,p as g,r as _,s as v,t as y,u as b}from"./proxied-fetch-CWqWgyRG.js";import{a as x,i as S,n as C,r as w,s as T,t as E}from"./src-CcFD5QfS.js";import{$t as D,An as O,At as ee,Bt as te,Cn as k,Ct as A,D as ne,Dn as re,Dt as ie,E as ae,En as oe,Et as se,Fn as ce,Ft as le,Gt as ue,Ht as de,In as j,It as fe,Jt as pe,Kt as me,L as he,Ln as M,Lt as ge,M as _e,Mn as ve,Mt as ye,Nn as N,Nt as P,On as be,Ot as xe,Pn as F,Pt as Se,Q as I,Qt as Ce,R as L,Rn as R,Rt as we,Sn as Te,St as Ee,Tn as De,Tt as z,Ut as Oe,V as ke,Vt as Ae,Wt as je,X as Me,Xt as Ne,Y as Pe,Yt as Fe,Z as Ie,Zt as Le,_n as Re,_t as ze,an as Be,at as Ve,bn as He,bt as Ue,cn as We,ct as eee,dn as Ge,dt as Ke,en as qe,et as Je,fn as B,ft as Ye,gn as Xe,gt as Ze,h as tee,hn as Qe,ht as $e,in as et,it as tt,jn as nt,jt as rt,kn as it,kt as at,ln as ot,lt as st,m as ct,mn as lt,mt as ut,nn as dt,nt as ft,on as pt,ot as nee,pn as mt,pt as ht,qt as gt,rn as _t,rt as vt,sn as yt,st as bt,tn as xt,tt as St,un as Ct,ut as wt,vn as V,vt as Tt,w as Et,wn as Dt,wt as Ot,xn as kt,xt as At,yn as jt,yt as Mt,zt as Nt}from"./account-store-BOO_CzoH.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-BfNg24Ce.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-Dcl0CQrv.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-B1Eib3Wt.js";import{a as aee,c as oee,i as bn,n as see,o as xn,r as Sn,s as Cn}from"./lick-urls-DEfVsxzt.js";import{C as wn,D as Tn,E as En,S as Dn,_ as On,a as kn,b as An,d as jn,g as Mn,h as Nn,m as Pn,n as Fn,o as In,r as Ln,s as Rn,t as zn,u as Bn,w as Vn,y as Hn}from"./db-DATxPCUz.js";import{a as Un,i as Wn,n as Gn,r as Kn}from"./tray-runtime-config-BoItLnrD.js";import{n as qn,r as Jn,t as Yn}from"./slicc-version-DV1WF_eM.js";import{a as Xn,c as Zn,d as Qn,i as $n,l as er,n as tr,o as nr,s as rr,t as ir,u as ar}from"./lick-manager-BJhAu_iX.js";import{a as or,n as sr,r as cr}from"./fs-Boij2gPF.js";import{a as lr,c as ur,i as dr,l as fr,n as pr,o as H,r as mr,s as hr}from"./cost-command-AOg9dLn6.js";import{_ as gr,a as _r,b as vr,c as yr,d as br,f as xr,g as Sr,h as Cr,i as cee,l as wr,m as Tr,n as lee,o as uee,p as dee,r as Er,s as fee,u as pee,v as mee,y as Dr}from"./skills-BKsLImdA.js";import{n as hee,t as gee}from"./llm-session-id-BZyXP_j2.js";import{n as _ee,r as vee}from"./frozen-archive-format--7sONywg.js";import{i as yee,r as bee}from"./browser-BAL8RehA.js";import{a as Or,i as kr,n as xee,r as See,t as Cee}from"./telemetry-BugxTkxX.js";import{n as Ar,t as jr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Mr,i as Nr,r as Pr,t as Fr}from"./git-config-DA8M5e8O.js";import{a as Ir,c as Lr,i as Rr,o as zr,r as Br,s as Vr,t as Hr}from"./script-catalog-Bt94D0RP.js";import{t as Ur}from"./process-manager-unCzdHp3.js";import{A as Wr,C as Gr,O as Kr,_ as qr,a as Jr,b as Yr,c as Xr,d as Zr,f as Qr,g as $r,h as ei,i as ti,k as ni,l as ri,m as ii,n as ai,o as oi,p as si,r as ci,s as li,t as ui,u as di,v as fi,x as pi,y as mi}from"./shared-DqziuFis.js";import{n as hi,t as gi}from"./esbuild-wasm-C_e51T2J.js";import{n as _i,t as vi}from"./wasm-compiler-Ct7QZURL.js";import{_ as yi,a as bi,c as xi,f as Si,g as Ci,h as wi,l as Ti,m as Ei,n as Di,p as Oi,r as ki,u as Ai,v as ji,y as Mi}from"./github-zip-7k6aGRi5.js";import{a as Ni,c as Pi,d as Fi,f as Ii,i as Li,l as Ri,n as zi,o as Bi,p as Vi,r as Hi,s as Ui,u as Wi}from"./github-install-B8nRAI8z.js";import{n as Gi,t as Ki}from"./magick-wasm-DVJe3sB9.js";import{a as qi,c as Ji,i as Yi,l as Xi,n as Zi,o as Qi,r as $i,s as ea,t as ta,u as na}from"./installer-CyaKvN2m.js";import{t as ra}from"./local-llm-Ca41QR9W.js";import{t as ia}from"./client-BGJKiXya.js";import{t as aa}from"./redirect-uri-DVwxCbAH.js";var oa=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 sa(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 ca=r(`cdp`);var la=class{ws=null;nextId=1;_superseded=!1;pending=new oa;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,ca.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(ca.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(),ca.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),ca.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 sa(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;ca.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(ca.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;ca.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,ca.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):ca.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 ua=r(`har-recorder`);var da=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}`),ua.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=>{ua.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 fa(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ua.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 ua.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)),ua.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 ua.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 fa(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){ua.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ua.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const pa=`(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 Cg(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 wg(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function Tg(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 Eg(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 Dg(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 Og(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 kg(e,t){let n=bg(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 Ag(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return kg(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 jg(e,t){let n=kg(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 Mg(e){let t=yg[e.type];return e.type===`session-reload`?xg(e,t):e.type===`upgrade`?Sg(e,t):e.type===`cherry`?Cg(e,t):e.type===`preview`?wg(e,t):e.type===`workflow`?Tg(e,t):e.type===`bash`?Eg(e,t):e.type===`sudo-request`?Dg(e,t):e.type===`navigate`?jg(e,t):e.type===`webhook`?Ag(e,t):e.type===`discovery`?Og(e,t):kg(e,t)}const Ng=new Map;function Pg(e){let t=Ng.get(e.id);t&&(Ng.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Fg=`slicc-sprinkle-routes`;function Ig(){try{let e=localStorage.getItem(Fg);return e?JSON.parse(e):{}}catch{return{}}}function Lg(e){try{localStorage.setItem(Fg,JSON.stringify(e))}catch{}}function Rg(e){return Ig()[e]}function zg(e,t){let n=Ig();n[e]=t,Lg(n)}function Bg(e){let t=Ig();delete t[e],Lg(t)}function Vg(){return Ig()}function Hg(e){switch(e){case`initializing`:return`creating`;case`processing`:return`running`;case`error`:return`failed`;case`ready`:return`ready`;default:return`creating`}}function Ug(e){if(wh(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 Wg(e,t){let n=wh(e);return{id:e.jid,parentId:e.parentJid,name:e.name,folder:e.folder,status:Hg(t?.status),display:{role:n?`primary`:`child`,label:e.assistantLabel},workspace:Ug(e),policy:Dh(e),completion:Oh(e)}}var Gg=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 Wg(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:Hg(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 Kg(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 qg=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=Kg(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 Gg(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 kh(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return Ah(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 Jg(e){let t=wh(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 Yg=`cone`;function Xg(e){return`session-${e.folder}`}function Zg(e){return e.toLowerCase().normalize(`NFKD`).replace(/\p{M}+/gu,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`cone`}function Qg(e,t){let n=new Set;for(let e of t)n.add(e.folder);if(!n.has(`cone`))return Yg;let r=`cone-${Zg(e)}`;if(!n.has(r))return r;for(let e=2;;e++){let t=`${r}-${e}`;if(!n.has(t))return t}}function $g(e){return wh(e)?`cone`:`scoop`}function e_(e){return wh(e)?`cone`:e.name??e.folder}const t_=r(`kernel-agent-event-stream`);var n_=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){t_.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}-${r_()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function r_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var i_=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=a_(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:wh(e),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=Ah(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function a_(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 o_={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function s_(){return{...o_}}function c_(){let e=s_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(Cn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const l_=new Set;function u_(e){return l_.add(e),()=>{l_.delete(e)}}function d_(){return f_(aee(),s_())}function f_(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 p_=`__slicc_binary__`;function m_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[p_]===`b64`&&typeof t.data==`string`}function h_(e){if(e instanceof Uint8Array)return{[p_]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(h_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=h_(r);return t}return e}function g_(e){if(m_(e))return f(e.data);if(Array.isArray(e))return e.map(g_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=g_(r);return t}return e}const __=r(`panel-transport`);function v_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function y_(){return{onMessage:e=>{let t=(t,n,r)=>(v_(t)&&e(g_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=h_(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)||__.error(`Offscreen → panel transport send failed`,{error:t})})}}}const b_=r(`kernel-bridge`);function x_(){return globalThis}function S_(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 C_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new i_;agentEventStream=new n_;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=y_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new mg;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-${w_()}`;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})},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:w_(),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(Xg(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()??[],d_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...d_()};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=S_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Rg(e),s=o?a.find(e=>e.name===o||e.folder===o||e.folder===`${o}-scoop`):void 0;if(s||=Ah(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Mg({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=Ah(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=Xg(t);this.sessionStore.saveMessages(n,e).catch(e=>{b_.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?Ah(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:e_(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=Xg(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){b_.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=Qg(e,this.orchestrator.getScoops()),n=t===Yg,r={...Kg({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:T_(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:e_(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:T_(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=Xg(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=Xg(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){b_.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}-${w_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?e_(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`){Pg(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=x_()[Rh];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&&wh(n)){if(Ah(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=Xg({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=x_().__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=x_().__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 w_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function T_(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 kg(e,t){let n=bg(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 Ag(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return kg(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 jg(e,t){let n=kg(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 Mg(e){let t=yg[e.type];return e.type===`session-reload`?xg(e,t):e.type===`upgrade`?Sg(e,t):e.type===`cherry`?Cg(e,t):e.type===`preview`?wg(e,t):e.type===`workflow`?Tg(e,t):e.type===`bash`?Eg(e,t):e.type===`sudo-request`?Dg(e,t):e.type===`navigate`?jg(e,t):e.type===`webhook`?Ag(e,t):e.type===`discovery`?Og(e,t):kg(e,t)}const Ng=new Map;function Pg(e){let t=Ng.get(e.id);t&&(Ng.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Fg=`slicc-sprinkle-routes`;function Ig(){try{let e=localStorage.getItem(Fg);return e?JSON.parse(e):{}}catch{return{}}}function Lg(e){try{localStorage.setItem(Fg,JSON.stringify(e))}catch{}}function Rg(e){return Ig()[e]}function zg(e,t){let n=Ig();n[e]=t,Lg(n)}function Bg(e){let t=Ig();delete t[e],Lg(t)}function Vg(){return Ig()}function Hg(e){switch(e){case`initializing`:return`creating`;case`processing`:return`running`;case`error`:return`failed`;case`ready`:return`ready`;default:return`creating`}}function Ug(e){if(wh(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 Wg(e,t){let n=wh(e);return{id:e.jid,parentId:e.parentJid,name:e.name,folder:e.folder,status:Hg(t?.status),display:{role:n?`primary`:`child`,label:e.assistantLabel},workspace:Ug(e),policy:Dh(e),completion:Oh(e)}}var Gg=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 Wg(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:Hg(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 Kg(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 qg=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=Kg(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 Gg(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 kh(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return Ah(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 Jg(e){let t=wh(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 Yg=`cone`;function Xg(e){return`session-${e.folder}`}function Zg(e){return e.toLowerCase().normalize(`NFKD`).replace(/\p{M}+/gu,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`cone`}function Qg(e,t){let n=new Set;for(let e of t)n.add(e.folder);if(!n.has(`cone`))return Yg;let r=`cone-${Zg(e)}`;if(!n.has(r))return r;for(let e=2;;e++){let t=`${r}-${e}`;if(!n.has(t))return t}}function $g(e){return wh(e)?`cone`:`scoop`}function e_(e){return wh(e)?`cone`:e.name??e.folder}const t_=r(`kernel-agent-event-stream`);var n_=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){t_.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}-${r_()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function r_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var i_=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=a_(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:wh(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=Ah(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function a_(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 o_={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function s_(){return{...o_}}function c_(){let e=s_();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(Cn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const l_=new Set;function u_(e){return l_.add(e),()=>{l_.delete(e)}}function d_(){return f_(aee(),s_())}function f_(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 p_=`__slicc_binary__`;function m_(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[p_]===`b64`&&typeof t.data==`string`}function h_(e){if(e instanceof Uint8Array)return{[p_]:`b64`,data:g(e)};if(Array.isArray(e))return e.map(h_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=h_(r);return t}return e}function g_(e){if(m_(e))return f(e.data);if(Array.isArray(e))return e.map(g_);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=g_(r);return t}return e}const __=r(`panel-transport`);function v_(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function y_(){return{onMessage:e=>{let t=(t,n,r)=>(v_(t)&&e(g_(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=h_(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)||__.error(`Offscreen → panel transport send failed`,{error:t})})}}}const b_=r(`kernel-bridge`);function x_(){return globalThis}function S_(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 C_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new i_;agentEventStream=new n_;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=y_(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new mg;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-${w_()}`;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})},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:w_(),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(Xg(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()??[],d_())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...d_()};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=S_(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Rg(e),s=o?a.find(e=>e.name===o||e.folder===o||e.folder===`${o}-scoop`):void 0;if(s||=Ah(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Mg({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=Ah(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=Xg(t);this.sessionStore.saveMessages(n,e).catch(e=>{b_.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?Ah(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:e_(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=Xg(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){b_.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=Qg(e,this.orchestrator.getScoops()),n=t===Yg,r={...Kg({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:T_(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:e_(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:T_(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=Xg(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=Xg(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){b_.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}-${w_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?e_(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`){Pg(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=x_()[Rh];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&&wh(n)){if(Ah(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=Xg({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=x_().__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=x_().__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 w_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function T_(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 E_=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function D_(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(E_.map(e=>O_(i,e,t,r)))).filter(e=>e!==null)}async function O_(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||!k_(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function k_(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 A_=r(`navigation-watcher`);function j_(e,t){return rr(e,t)}var M_=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}=j_(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=ar(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 D_(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){A_.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){A_.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){A_.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){A_.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){A_.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){A_.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){A_.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};function N_(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var P_=`# /etc/llmstxtignore — llms.txt discovery suppression
893
893
  #
894
894
  # One advertising hostname or glob per line. Matching is case-insensitive.
@@ -5419,7 +5419,7 @@ except BaseException:
5419
5419
  `)}}function yz(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=xz(e.stdin??``,o),c=lz(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:Wr},version:`v${Wr}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new gz(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var bz=class extends wP.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 gz){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 xz(e,t){return new bz(e,t)}function Sz(e){if(e===``)return[];let t=e.split(`
5420
5420
  `);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function Cz(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function wz(e){return new TextDecoder(`utf-8`).decode(DN(e))}function Tz(e){if(e&&typeof e.write==`function`)return e}var Ez=class extends vP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=Sz(wz(Cz(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 gz&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function Dz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=Tz(e.output)}else r=t,i=Tz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new Ez(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:Ez,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var Oz=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`?`: ${kz(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 kz(e){try{return JSON.stringify(e)}catch{return String(e)}}function Az(e){return new Promise(t=>setTimeout(t,e))}function jz(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 Mz(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 Nz(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function Pz(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 Fz(e){if(Nz(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 Iz(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 Lz(e){let t=e.sleep??Az;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=jz(n.baseUrl,o,s.params),l=Mz(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=Iz(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 Fz(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 Fz(m).catch(()=>null);throw new Oz(m.status,m.statusText,c,e)}let h=Pz(m.headers.get(`retry-after`)),g=500*2**a;await t(h===null?g:h)}if(f){let e=await Fz(f).catch(()=>null);throw new Oz(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 Rz(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 zz(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`,Rz(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 Bz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(zz(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 Vz(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 Hz(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:Vz(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Uz(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:Vz(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Vz(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Vz(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Hz(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Wz(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 Gz(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 Kz(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 Uz(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=Wz(c),d=Gz(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function qz(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 Jz(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=qz(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 Yz(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 Xz(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 Xz(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:Zz(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:Zz(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:Zz(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 Zz(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 Qz(e){return{findTab:t=>e.call(`browser`,`findTab`,[eB(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,tB(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[qz(t),$z(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[qz(t),$z(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[qz(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[qz(t),n]),fetch:(t,n,r={})=>Kz(n,r).then(n=>e.call(`browser`,`evalAsync`,[qz(t),n])),websocket:Jz(e)}}function $z(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 eB(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 tB(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function nB(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function rB(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:nB(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function iB(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 aB(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function oB(e){return e==null?[]:Array.isArray(e)?e:[e]}function sB(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:aB(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,iB(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,iB(r)]),receiveFeatureReport:async t=>aB((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 cB(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>sB(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[oB(t)]))[0];if(!n)throw Error(`No device selected.`);return sB(e,n)}}}function lB(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 uB=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 };`)}},dB=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=lB(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 uB(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 uB(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?.())}},fB=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 dB(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()}},pB=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 dB(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 fB(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 mB(e){let t=async t=>new pB(e),n=async(t,n)=>new pB(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const hB=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`]),gB={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 _B(e,t){let n=gB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function vB(e){return{...e,time:mz,fmt:iP,pool:uz}}function yB(e,t){return e?.startsWith(`/`)?hz(e):t}function bB(e){return e.includes(`require`)||e.includes(`import`)}async function xB(e,t,n,r){return bB(t)?e.call(`module`,`buildGraph`,[t,yB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function SB(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 CB(e){return{playwright:mB(e)}}function wB(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c}=e,l=new Map(t.files.map(e=>[e.path,e.cjsSource])),u=new Map(t.files.map(e=>[e.path,e.kind])),d=new Map,f=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:DB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=TB(t,n,r,i,c);if(a.hit)return a;if(hB.has(t))throw _B(e,t);if(ni.has(t))throw kB(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]):EB(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=hz(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`&&SB(o.exports),o.exports}return{require:e=>p(t.entryMap,e)}}function TB(e,t,n,r,i){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:CF}:e===`crypto`?{hit:!0,value:dF}: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:gP}:e===`assert/strict`?{hit:!0,value:hP}:e===`util`?{hit:!0,value:BP}:e===`events`?{hit:!0,value:yP}:e===`os`?{hit:!0,value:fF}:e===`tty`?{hit:!0,value:wF}:e===`stream`?{hit:!0,value:wP}:e===`url`?{hit:!0,value:DF}:e===`zlib`?{hit:!0,value:sz}:e===`readline`&&i?{hit:!0,value:i}:e===`readline/promises`&&i?{hit:!0,value:i.promises}:{hit:!1}}function EB(e){if(e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`node:`))return Error(`Cannot find module '${e}'`);let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0];return Error(`Cannot find module '${e}' (run: ipk install ${t})`)}function DB(e,t){let n=e.slice(7);if(n===``)throw Error(`require('sliccy:'): empty sliccy: module name`);if(!Object.prototype.hasOwnProperty.call(t,n))throw Error(`require('${e}'): unknown sliccy: module '${n}'. Known names: ${Object.keys(t).sort().join(`, `)}`);return t[n]}const OB={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function kB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${OB[t]||``}`)}async function AB(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";
5421
5421
  `:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof gz?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function jB(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?iB(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,iB(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function MB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>jB(e,t)),request:async t=>jB(e,await e.call(`serial`,`request`,[oB(t)]))}}function NB(e,t){let n=t.handle,r=e=>({status:e.status,data:aB(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,iB(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,iB(r)])}}function PB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>NB(e,t)),request:async t=>NB(e,await e.call(`usb`,`request`,[oB(t)]))}}function FB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function IB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function LB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function RB(e){let t=FB(e.argv[1]??``),n=LB(t,`references`),r=LB(t,`assets`),i=LB(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)+`
5422
- `),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 ${IB(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 zB=new Map,BB=new Map;function VB(e){let t=crypto.randomUUID();return zB.set(t,e),t}function HB(e){return zB.get(e)??null}function UB(e,t){if(!zB.has(e))return t.abort(),()=>{};let n=BB.get(e);return n||(n=new Set,BB.set(e,n)),n.add(t),()=>{let n=BB.get(e);n&&(n.delete(t),n.size===0&&BB.delete(e))}}function WB(e){zB.delete(e);let t=BB.get(e);if(t){BB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function GB(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 KB(e){let t=HB(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 GB(e)}}function qB(e){return`slicc-sync-fs-`+e}const JB=`sync-fs-ack`,YB=`sync-fs-res`,XB=6e5,ZB=5e3,QB=`exec`;function $B(e){return e.channel===QB}function eV(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 tV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,XB)}async function nV(e){let t=HB(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=eV(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()},tV(e.timeoutMs,XB)),o=UB(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`}:GB(e)}finally{clearTimeout(a),o()}}function rV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function iV(e){let t=oV(e);if(sV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw rV(`EIO`,e.label);cV(t,e.label)}function aV(e){let t=iV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw rV(`EIO`,e.label)}}function oV(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 rV(`EIO`,e.label)}return t}function sV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function cV(e,t){throw rV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function lV(e){return(t,n,r)=>{let i=aV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:QB})),timeoutMs:n+ZB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw rV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function uV(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 dV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??lV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&uV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=tV(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 fV(e,t){return rV(e,`sync-fs bridge, '${t}'`)}function pV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function mV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:pV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return iV(r(`GET`,e))},writeFile(e,t){iV(r(`POST`,e,t))},stat(e){let t=aV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw fV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=aV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw fV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=aV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw fV(`EIO`,e);return t},exists(e){let t=aV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw fV(`EIO`,e);return t},mkdir(e){iV(r(`POST`,e,void 0,`mkdir`))},rm(e){iV(r(`POST`,e,void 0,`rm`))}}}const hV=new TextEncoder,gV=new TextDecoder;function _V(e){if(!e.ok)return{status:4,payload:hV.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:hV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function vV(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(gV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(gV.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 yV(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 bV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function xV(e,t,n={}){let{header:r,window:i}=yV(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 rV(`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 rV(`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 rV(`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 rV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return vV(f,d)}}}function SV(e,t){return rV(e,`sync-sab bridge, '${t}'`)}function CV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function wV(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 SV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw SV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw SV(`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(!CV(t))throw SV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!CV(t))throw SV(`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 SV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw SV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function TV(e){return(t,n,r)=>{let i=e.call({...t,channel:QB},n+ZB,r);if(!i.ok)throw rV(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 rV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function EV(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 TN(r)}function DV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function OV(e,t){return t?wV(t):e.syncFsToken?mV(e.syncFsToken):void 0}function kV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return xV(e.syncSab,t)}function AV(e,t,n,r,i){let a=kV(e,t),o=OV(e,a);if(Object.assign(r,GN(n,e.cwd,o,i)),e.syncFsToken)return dV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:TV(a)}:{}})}function jV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:qn().version,writable:!1,enumerable:!1,configurable:!1})}function MV(e,t,n){let r=JN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:KN({writeStdout:t,writeStderr:n,exit:e=>{throw new gz(e)},color:r})}}function NV(e,t,n){return{readStdinBytes:()=>DN(e.stdin??``),writeStdout:t,writeStderr:n}}function PV(e){return{usbBridge:PB(e),serialBridge:MB(e),hidBridge:cB(e)}}async function FV(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=vz(i,a),s=yz(e,i,a),{colorApi:c,cliApi:l}=MV(!!e.env?.NO_COLOR,i,a),u=new IM(t),d=NV(e,i,a),f=zN(u,C,d),p=await EV(u,e.cwd,DV(e,a)),m=AV(e,t,p,f,d),h=rB(u,p,e.cwd,a),g=Bz(h,{cwd:e.cwd}),_=RB({argv:e.argv,fs:f,exec:h}),v=Qz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=PV(u),S=Lz({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 Yz(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=vB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=hz(T),D=await xB(u,e.code,e.cwd,T),O=wB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:YP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:CB(u),nodeReadline:Dz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;jV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await AB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await IV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await LV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function IV(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 LV(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 RV(){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 zV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=RV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&FV(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 BV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=RV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&qM(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 VV=zV(),HV=BV();function UV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?GV():HV({kind:e,ctx:t}):typeof Worker<`u`?WV():VV({kind:e,ctx:t})}function WV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return KV(new Worker(new URL(`/assets/js-realm-worker-BA0s-HAh.js`,``+import.meta.url),{type:`module`}))}function GV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return KV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function KV(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 qV(){if(Qr())return decodeURIComponent(ei(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function JV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function YV(e){return e instanceof Error?e.message:String(e)}function XV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function ZV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:XV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function QV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:XV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const $V=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,eH=/\bimport\s*\.\s*meta\b/g;function tH(e,t){let n=JSON.stringify(t);return e.replace($V,n).replace(eH,`({ url: ${n} })`)}async function nH(e,t,n,r){let i=await e();return i.transpileModule(tH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function rH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>hi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>di(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Yr(e))return e;let a=JV(t),o;try{return await ZV(n,e,t,a)}catch(e){o=e}try{return await nH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${YV(o)}; typescript fallback: ${YV(e)}`)}}}function iH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>hi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>di(t));return async({source:e,filename:t})=>{if(!Yr(e)&&!mi(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?JV(t):void 0,o=i?t:`[eval].js`,s;try{return await QV(n,e,t,a)}catch(e){s=e}try{return await nH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${YV(s)}; typescript fallback: ${YV(e)}`)}}}function aH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
5422
+ `),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 ${IB(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 zB=new Map,BB=new Map;function VB(e){let t=crypto.randomUUID();return zB.set(t,e),t}function HB(e){return zB.get(e)??null}function UB(e,t){if(!zB.has(e))return t.abort(),()=>{};let n=BB.get(e);return n||(n=new Set,BB.set(e,n)),n.add(t),()=>{let n=BB.get(e);n&&(n.delete(t),n.size===0&&BB.delete(e))}}function WB(e){zB.delete(e);let t=BB.get(e);if(t){BB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function GB(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 KB(e){let t=HB(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 GB(e)}}function qB(e){return`slicc-sync-fs-`+e}const JB=`sync-fs-ack`,YB=`sync-fs-res`,XB=6e5,ZB=5e3,QB=`exec`;function $B(e){return e.channel===QB}function eV(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 tV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,XB)}async function nV(e){let t=HB(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=eV(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()},tV(e.timeoutMs,XB)),o=UB(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`}:GB(e)}finally{clearTimeout(a),o()}}function rV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function iV(e){let t=oV(e);if(sV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw rV(`EIO`,e.label);cV(t,e.label)}function aV(e){let t=iV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw rV(`EIO`,e.label)}}function oV(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 rV(`EIO`,e.label)}return t}function sV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function cV(e,t){throw rV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function lV(e){return(t,n,r)=>{let i=aV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:QB})),timeoutMs:n+ZB,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw rV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function uV(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 dV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??lV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&uV(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=tV(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 fV(e,t){return rV(e,`sync-fs bridge, '${t}'`)}function pV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function mV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:pV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return iV(r(`GET`,e))},writeFile(e,t){iV(r(`POST`,e,t))},stat(e){let t=aV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw fV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=aV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw fV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=aV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw fV(`EIO`,e);return t},exists(e){let t=aV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw fV(`EIO`,e);return t},mkdir(e){iV(r(`POST`,e,void 0,`mkdir`))},rm(e){iV(r(`POST`,e,void 0,`rm`))}}}const hV=new TextEncoder,gV=new TextDecoder;function _V(e){if(!e.ok)return{status:4,payload:hV.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:hV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function vV(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(gV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(gV.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 yV(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 bV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function xV(e,t,n={}){let{header:r,window:i}=yV(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 rV(`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 rV(`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 rV(`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 rV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return vV(f,d)}}}function SV(e,t){return rV(e,`sync-sab bridge, '${t}'`)}function CV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function wV(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 SV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw SV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw SV(`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(!CV(t))throw SV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!CV(t))throw SV(`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 SV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw SV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function TV(e){return(t,n,r)=>{let i=e.call({...t,channel:QB},n+ZB,r);if(!i.ok)throw rV(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 rV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function EV(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 TN(r)}function DV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function OV(e,t){return t?wV(t):e.syncFsToken?mV(e.syncFsToken):void 0}function kV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return xV(e.syncSab,t)}function AV(e,t,n,r,i){let a=kV(e,t),o=OV(e,a);if(Object.assign(r,GN(n,e.cwd,o,i)),e.syncFsToken)return dV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:TV(a)}:{}})}function jV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:qn().version,writable:!1,enumerable:!1,configurable:!1})}function MV(e,t,n){let r=JN({isTTY:!e,noColor:e});return{colorApi:r,cliApi:KN({writeStdout:t,writeStderr:n,exit:e=>{throw new gz(e)},color:r})}}function NV(e,t,n){return{readStdinBytes:()=>DN(e.stdin??``),writeStdout:t,writeStderr:n}}function PV(e){return{usbBridge:PB(e),serialBridge:MB(e),hidBridge:cB(e)}}async function FV(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=vz(i,a),s=yz(e,i,a),{colorApi:c,cliApi:l}=MV(!!e.env?.NO_COLOR,i,a),u=new IM(t),d=NV(e,i,a),f=zN(u,C,d),p=await EV(u,e.cwd,DV(e,a)),m=AV(e,t,p,f,d),h=rB(u,p,e.cwd,a),g=Bz(h,{cwd:e.cwd}),_=RB({argv:e.argv,fs:f,exec:h}),v=Qz(u),{usbBridge:y,serialBridge:b,hidBridge:x}=PV(u),S=Lz({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 Yz(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=vB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=hz(T),D=await xB(u,e.code,e.cwd,T),O=wB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:YP(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:CB(u),nodeReadline:Dz({output:{write:i},onExit:s.recordExit})}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,k=D.entrySource??e.code,A=globalThis;jV(),A.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ne=await AB(k,{process:s.processShim,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await IV(u,p,a),s.getDidCallProcessExit()?ne=s.getExitCode():await LV(u),delete A.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function IV(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 LV(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 RV(){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 zV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=RV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&FV(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 BV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=RV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&qM(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 VV=zV(),HV=BV();function UV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?GV():HV({kind:e,ctx:t}):typeof Worker<`u`?WV():VV({kind:e,ctx:t})}function WV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return KV(new Worker(new URL(`/assets/js-realm-worker-BH_Uhjou.js`,``+import.meta.url),{type:`module`}))}function GV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return KV(new Worker(new URL(`/assets/py-realm-worker-C-Ej3Sv5.js`,``+import.meta.url),{type:`module`}))}function KV(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 qV(){if(Qr())return decodeURIComponent(ei(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function JV(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function YV(e){return e instanceof Error?e.message:String(e)}function XV(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function ZV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:XV(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function QV(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:XV(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const $V=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,eH=/\bimport\s*\.\s*meta\b/g;function tH(e,t){let n=JSON.stringify(t);return e.replace($V,n).replace(eH,`({ url: ${n} })`)}async function nH(e,t,n,r){let i=await e();return i.transpileModule(tH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function rH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>hi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>di(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!Yr(e))return e;let a=JV(t),o;try{return await ZV(n,e,t,a)}catch(e){o=e}try{return await nH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${YV(o)}; typescript fallback: ${YV(e)}`)}}}function iH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>hi(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>di(t));return async({source:e,filename:t})=>{if(!Yr(e)&&!mi(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?JV(t):void 0,o=i?t:`[eval].js`,s;try{return await QV(n,e,t,a)}catch(e){s=e}try{return await nH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${YV(s)}; typescript fallback: ${YV(e)}`)}}}function aH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
5423
5423
  `);return t===-1?``:e.slice(t+1)}function oH(e){return zt(e).dir}const sH=[`node`,`require`,`default`],cH=[`node`,`import`,`default`],lH=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,uH=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,dH=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,fH=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,pH=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function mH(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function hH(e){let t=pi(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!mH(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(lH,`require`,`require`),r(uH,`import`,`import`),r(dH,`import`,`import`),r(fH,`import`,`export`),r(pH,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function gH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=aH(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 _H(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??sH,s=e.importConditions??cH,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 gH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=oH(e),p={};for(let{specifier:t,kind:i}of hH(n)){let n;try{n=await Gr(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 Gr(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 vH(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||Kr.has(e)||hB.has(e))}async function yH(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 hH(t))if(vH(e))try{let t=await _H({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?cH:sH,requireConditions:sH,importConditions:cH});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&&(Yr(t)||mi(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 bH(){return globalThis.navigator?.hid??null}function xH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function SH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&xH(e)===xH(t)&&!!e.productName}var CH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(SH(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 wH=null;function TH(){return wH||=new CH,wH}const EH=4194304;function DH(e,t){let n=t.collections?.[0];return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...n?.usagePage===void 0?{}:{usagePage:n.usagePage},...n?.usage===void 0?{}:{usage:n.usage},opened:t.opened}}function OH(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function kH(e){e.opened||await e.open()}function AH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${EH}-byte (4 MiB) v1 limit`)}function jH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function MH(e,t){return(await t.getDevices()).map(t=>DH(e.register(t),t))}async function NH(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>DH(e.register(t),t))}function PH(e,t){return DH(t,OH(e,t))}async function FH(e,t){await OH(e,t).open()}async function IH(e,t){await OH(e,t).close()}async function LH(e,t,n,r){AH(r.byteLength,`send report payload`);let i=OH(e,t);await kH(i),await i.sendReport(n,r)}async function RH(e,t,n,r){AH(r.byteLength,`send feature report payload`);let i=OH(e,t);await kH(i),await i.sendFeatureReport(n,r)}async function zH(e,t,n){let r=OH(e,t);return await kH(r),{reportId:n,bytes:jH(await r.receiveFeatureReport(n))}}async function BH(e,t,n){let r=OH(e,t);await kH(r);let i=e=>{n({reportId:e.reportId,bytes:jH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const VH=6e4;function HH(){return an()}function UH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),VH);rn(`hid-device`,e??[],void 0,{timeoutMs:VH}).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 WH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var GH=class{registry;constructor(e){this.registry=e}hid(){let e=bH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return MH(this.registry,this.hid())}async request(e){if(HH()){let t=await UH(e);if(`cancelled`in t)throw Error(`user cancelled the HID picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquireAll(t.info);if(n.length===0)throw Error(`granted device could not be re-acquired`);return n.map(e=>DH(this.registry.register(e),e))}return NH(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(PH(this.registry,e))}open(e){return FH(this.registry,e)}close(e){return IH(this.registry,e)}sendReport(e,t,n){return LH(this.registry,e,t,WH(n))}sendFeatureReport(e,t,n){return RH(this.registry,e,t,WH(n))}async receiveFeatureReport(e,t){let n=await zH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return BH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},KH=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:WH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:WH(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 qH(e,t){return e&&bH()?new GH(TH()):t?new KH(t):null}function JH(e){return async function(t,n){let r=t instanceof Request?t:null,i=YH(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=ZH(r?.headers,n?.headers),s=await eU(n,r,a,o);s.defaultContentType&&!QH(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 YH(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function XH(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 ZH(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=XH(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function QH(e,t){return $H(e,t)!==void 0}function $H(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function eU(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=rU(e.body,n);return{body:await tU(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=$H(r,`content-type`)??``,a=e&&(!i||!d(i));return{body:n.byteLength===0?void 0:a?iU(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function tU(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 iU(e);if(e instanceof ArrayBuffer)return iU(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return iU(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return iU(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 nU(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function rU(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!nU(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function iU(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 aU(){return globalThis.navigator?.serial??null}var oU=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 sU=null;function cU(){return sU||=new oU,sU}const lU=4194304;function uU(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 dU(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function fU(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function pU(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 mU(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return uU(n,e.get(n))})}async function hU(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return uU(i,e.get(i))}function gU(e,t){return uU(t,dU(e,t))}async function _U(e,t,n){let r=dU(e,t);await r.port.open(n),r.opened=!0}async function vU(e,t){let n=dU(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 yU(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 bU(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 xU(e,t,n){let r=dU(e,t),i=Math.min(n.maxBytes??4194304,lU),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=pU(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=yU(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=fU(c,a.value);let e=u();if(e)return e}}return c}async function SU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${lU}-byte (4 MiB) v1 limit`);return await bU(dU(e,t)).write(n),n.length}async function CU(e,t){return dU(e,t).port.getSignals()}async function wU(e,t,n){await dU(e,t).port.setSignals(n)}const TU=6e4;function EU(){return an()}function DU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),TU);rn(`serial-port`,e??[],void 0,{timeoutMs:TU}).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 OU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var kU=class{registry;constructor(e){this.registry=e}serial(){let e=aU();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return mU(this.registry,this.serial())}async request(e){if(EU()){let t=await DU(e);if(`cancelled`in t)throw Error(`user cancelled the serial picker`);if(`error`in t)throw Error(t.error);let n=await this.reacquire(t.info);if(!n)throw Error(`granted port could not be re-acquired`);let r=this.registry.register(n);return uU(r,this.registry.get(r))}return hU(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(gU(this.registry,e))}open(e,t){return _U(this.registry,e,t)}close(e){return vU(this.registry,e)}read(e,t){return xU(this.registry,e,t)}write(e,t){return SU(this.registry,e,t)}getSignals(e){return CU(this.registry,e)}setSignals(e,t){return wU(this.registry,e,t)}},AU=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?OU(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:OU(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 jU(e,t){return e&&aU()?new kU(cU()):t?new AU(t):null}function MU(){return globalThis.navigator?.usb??null}function NU(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var PU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(NU(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 FU=null;function IU(){return FU||=new PU,FU}const LU=4194304;function RU(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 zU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function BU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${LU}-byte (4 MiB) v1 limit`)}function VU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function HU(e,t){return(await t.getDevices()).map(t=>RU(e.register(t),t))}async function UU(e,t,n){let r=await t.requestDevice({filters:n});return RU(e.register(r),r)}function WU(e,t){return RU(t,zU(e,t))}async function GU(e,t){await zU(e,t).open()}async function KU(e,t){await zU(e,t).close()}async function qU(e,t,n){await zU(e,t).selectConfiguration(n)}async function JU(e,t,n){await zU(e,t).claimInterface(n)}async function YU(e,t,n){await zU(e,t).releaseInterface(n)}async function XU(e,t,n,r){BU(r,`control-in length`);let i=await zU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?VU(i.data):new ArrayBuffer(0)}}async function ZU(e,t,n,r){BU(r.byteLength,`control-out payload`);let i=await zU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function QU(e,t,n,r){BU(r,`transfer-in length`);let i=await zU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?VU(i.data):new ArrayBuffer(0)}}async function $U(e,t,n,r){BU(r.byteLength,`transfer-out payload`);let i=await zU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function eW(e,t){await zU(e,t).reset()}const tW=6e4;function nW(){return an()}function rW(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),tW);rn(`usb-device`,e??[],void 0,{timeoutMs:tW}).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 iW(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var aW=class{registry;constructor(e){this.registry=e}usb(){let e=MU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return HU(this.registry,this.usb())}async request(e){if(nW()){let t=await rW(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 RU(this.registry.register(n),n)}return UU(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(WU(this.registry,e))}open(e){return GU(this.registry,e)}close(e){return KU(this.registry,e)}selectConfig(e,t){return qU(this.registry,e,t)}claim(e,t){return JU(this.registry,e,t)}release(e,t){return YU(this.registry,e,t)}async controlIn(e,t,n){let r=await XU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return ZU(this.registry,e,t,iW(n))}async transferIn(e,t,n){let r=await QU(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return $U(this.registry,e,t,iW(n))}reset(e){return eW(this.registry,e)}},oW=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:iW(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:iW(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function sW(e,t){return e&&MU()?new aW(IU()):t?new oW(t):null}function cW(e,t,n,r={}){let{header:i,window:a}=yV(t),o=new Map,s=!1,c=r.dispatch??(e=>$B(e)?nV(e):KB(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}=_V(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 lW=r(`realm-host`);function uW(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?VB({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;dW(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?cW(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&WB(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 dW(e,t,n,r,i,a){try{let o=await fW(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=tG(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 fW(e,t,n,r,i){switch(e.channel){case`vfs`:return vW(e.op,e.args,t);case`exec`:return jW(e.op,e.args,t,i);case`fetch`:return FW(e.op,e.args,t);case`browser`:return zW(e.op,e.args,pW(n),n);case`usb`:return QW(e.op,e.args,hW(n));case`serial`:return $W(e.op,e.args,gW(n));case`hid`:return eG(e.op,e.args,_W(n),r);case`module`:return LW(e.op,e.args,t);case`wasm`:return RW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function pW(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 mW(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 hW(e){if(e.usbBackend)return e.usbBackend;let t=sW(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function gW(e){if(e.serialBackend)return e.serialBackend;let t=jU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function _W(e){if(e.hidBackend)return e.hidBackend;let t=qH(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function vW(e,t,n){let r=typeof t[0]==`string`?t[0]:null,i=r===null?null:n.fs.resolvePath(n.cwd,r);switch(e){case`readFile`:return n.fs.readFile(i);case`readFileBinary`:return n.fs.readFileBuffer(i);case`writeFile`:return await n.fs.writeFile(i,t[1]),!0;case`writeFileBinary`:return await n.fs.writeFile(i,t[1]),!0;case`readDir`:return n.fs.readdir(i);case`exists`:return n.fs.exists(i);case`stat`:{let e=await n.fs.stat(i);return{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}case`mkdir`:return await n.fs.mkdir(i,{recursive:!0}),!0;case`rm`:return await n.fs.rm(i,{recursive:!0}),!0;case`rename`:{let e=n.fs.resolvePath(n.cwd,t[1]),r=n.fs;if(r.rename)await r.rename(i,e);else{let t=await n.fs.readFileBuffer(i);await n.fs.writeFile(e,t),await n.fs.rm(i,{recursive:!0})}return!0}case`resolvePath`:return n.fs.resolvePath(n.cwd,t[0]);case`invalidatePaths`:{let e=t[0],r=n.fs;return r.invalidatePaths&&r.invalidatePaths(e),!0}case`snapshot`:return DW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await OW(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const yW=10485760;function bW(e){return e.fileCount>=500||e.totalBytes>=yW}function xW(e){return e.entries.length>=2e4}async function SW(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 CW(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 wW(e,t,n,r,i){if(n>1048576||bW(r)||r.totalBytes+n>yW){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 TW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function TW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await SW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function EW(e,t,n){if(xW(n))return;let r=[t];for(;r.length>0;){if(xW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await CW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await SW(e,t,r,n):a.isFile&&await wW(e,t,a.size,n,r)}}async function DW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await EW(e,t,n),t!==`/tmp`&&await EW(e,`/tmp`,n),{entries:n.entries}}async function OW(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 kW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),AW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function jW(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 NW(t,n,r);if(e===`kill`)return PW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function MW(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 NW(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??{};MW(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 PW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&kW.has(r)?r:`SIGTERM`;AW.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 FW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?JH(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 IW(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 LW(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=IW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return yH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:rH({ipk:s}),transpileEntry:iH({ipk:s})})}async function RW(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 vi(e=>n.fs.readFileBuffer(e),i)}async function zW(e,t,n,r){switch(e){case`findTab`:return HW(n,t[0]??{});case`ensureTab`:{let e=t[0];return UW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return WW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return WW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return JW(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return YW(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await mW(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return mW(r).update(e,n)}case`wsClose`:{let e=t[0];return mW(r).close(e)}case`wsList`:return mW(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 qW(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function BW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function VW(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=BW()?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){lW.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function HW(e,t){let n=await VW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=XW(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 UW(e,t,n){let r=await VW(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=ZW(t);if(e){let t=r.find(t=>ZW(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function WW(e,t,n,r){return e.withTab(t,async()=>GW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function GW(e){if(typeof e!=`string`)return e;let t=KW(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=KW(t);if(typeof e==`object`&&e)return e}return t}return e}function KW(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 qW(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(){
5424
5424
  try {
5425
5425
  var entries = performance.getEntriesByType('resource');
@@ -5542,7 +5542,7 @@ Examples:
5542
5542
  skill list
5543
5543
  skill info bluebubbles
5544
5544
  skill read bluebubbles
5545
- `,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-BmQBvY-R.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${QG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:eK(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
5545
+ `,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-BKsLImdA.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${QG()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:eK(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
5546
5546
  `,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:tK(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
5547
5547
  `,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+`
5548
5548
  `,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 iK=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&Zn(e),error:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters`,apply:(e,t)=>{e.branch=t}},{names:[`--from`],validate:e=>Li(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=>er(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 aK(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=iK.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 oK(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function sK(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 cK(e,t,n,r){let i=await sK(e,t);return Oi(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?oK(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function lK(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await cK(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 Ei(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 uK(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 Ti(t),d=await Ii(s,c,o.ref,u,!0);if(d&&r.sha===d&&await dK(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await fK(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 lK(e,`${Ci}/${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 _K(e,{changes:h,writes:g,removals:_}),await Vi(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 dK(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 fK(e,t,n,r,i,a,o){let s=await ki(e,t,a,i??`main`);if(s.status===`ok`){let i=bi(s.files),a=n||pK(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:gK(i,a),path:a}}try{return{files:hK(mK(await Di(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 pK(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 mK(e){return new Map([...e].filter(([e])=>xi(e)))}function hK(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function gK(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);xi(e)&&r.set(e,i)}return hK(r)}async function _K(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 vK(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 XG(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${Ci}/${n}/SKILL.md`,u=await sK(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&JG(new TextDecoder().decode(u))===JG(c.content);if(oK(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${Ci}/${n}`,{recursive:!0}),await e.writeFile(l,d),await Vi(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function yK(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 bK(e,t,n,r){let i=Li(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 xK(e,t,n){if(t.length===0)return{targets:await Wi(e),missing:[]};let r=[],i=[];for(let a of t){let t=await Fi(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?bK(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 SK(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
@@ -5576,7 +5576,7 @@ Nothing to update — all skills are current.
5576
5576
  `,{stdout:s,stderr:``,exitCode:0}}function IK(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
5577
5577
  `,exitCode:1}:Zn(e)?null:{stdout:``,stderr:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters
5578
5578
  `,exitCode:1}}function LK(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`||!er(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
5579
- `,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=IK(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 RK(e){let t=await(await import(`./skills-BmQBvY-R.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${QG()}`,stderr:``,exitCode:0}:{stdout:eK(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function zK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-BmQBvY-R.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 Fi(n,t),a=i?Ri(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:tK(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+`
5579
+ `,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=IK(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 RK(e){let t=await(await import(`./skills-BKsLImdA.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${QG()}`,stderr:``,exitCode:0}:{stdout:eK(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function zK(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-BKsLImdA.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 Fi(n,t),a=i?Ri(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:tK(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+`
5580
5580
  `,stderr:``,exitCode:0}}async function BK(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 Bi(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 VK(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 zi(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 HK(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await zi(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 UK(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 WK(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await Ti(r),l=await Hi(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:UK(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:UK(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 ki(i,a,r,o);if(e.status===`ok`){let r=await Ii(i,a,o,c),s=await BK(u,i,a,bi(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 VK(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await HK(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 Pi()),{stdout:p,stderr:m,exitCode:+!!m}}async function GK(e,t,n,r){switch(e[0]){case`tabs`:return PK(t,n,r,e.includes(`--json`));case`recommendations`:return FK(t,n,e.includes(`--install`));case`update`:case`upgrade`:return wK(e.slice(1),t,n);case`list`:return RK(t);case`info`:case`read`:return zK(e[0],e[1],t);case`search`:return qK(e,n);default:return null}}function KK(e,t,n){return H(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return nK();let a=await GK(r,e,t,n);if(a)return a;let o=LK(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return nK();if(o.sourceRef.startsWith(`tessl:`))return JK(o.sourceRef,o.force,e,t);let s=GG(o.sourceRef);if(s)return ZG(s.hostname,s.task,e,t,o.force);let c=Li(o.sourceRef);return c?WK(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 qK(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?kK(a,t,i):nK()}async function JK(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
5581
5581
  `,exitCode:1};let a=await EK(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await Ti(r);return zi(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function YK(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
5582
5582
 
@@ -6979,7 +6979,7 @@ Common base URLs:
6979
6979
  llama.cpp http://localhost:8080/v1
6980
6980
  vLLM http://localhost:8000/v1
6981
6981
  Jan http://localhost:1337/v1
6982
- `}function kae(){return H(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Oae(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-8bWQwrlg.js`),{verifyConnection:a}=await import(`./local-llm-BHq5S7yF.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(Q6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
6982
+ `}function kae(){return H(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Oae(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-BWmqGvFK.js`),{verifyConnection:a}=await import(`./local-llm-Ca41QR9W.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(Q6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
6983
6983
  `,exitCode:1};let c=await a(s,t(Q6)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
6984
6984
  `)+`
6985
6985
  `,exitCode:1}}if(o===`discover`){let e=n(Q6)??``;return i(Q6,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
@@ -7023,20 +7023,20 @@ authorization-code flow, stores the access token, and retries.
7023
7023
  On success, the server is persisted to /workspace/.mcp/servers.json and
7024
7024
  an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
7025
7025
  short name resolves on the PATH.
7026
- `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CG5kLFp1.js`).then(e=>e.r);if(await a(i,t.fs))return n8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await Iae(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>s8(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await toe(i,t);let m=await u8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BVorzuId.js`);e({name:i,serverUrl:r,auth:u})}return t8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${e8}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
7026
+ `);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-CEccVDd7.js`).then(e=>e.r);if(await a(i,t.fs))return n8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.js`).then(e=>e.n),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await Iae(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>s8(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await toe(i,t);let m=await u8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-xByUgvpM.js`);e({name:i,serverUrl:r,auth:u})}return t8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${e8}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
7027
7027
  `)+`
7028
- `)}async function Iae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r),c=await $ae(r.oauthFetchImpl),l=r.oauthLauncher??await c8(),u=await i(e,n,c);$6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await aa(),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 Lae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp list
7029
- `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-BVorzuId.js`);await n();let{listServers:r}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return t8(r8(o))}function r8(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
7028
+ `)}async function Iae(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r),c=await $ae(r.oauthFetchImpl),l=r.oauthLauncher??await c8(),u=await i(e,n,c);$6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await aa(),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 Lae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp list
7029
+ `);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-xByUgvpM.js`);await n();let{listServers:r}=await import(`./store-CEccVDd7.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return t8(r8(o))}function r8(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
7030
7030
  `)+`
7031
7031
  `}async function Rae(e,t){if(qX(e))return t8(`usage: mcp search <query>
7032
7032
 
7033
7033
  Case-insensitive substring search across the cached tools of every
7034
7034
  registered MCP server. Matches tool name OR description and prints a
7035
7035
  table of (server, tool, description, match-field) rows.
7036
- `);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-BVorzuId.js`);await i();let{listServers:a}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return t8(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,zae(e.description),e.match]);return t8(r8(l))}function zae(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Bae(e,t){if(e.length===0||qX(e))return e.length===0?n8(`mcp delete: expected <name>`):t8(`usage: mcp delete <name>
7037
- `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-BVorzuId.js`);await r(n);let{deleteServer:a}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),o=await a(n,t.fs);await noe(n,t),await roe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){$6.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?n8(`mcp delete: no server, alias, or account found for "${n}"`):t8([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
7036
+ `);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-xByUgvpM.js`);await i();let{listServers:a}=await import(`./store-CEccVDd7.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return t8(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,zae(e.description),e.match]);return t8(r8(l))}function zae(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function Bae(e,t){if(e.length===0||qX(e))return e.length===0?n8(`mcp delete: expected <name>`):t8(`usage: mcp delete <name>
7037
+ `);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-xByUgvpM.js`);await r(n);let{deleteServer:a}=await import(`./store-CEccVDd7.js`).then(e=>e.r),o=await a(n,t.fs);await noe(n,t),await roe(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){$6.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?n8(`mcp delete: no server, alias, or account found for "${n}"`):t8([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
7038
7038
  `)+`
7039
- `)}async function Vae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(Uae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-BVorzuId.js`);await i(n);let{getServer:a}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return n8(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return t8(Wae(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return n8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=Hae(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return t8(Gae(n,l));let p=Kae(d,l.inputSchema);if(!p.ok)return n8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BGJKiXya.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=Xae(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function Hae(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=i8(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=i8(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function i8(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function Uae(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
7039
+ `)}async function Vae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(Uae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-xByUgvpM.js`);await i(n);let{getServer:a}=await import(`./store-CEccVDd7.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return n8(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return t8(Wae(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return n8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=Hae(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return t8(Gae(n,l));let p=Kae(d,l.inputSchema);if(!p.ok)return n8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BGJKiXya.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=Xae(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function Hae(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=i8(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=i8(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function i8(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function Uae(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
7040
7040
 
7041
7041
  mcp invoke <name> List tools on <name>.
7042
7042
  mcp invoke <name> <tool> --help Show flags for <tool>.
@@ -7066,7 +7066,7 @@ Arguments are coerced according to the tool's JSON Schema:
7066
7066
 
7067
7067
  Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
7068
7068
  OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
7069
- `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-BVorzuId.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return n8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return n8(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,protocolVersion:l.getNegotiatedProtocolVersion(),tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await u8(n,d,t);return t8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function Qae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp auth <name> [--silent | --interactive]
7069
+ `);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-xByUgvpM.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-CEccVDd7.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return n8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BGJKiXya.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return n8(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,protocolVersion:l.getNegotiatedProtocolVersion(),tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await u8(n,d,t);return t8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function Qae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp auth <name> [--silent | --interactive]
7070
7070
 
7071
7071
  Re-authenticate an existing MCP server. By default, attempts a silent
7072
7072
  token renewal using the persisted refresh_token; if that returns no
@@ -7078,7 +7078,7 @@ Options:
7078
7078
  -i, --interactive Skip silent renewal and open the OAuth popup
7079
7079
  directly. Use after revoking a refresh token or
7080
7080
  when the AS no longer accepts the cached one.
7081
- `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BVorzuId.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-CG5kLFp1.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return n8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return n8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return n8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-D2Pn4dpP.js`).then(e=>e.r),f=d(u);if(!f)return n8(`mcp auth: provider "${u}" is not registered`);if(a)return await o8(r,f,t);if(!f.onSilentRenew)return i?n8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await o8(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return n8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);$6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?t8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?n8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await o8(r,f,t)}async function o8(e,t,n){if(!t.onOAuthLogin)return n8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await c8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?t8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):n8(`mcp auth: interactive login for "${e}" did not complete`)}async function s8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-D2Pn4dpP.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){$6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function c8(){let{createOAuthLauncher:e}=await import(`./oauth-service-DNcIcWT8.js`);return e()}async function $ae(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function l8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BFiiSgrN.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 eoe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
7081
+ `);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-xByUgvpM.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-CEccVDd7.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return n8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return n8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return n8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-DH1Mhm__.js`).then(e=>e.r),f=d(u);if(!f)return n8(`mcp auth: provider "${u}" is not registered`);if(a)return await o8(r,f,t);if(!f.onSilentRenew)return i?n8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await o8(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return n8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);$6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?t8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?n8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await o8(r,f,t)}async function o8(e,t,n){if(!t.onOAuthLogin)return n8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await c8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?t8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):n8(`mcp auth: interactive login for "${e}" did not complete`)}async function s8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-DH1Mhm__.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){$6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function c8(){let{createOAuthLauncher:e}=await import(`./oauth-service-DNcIcWT8.js`);return e()}async function $ae(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function l8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-Boij2gPF.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 eoe(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
7082
7082
  // Auto-generated by \`mcp add ${e}\`; do not edit by hand.
7083
7083
  const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
7084
7084
  const escape = (s) => {
@@ -7092,7 +7092,7 @@ const r = await exec(cmd);
7092
7092
  if (r.stdout) process.stdout.write(r.stdout);
7093
7093
  if (r.stderr) process.stderr.write(r.stderr);
7094
7094
  process.exit(r.exitCode || 0);
7095
- `}async function toe(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,eoe(e)),t.scriptCatalog?.invalidateJsh()}async function noe(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function roe(e,t){let{removeAppSprinkles:n}=await import(`./apps-DgC8YSsY.js`);await n(e,t.fs)}async function u8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-DgC8YSsY.js`);return(await r(e,t,n.fs)).length}catch(t){return $6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function d8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function f8(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e,r=`B`;for(let e of t){if(n<1024)break;n/=1024,r=e}return`${n.toFixed(1)} ${r}`}function ioe(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 aoe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function ooe(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 soe(e){let t=[`total: ${f8(e.bytes)}`],n=[...e.breakdown].filter(e=>e.bytes>0).sort((e,t)=>t.bytes-e.bytes);if(n.length>0){t.push(``,`BYTES TYPES ATTRIBUTION`);for(let e of n)t.push(`${f8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${ioe(e)}`)}return`${t.join(`
7095
+ `}async function toe(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,eoe(e)),t.scriptCatalog?.invalidateJsh()}async function noe(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function roe(e,t){let{removeAppSprinkles:n}=await import(`./apps-Dy99L1_j.js`);await n(e,t.fs)}async function u8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-Dy99L1_j.js`);return(await r(e,t,n.fs)).length}catch(t){return $6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function d8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function f8(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e,r=`B`;for(let e of t){if(n<1024)break;n/=1024,r=e}return`${n.toFixed(1)} ${r}`}function ioe(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 aoe(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function ooe(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 soe(e){let t=[`total: ${f8(e.bytes)}`],n=[...e.breakdown].filter(e=>e.bytes>0).sort((e,t)=>t.bytes-e.bytes);if(n.length>0){t.push(``,`BYTES TYPES ATTRIBUTION`);for(let e of n)t.push(`${f8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${ioe(e)}`)}return`${t.join(`
7096
7096
  `)}\n`}function coe(e={}){return H(`meminfo`,async t=>{let n=ooe(t);if(`error`in n)return d8(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
7097
7097
 
7098
7098
  Usage:
@@ -7118,7 +7118,7 @@ Options:
7118
7118
  -h, --help Show this help message
7119
7119
  `}function foe(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function h8(e){return`$${e.toFixed(2)}`}const poe=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function moe(e){let t=`${e.id} ${e.name??``}`;return!poe.test(t)}function hoe(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 goe(e){let t=new Map;for(let n of e){let e=hoe(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function _oe(e,t,n,r,i){let a=i?uoe(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 voe(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${h8(e.cost.input)} / ${h8(e.cost.output)}`,a=`${foe(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(`
7120
7120
  `)+`
7121
- `}function yoe(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-8bWQwrlg.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:doe(),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.
7121
+ `}function yoe(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-BWmqGvFK.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:doe(),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.
7122
7122
  `,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await loe(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(moe);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>_oe(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=goe(n)),w.push(...n),!l){let t=i(e);T.push(voe(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
7123
7123
  `,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
7124
7124
  `);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(`
@@ -7158,7 +7158,7 @@ Examples:
7158
7158
  oauth-domain add adobe '*.da.live'
7159
7159
  oauth-domain list adobe
7160
7160
  oauth-domain remove adobe admin.da.live
7161
- `}function koe(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-8bWQwrlg.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(`
7161
+ `}function koe(){return H(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-BWmqGvFK.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(`
7162
7162
  `)+`
7163
7163
  `,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)
7164
7164
  `,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
@@ -7230,7 +7230,7 @@ Examples:
7230
7230
  --authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
7231
7231
  --redirect-pattern 'http://127.0.0.1:56121/*'
7232
7232
  curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
7233
- `}function Ioe(){return H(`oauth-token`,Loe)}async function Loe(e,t){let n=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r),r=await import(`./providers-D2Pn4dpP.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Foe(),stderr:``,exitCode:0};if(e.includes(`--list`))return ese(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return qoe(e);if(e.includes(`--renew`))return Joe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return Yoe(e,t);let i=Roe(e);if(!i.ok)return i.result;let a=zoe(e),o=Boe(e,n,r);if(!o.ok)return o.result;let s=Voe(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await Hoe(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return Uoe(o.value,s.value,i.value,n.getOAuthAccountInfo)}function Roe(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:T8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function zoe(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function Boe(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:T8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(y8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>y8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:T8(`oauth-token: no OAuth providers configured`)}}function y8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function Voe(e,t){let n=t(e);return n?y8(n)?{ok:!0,value:n}:{ok:!1,result:T8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:T8(`oauth-token: unknown provider "${e}"`)}}async function Hoe(e,t,n,r){let i=n(e);return i&&!i.expired?b8(e,i,r):!i?.expired||!t.onSilentRenew||!await Koe(t.onSilentRenew)?null:b8(e,n(e),r)}function b8(e,t,n){return n&&!Poe(t?.scopes,n)?null:x8(e,t?.maskedValue)}function x8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:T8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function Uoe(e,t,n,r){try{let i=await Woe(e,t,n);return i.error?i.error:Goe(e,r,i.succeeded)}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof Error&&t.name===`OAuthLaunchError`?(console.error(`[oauth-token] Provider ${e}: login could not be shown:`,n),T8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),T8(`oauth-token: login failed: ${n}`))}}async function Woe(e,t,n){let r=n?{scopes:n}:void 0,i=!1,a=()=>{i=!0};if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-DNcIcWT8.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:T8(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`),succeeded:!1}}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-DNcIcWT8.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:T8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function Goe(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),T8(`oauth-token: interactive login was not completed (cancelled, timed out, or no one could approve it)`);let r=t(e);return r?.token&&!r.expired?x8(e,r.maskedValue):r?.token?T8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),T8(`oauth-token: login completed but no token was saved`))}async function Koe(e){try{return await e()!==null}catch{return!1}}function S8(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function qoe(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-D2Pn4dpP.js`).then(e=>e.r),o=S8(e,n,i,a);if(!o)return T8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return T8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return T8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return T8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return T8(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function Joe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-CCg1CJzw.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-D2Pn4dpP.js`).then(e=>e.r),a=S8(e,t,r,i);if(!a)return T8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return T8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return T8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${C8(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${C8(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
7233
+ `}function Ioe(){return H(`oauth-token`,Loe)}async function Loe(e,t){let n=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r),r=await import(`./providers-DH1Mhm__.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Foe(),stderr:``,exitCode:0};if(e.includes(`--list`))return ese(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return qoe(e);if(e.includes(`--renew`))return Joe(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return Yoe(e,t);let i=Roe(e);if(!i.ok)return i.result;let a=zoe(e),o=Boe(e,n,r);if(!o.ok)return o.result;let s=Voe(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await Hoe(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return Uoe(o.value,s.value,i.value,n.getOAuthAccountInfo)}function Roe(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:T8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function zoe(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function Boe(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:T8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(y8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>y8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:T8(`oauth-token: no OAuth providers configured`)}}function y8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function Voe(e,t){let n=t(e);return n?y8(n)?{ok:!0,value:n}:{ok:!1,result:T8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:T8(`oauth-token: unknown provider "${e}"`)}}async function Hoe(e,t,n,r){let i=n(e);return i&&!i.expired?b8(e,i,r):!i?.expired||!t.onSilentRenew||!await Koe(t.onSilentRenew)?null:b8(e,n(e),r)}function b8(e,t,n){return n&&!Poe(t?.scopes,n)?null:x8(e,t?.maskedValue)}function x8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:T8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function Uoe(e,t,n,r){try{let i=await Woe(e,t,n);return i.error?i.error:Goe(e,r,i.succeeded)}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof Error&&t.name===`OAuthLaunchError`?(console.error(`[oauth-token] Provider ${e}: login could not be shown:`,n),T8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),T8(`oauth-token: login failed: ${n}`))}}async function Woe(e,t,n){let r=n?{scopes:n}:void 0,i=!1,a=()=>{i=!0};if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-DNcIcWT8.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:T8(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`),succeeded:!1}}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-DNcIcWT8.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:T8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function Goe(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),T8(`oauth-token: interactive login was not completed (cancelled, timed out, or no one could approve it)`);let r=t(e);return r?.token&&!r.expired?x8(e,r.maskedValue):r?.token?T8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),T8(`oauth-token: login completed but no token was saved`))}async function Koe(e){try{return await e()!==null}catch{return!1}}function S8(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function qoe(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-DH1Mhm__.js`).then(e=>e.r),o=S8(e,n,i,a);if(!o)return T8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return T8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return T8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return T8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return T8(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function Joe(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-BOO_CzoH.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-DH1Mhm__.js`).then(e=>e.r),a=S8(e,t,r,i);if(!a)return T8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return T8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return T8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${C8(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${C8(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
7234
7234
  `)+`
7235
7235
  `,stderr:``,exitCode:+!u}}function C8(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function Yoe(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-BIKnTjZm.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-DNcIcWT8.js`),i=await Xoe(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return T8(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return T8(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let s=await o(a.config);return s?{stdout:`${s}\n`,stderr:``,exitCode:0}:T8(`oauth-token: intercept timed out or was cancelled`)}function Xoe(e,t){let n=e.indexOf(`--from-file`);return n>=0?Zoe(e[n+1],t):Qoe(e)}async function Zoe(e,t){if(!e)return{ok:!1,result:T8(`oauth-token: --from-file requires a path`)};try{let n=t.fs.resolvePath(t.cwd,e),r=await t.fs.readFile(n),i=typeof r==`string`?r:new TextDecoder().decode(r);return{ok:!0,value:JSON.parse(i)}}catch(t){return{ok:!1,result:T8(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function Qoe(e){let t=w8(e,`--authorize-url`),n=w8(e,`--redirect-pattern`);if(!t)return{ok:!1,result:T8(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:T8(`oauth-token: --redirect-pattern is required`)};let r=$oe(e);return r.ok?{ok:!0,value:{authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.value.length>0?{rewrite:r.value}:{}}}:r}function $oe(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]!==`--rewrite`)continue;let r=e[n+1];if(!r)return{ok:!1,result:T8(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:T8(`oauth-token: --rewrite "${r}" must be "<match>=<key>=<value>"`)};let[a,o,...s]=i;t.push({match:a,appendParams:{[o]:s.join(`=`)}})}return{ok:!0,value:t}}function w8(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function T8(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function ese(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
7236
7236
  `,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(`
@@ -7348,7 +7348,7 @@ Examples:
7348
7348
  plugin list
7349
7349
  plugin info my-plugin
7350
7350
  plugin remove my-plugin
7351
- `}function Mse(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(jse());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Pse(i,a,e);case`list`:case`ls`:return await Rse(i,e);case`info`:return await zse(i,e);case`validate`:return await Bse(i,a,e);case`remove`:case`rm`:case`delete`:return await Vse(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-BFiiSgrN.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return t.create({dbName:n})}async function W8(e,t,n){let r=Hse(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-jWWA5n2X.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 Nse(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function G8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${B8}/${t.map(Nse).join(`--`)}`}async function K8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-BZcI0-aZ.js`).then(e=>e.i),s=await i(e.owner,e.repo,r,e.branch);if(s.status===`error`)return`failed to download ${e.display}: ${s.message}`;let c=a(s.files),l=e.path?e.path.replace(/^\/|\/$/g,``)+`/`:``;if(!c[`${l}plugin.json`])return`no plugin.json found at ${e.display} — not an Agent Plugins package`;try{await n.rm(t,{recursive:!0})}catch{}return await n.mkdir(t,{recursive:!0}),(await o(c,l,t,n,!1)).length===0?`no files found at ${e.display}`:null}async function q8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Pse(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin install <path|repo>
7351
+ `}function Mse(e={}){return H(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(jse());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Pse(i,a,e);case`list`:case`ls`:return await Rse(i,e);case`info`:return await zse(i,e);case`validate`:return await Bse(i,a,e);case`remove`:case`rm`:case`delete`:return await Vse(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-Boij2gPF.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return t.create({dbName:n})}async function W8(e,t,n){let r=Hse(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-B8nRAI8z.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 Nse(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function G8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${B8}/${t.map(Nse).join(`--`)}`}async function K8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-7k6aGRi5.js`).then(e=>e.i),s=await i(e.owner,e.repo,r,e.branch);if(s.status===`error`)return`failed to download ${e.display}: ${s.message}`;let c=a(s.files),l=e.path?e.path.replace(/^\/|\/$/g,``)+`/`:``;if(!c[`${l}plugin.json`])return`no plugin.json found at ${e.display} — not an Agent Plugins package`;try{await n.rm(t,{recursive:!0})}catch{}return await n.mkdir(t,{recursive:!0}),(await o(c,l,t,n,!1)).length===0?`no files found at ${e.display}`:null}async function q8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Pse(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin install <path|repo>
7352
7352
 
7353
7353
  Loads the Agent Plugins package at <path>, or downloads it from a GitHub
7354
7354
  reference (owner/repo, owner/repo@branch, or
@@ -7359,19 +7359,19 @@ mcp.json. On success the plugin is recorded in
7359
7359
  /workspace/.plugins/plugins.json — its skills then surface through the
7360
7360
  standard skills discovery, and each supported streamable-http MCP server
7361
7361
  is registered in the MCP store as "<plugin>:<server>".
7362
- `);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-sgPDMLWT.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-DvmZZQcL.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await q8(i,o),H8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await Lse(u,n),g=await Ise(d,m?.mcpServerNames,h.registered,n);return await p(d,{root:o,version:u.manifest.version,description:u.manifest.description,installedAt:new Date().toISOString(),mcpServerNames:h.registered,...s?{source:s}:{}},n.fs),V8(Fse(u,h,g,s??o,l.diagnostics))}function Fse(e,t,n,r,i){let a=e.manifest.name,o=t.registered,s=e.mcp.servers.filter(e=>e.status!==`supported`),c=[`Installed agent plugin "${a}"${e.manifest.version?` v${e.manifest.version}`:``} from ${r}`,` skills: ${e.skills.length}${e.skills.length>0?` (${e.skills.map(e=>e.name).join(`, `)})`:``}`,` mcp: ${o.length} registered${o.length>0?` (${o.join(`, `)})`:``}${s.length>0?`, ${s.length} skipped`:``}${n>0?`, ${n} removed from previous install`:``}`];return t.conflicts.length>0&&c.push(` warning: not bridged — MCP server name(s) already in use and not owned by this plugin: ${t.conflicts.join(`, `)} (remove them with \`mcp remove\` first)`),i.length>0&&c.push(`Diagnostics:`,J8(i)),c.join(`
7362
+ `);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-sgPDMLWT.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-CgULlP3e.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await q8(i,o),H8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await Lse(u,n),g=await Ise(d,m?.mcpServerNames,h.registered,n);return await p(d,{root:o,version:u.manifest.version,description:u.manifest.description,installedAt:new Date().toISOString(),mcpServerNames:h.registered,...s?{source:s}:{}},n.fs),V8(Fse(u,h,g,s??o,l.diagnostics))}function Fse(e,t,n,r,i){let a=e.manifest.name,o=t.registered,s=e.mcp.servers.filter(e=>e.status!==`supported`),c=[`Installed agent plugin "${a}"${e.manifest.version?` v${e.manifest.version}`:``} from ${r}`,` skills: ${e.skills.length}${e.skills.length>0?` (${e.skills.map(e=>e.name).join(`, `)})`:``}`,` mcp: ${o.length} registered${o.length>0?` (${o.join(`, `)})`:``}${s.length>0?`, ${s.length} skipped`:``}${n>0?`, ${n} removed from previous install`:``}`];return t.conflicts.length>0&&c.push(` warning: not bridged — MCP server name(s) already in use and not owned by this plugin: ${t.conflicts.join(`, `)} (remove them with \`mcp remove\` first)`),i.length>0&&c.push(`Diagnostics:`,J8(i)),c.join(`
7363
7363
  `)+`
7364
- `}async function Ise(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-CG5kLFp1.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 Lse(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-CG5kLFp1.js`).then(e=>e.r),{McpClient:a}=await import(`./client-BGJKiXya.js`).then(e=>e.n),o=[],s=[];for(let c of n){let n=c.config,l=`${e.manifest.name}:${c.name}`,u=await r(l,t.fs);if(u&&u.pluginOrigin!==e.manifest.name){s.push(l);continue}let d=[];try{let e=new a({url:n.url,headers:n.headers});await e.initialize(),d=await e.toolsList()}catch{}await i(l,{url:n.url,...n.headers?{headers:n.headers}:{},tools:d,addedAt:new Date().toISOString(),pluginOrigin:e.manifest.name},t.fs),o.push(l)}return{registered:o,conflicts:s}}async function Rse(e,t){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin list
7365
- `);let{listInstalledPlugins:n}=await import(`./store-DvmZZQcL.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return V8("No agent plugins installed. Use `plugin install <path>`.\n");let a=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of i){let t=r[e];a.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let o=a[0].map((e,t)=>Math.max(...a.map(e=>e[t].length)));return V8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
7364
+ `}async function Ise(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-CEccVDd7.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 Lse(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-CEccVDd7.js`).then(e=>e.r),{McpClient:a}=await import(`./client-BGJKiXya.js`).then(e=>e.n),o=[],s=[];for(let c of n){let n=c.config,l=`${e.manifest.name}:${c.name}`,u=await r(l,t.fs);if(u&&u.pluginOrigin!==e.manifest.name){s.push(l);continue}let d=[];try{let e=new a({url:n.url,headers:n.headers});await e.initialize(),d=await e.toolsList()}catch{}await i(l,{url:n.url,...n.headers?{headers:n.headers}:{},tools:d,addedAt:new Date().toISOString(),pluginOrigin:e.manifest.name},t.fs),o.push(l)}return{registered:o,conflicts:s}}async function Rse(e,t){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin list
7365
+ `);let{listInstalledPlugins:n}=await import(`./store-CgULlP3e.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return V8("No agent plugins installed. Use `plugin install <path>`.\n");let a=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of i){let t=r[e];a.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let o=a[0].map((e,t)=>Math.max(...a.map(e=>e[t].length)));return V8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
7366
7366
  `)+`
7367
7367
  `)}async function zse(e,t){if(e.length===0||qX(e))return e.length===0?H8(`plugin info: expected <name>`):V8(`usage: plugin info <name>
7368
- `);let n=e[0],{getInstalledPlugin:r}=await import(`./store-DvmZZQcL.js`),i=await r(n,t.fs);if(!i)return H8(`plugin info: no installed plugin named "${n}"`);let a=await U8(t),{loadPluginFromDirectory:o}=await import(`./loader-sgPDMLWT.js`),s=await o(a,i.root);if(!s.ok)return H8(`plugin info: plugin at ${i.root} no longer loads:\n${J8(s.diagnostics)}`);let{plugin:c}=s,l=c.manifest,u=[`${l.name}${l.version?` v${l.version}`:``}`,...l.description?[` ${l.description}`]:[],` root: ${c.root}`,...l.license?[` license: ${l.license}`]:[],...l.homepage?[` home: ${l.homepage}`]:[],``,`Skills (${c.skills.length}):`,...c.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${c.mcp.servers.length}):`,...c.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return s.diagnostics.length>0&&u.push(``,`Diagnostics:`,J8(s.diagnostics)),V8(u.join(`
7368
+ `);let n=e[0],{getInstalledPlugin:r}=await import(`./store-CgULlP3e.js`),i=await r(n,t.fs);if(!i)return H8(`plugin info: no installed plugin named "${n}"`);let a=await U8(t),{loadPluginFromDirectory:o}=await import(`./loader-sgPDMLWT.js`),s=await o(a,i.root);if(!s.ok)return H8(`plugin info: plugin at ${i.root} no longer loads:\n${J8(s.diagnostics)}`);let{plugin:c}=s,l=c.manifest,u=[`${l.name}${l.version?` v${l.version}`:``}`,...l.description?[` ${l.description}`]:[],` root: ${c.root}`,...l.license?[` license: ${l.license}`]:[],...l.homepage?[` home: ${l.homepage}`]:[],``,`Skills (${c.skills.length}):`,...c.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${c.mcp.servers.length}):`,...c.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return s.diagnostics.length>0&&u.push(``,`Diagnostics:`,J8(s.diagnostics)),V8(u.join(`
7369
7369
  `)+`
7370
7370
  `)}async function Bse(e,t,n){if(e.length===0||qX(e))return e.length===0?H8(`plugin validate: expected <path|repo>`):V8(`usage: plugin validate <path|repo>
7371
7371
  `);let r=await U8(n),i=await W8(e[0],t,r);if(i.kind===`error`)return H8(`plugin validate: ${i.message}`);let a,o=null;if(i.kind===`github`){if(!n.fetch)return H8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);o=`/tmp/.plugin-validate/${G8(i.ref).split(`/`).pop()}`;let e=await K8(i.ref,o,r,n.fetch);if(e)return H8(`plugin validate: ${e}`);a=o}else a=i.root;let{loadPluginFromDirectory:s}=await import(`./loader-sgPDMLWT.js`),c;try{c=await s(r,a)}finally{o&&await q8(r,o)}if(!c.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${J8(c.diagnostics)}\n`,exitCode:1};let{plugin:l}=c,u=l.mcp.servers.filter(e=>e.status===`supported`).length,d=[`plugin validate: OK — "${l.manifest.name}"${l.manifest.version?` v${l.manifest.version}`:``}`,` skills: ${l.skills.length}`,` mcp servers: ${u} supported, ${l.mcp.servers.length-u} skipped (mcp.json ${l.mcp.status})`];return c.diagnostics.length>0&&d.push(`Diagnostics:`,J8(c.diagnostics)),V8(d.join(`
7372
7372
  `)+`
7373
7373
  `)}async function Vse(e,t){if(e.length===0||qX(e))return e.length===0?H8(`plugin remove: expected <name>`):V8(`usage: plugin remove <name>
7374
- `);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-DvmZZQcL.js`),a=await r(n,t.fs);if(!a)return H8(`plugin remove: no installed plugin named "${n}"`);let o=0;if(a.mcpServerNames&&a.mcpServerNames.length>0){let{deleteServer:e,getServer:r}=await import(`./store-CG5kLFp1.js`).then(e=>e.r);for(let i of a.mcpServerNames)(await r(i,t.fs))?.pluginOrigin===n&&await e(i,t.fs)&&(o+=1)}await i(n,t.fs);let s=a.root.startsWith(`${B8}/`);return s&&await q8(await U8(t),a.root),V8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
7374
+ `);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-CgULlP3e.js`),a=await r(n,t.fs);if(!a)return H8(`plugin remove: no installed plugin named "${n}"`);let o=0;if(a.mcpServerNames&&a.mcpServerNames.length>0){let{deleteServer:e,getServer:r}=await import(`./store-CEccVDd7.js`).then(e=>e.r);for(let i of a.mcpServerNames)(await r(i,t.fs))?.pluginOrigin===n&&await e(i,t.fs)&&(o+=1)}await i(n,t.fs);let s=a.root.startsWith(`${B8}/`);return s&&await q8(await U8(t),a.root),V8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
7375
7375
  `)+`
7376
7376
  `)}function Hse(e,t){let n=t.startsWith(`/`)?t:`${e.replace(/\/$/,``)}/${t}`,r=[];for(let e of n.split(`/`))e!==``&&e!==`.`&&(e===`..`?r.pop():r.push(e));return`/${r.join(`/`)}`}function J8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
7377
7377
  `)}const Y8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],Use=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],Wse={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function Gse(e={}){return H(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return rce();let n=e.processManager??Kse();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
@@ -9067,7 +9067,7 @@ ${e}
9067
9067
  ${i?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
9068
9068
  ${t}
9069
9069
  ---`);let c=wx(n);return c&&(s+=c),s}};const P9=r(`scoop-lifecycle-manager`);var ehe=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 aS(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))??Ah(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??Ah(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 cr))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=Wg(t).policy.filesystem,o=a.kind===`full-workspace`?r:new cr(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 $me(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();Jg(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&&Or(`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&&Ah(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}=Wg(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}),Or(`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)},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}),Or(`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`),Wg(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 the=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}`);Or(`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=En(zn(An(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}: ${yh(e.content,e.attachments)}`).join(`
9070
- `),l=s.flatMap(e=>bh(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=En(zn(An(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 nhe=class{scoops=new Map;workUnits=new qg(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new kx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new nS({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 eS({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Jx({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 Bx({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=>Pn(e),saveMessage:e=>Dn(e)});lickRegistry=new Mx({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 the({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=>Dn(e),deleteMessage:e=>kn(e),clearMessagesForScoop:e=>Ln(e),clearAllMessages:()=>Fn(),getMessagesSince:(e,t,n)=>Nn(e,t,n),setState:(e,t)=>Tn(e,t)},isExternalLickChannel:vg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new ehe({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=>wn(e),deleteScoop:e=>In(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>ir(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 Hn(),this.sharedFs=await Ix(()=>sr.create({dbName:`slicc-fs`}),e),this.sessionStore=new Ch,this.fsWatcher=new or,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new jv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new W_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new Fx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Bn(),n=Object.values(t).find(e=>e.isCone)?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Jg(e),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await Mn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Rx({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}`)}dr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=Nv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=e.isCone?null:t??null;try{await wn(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=>tr(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 Ah(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 sr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Tx(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 jv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new W_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Fx(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 Pn(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(mr)]}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 mg,t=this.sharedFs;return new nb({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:bb(),snapshotStore:{read:e=>pb(t,e),write:(e,n)=>fb(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.75.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function rhe(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)=>che(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),ohe(t,n);let f=a(o.ctx,l),p=she(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`?ahe(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 ihe(e){let t=rhe(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function ahe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function ohe(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 she(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 che(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?lhe(n,t,a?.args??[],r):e===`agent`?uhe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function lhe(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 uhe(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 dhe=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 _he(t);let n=this.pm.get(e);switch(t){case`status`:return fhe(n);case`cmdline`:return phe(n);case`cwd`:return mhe(n);case`stat`:return hhe(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 fhe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${ghe(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(`
9070
+ `),l=s.flatMap(e=>bh(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=En(zn(An(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 nhe=class{scoops=new Map;workUnits=new qg(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new kx({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new nS({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 eS({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Jx({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 Bx({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=>Pn(e),saveMessage:e=>Dn(e)});lickRegistry=new Mx({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 the({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=>Dn(e),deleteMessage:e=>kn(e),clearMessagesForScoop:e=>Ln(e),clearAllMessages:()=>Fn(),getMessagesSince:(e,t,n)=>Nn(e,t,n),setState:(e,t)=>Tn(e,t)},isExternalLickChannel:vg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new ehe({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=>wn(e),deleteScoop:e=>In(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>ir(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 Hn(),this.sharedFs=await Ix(()=>sr.create({dbName:`slicc-fs`}),e),this.sessionStore=new Ch,this.fsWatcher=new or,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new jv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new W_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new Fx(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await Bn(),n=Object.values(t).find(e=>e.isCone)?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),Jg(e),this.migrateScoopConfig(e),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let t=await Mn(`lastAgentTs_${e.jid}`);t&&this.messageRouter.setLastAgentTimestamp(e.jid,t)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Rx({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}`)}dr(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=Nv(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=e.isCone?null:t??null;try{await wn(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=>tr(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 Ah(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 sr.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Tx(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 jv({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new W_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new Fx(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 Pn(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(mr)]}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 mg,t=this.sharedFs;return new nb({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:bb(),snapshotStore:{read:e=>pb(t,e),write:(e,n)=>fb(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.76.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function rhe(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)=>che(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),ohe(t,n);let f=a(o.ctx,l),p=she(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`?ahe(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 ihe(e){let t=rhe(e);return globalThis[X7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function ahe(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function ohe(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 she(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 che(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?lhe(n,t,a?.args??[],r):e===`agent`?uhe(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function lhe(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 uhe(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 dhe=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 _he(t);let n=this.pm.get(e);switch(t){case`status`:return fhe(n);case`cmdline`:return phe(n);case`cwd`:return mhe(n);case`stat`:return hhe(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 fhe(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${ghe(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(`
9071
9071
  `)+`
9072
9072
  `}function phe(e){return e.argv.join(`\0`)+`\0`}function mhe(e){return e.cwd+`
9073
9073
  `}function hhe(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
@@ -9076,4 +9076,4 @@ ${t}
9076
9076
  `;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
9077
9077
  `;case`stat`:return`1 (kernel-host) R 0 - 0 -
9078
9078
  `}}function vhe(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(qB(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(!HB(n.token))return;let a=i.get(n.id);if(a){r({type:JB,id:n.id}),a.result&&r({type:YB,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:JB,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:YB,id:n.id,...e})};($B(n)?nV(n):KB(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 yhe(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 bhe(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 xhe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}She(e,t)}function She(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`):Ah(r)[0],!i){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!V_(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=Mg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=yhe(e),s=bhe(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 Che(e,t,n,r,i){let a=new Ur,o=new nhe(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,W9().__slicc_browser=t,await n.bind(o,t);let s=xn(()=>n.emitTrayRuntimeStatus()),c=u_(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function whe(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-AOg9dLn6.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-BJhAu_iX.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??xhe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function The(e){Ah(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 Ehe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;ihe({sharedFs:i,getConeJid:()=>t.getWorkUnits().resolveDefaultRoot()?.descriptor.id,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>dG(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>Z7().slice(10,22),splitResult:(e,t)=>Q7(e,t)})}async function Dhe(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))+`
9079
- `,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 Ohe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C5jpbwXT.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function khe(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 M_(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})},Ahe(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Ahe(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:()=>N_()}}function jhe(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-DkiFv5PY.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 Mhe(){Jn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-L9WqdkJi.js`);return e()})}function Nhe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-L9WqdkJi.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 Phe(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 Fhe(){return vt()}async function Ihe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Mhe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Che(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?$h(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new dhe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await whe(l,e,o);s(`lick-manager-ready`),f&&Ehe({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Dhe({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;Fhe()&&(g=await Ohe(p,o,e.localLickWsUrl??null));let _=khe(n,p,o);f&&jhe(f,p,o),a||await The(l),s(`cone-bootstrapped`),f&&Nhe(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Phe(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=vhe({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 Lhe({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 Lhe(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)}Rhe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Rhe(e){let t=W9();t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[X7]}const G9=`x-bypass-llm-proxy`;function zhe(e,t,n){return t?(r,i)=>{if(!Bhe(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 Bhe(e,t,n){if(Hhe(e,t))return!0;let r=n?.()??null;return r?Vhe(e,r,t):!1}function Vhe(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 Hhe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Uhe(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var Whe=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(!Ghe(e)||e.source!==`panel`)return;let t=e.payload;Khe(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 Ghe(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 Khe(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 qhe=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 Jhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Whe({transport:t,processManager:i,createShell:(a,o)=>new qhe(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 Yhe(e){let t=new Xhe(e);return t.start(),{stop:()=>t.dispose()}}var Xhe=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(!Zhe(e)||e.source!==`panel`)return;let t=e.payload;if(Qhe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if($he(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new 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(ege(e.type),e.requestId,new un(`EACCES`,`vfs-rpc-host has no writable backend wired`),tge(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 Zhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qhe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function $he(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function ege(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 tge(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 nge(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=zhe(e.bind(globalThis),t,rge)}function rge(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function ige(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 age=Uhe(e=>cge(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&age.handle(e.data)});function oge(e){let t=Aee(e.pageBuildId,`6.75.0-mt301qkw`);return()=>{t&&xee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.75.0-mt301qkw`)}}function sge(e){nge(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),aG(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),ige(e.localStorageSeed??{}),e.flagFloat&&Va(e.flagFloat)}async function cge(e){Oee(e.instanceId);let t=oge(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{sge(e),Cee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Mee(e.kernelPort),a=new C_(r),o=C_.createCallbacks(a),c=new Nee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new va(c);Y9=await Ihe({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(wa(i));let m=await uge({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){lge(e.kernelPort,t)}}function lge(e,t){kee(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 uge(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=Jhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Yhe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await dge(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function dge(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-tfN1ILpq.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
9079
+ `,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 Ohe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C5jpbwXT.js`);return t(e,{locationHref:self.location.href,lickWsUrl:n??null}).stop}catch(e){return(t.error?.bind(t)??t.warn.bind(t)??((e,t)=>console.error(`[lick-ws-bridge]`,e,t)))(`Failed to start lick-ws bridge — webhook / crontask / handoff lick delivery is non-functional in this session`,{error:e instanceof Error?e.message:String(e)}),null}}function khe(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 M_(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})},Ahe(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function Ahe(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:()=>N_()}}function jhe(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-B1Eib3Wt.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 Mhe(){Jn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-Di65pY4y.js`);return e()})}function Nhe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Di65pY4y.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 Phe(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 Fhe(){return vt()}async function Ihe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);Mhe();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Che(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?$h(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new dhe(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await whe(l,e,o);s(`lick-manager-ready`),f&&Ehe({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await Dhe({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;Fhe()&&(g=await Ohe(p,o,e.localLickWsUrl??null));let _=khe(n,p,o);f&&jhe(f,p,o),a||await The(l),s(`cone-bootstrapped`),f&&Nhe(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await Phe(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=vhe({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 Lhe({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 Lhe(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)}Rhe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function Rhe(e){let t=W9();t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[X7]}const G9=`x-bypass-llm-proxy`;function zhe(e,t,n){return t?(r,i)=>{if(!Bhe(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 Bhe(e,t,n){if(Hhe(e,t))return!0;let r=n?.()??null;return r?Vhe(e,r,t):!1}function Vhe(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 Hhe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Uhe(e,t={}){let n=t.onError??(e=>console.error(`[kernel-worker] boot failed`,e)),r=t.onDuplicate??(()=>console.warn(`[kernel-worker] received duplicate kernel-worker-init; ignoring`)),i=!1;return{handle(t){if(i){r();return}i=!0,e(t).catch(e=>{i=!1,n(e)})},isInitialized(){return i}}}var Whe=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(!Ghe(e)||e.source!==`panel`)return;let t=e.payload;Khe(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 Ghe(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 Khe(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 qhe=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 Jhe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new Whe({transport:t,processManager:i,createShell:(a,o)=>new qhe(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 Yhe(e){let t=new Xhe(e);return t.start(),{stop:()=>t.dispose()}}var Xhe=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(!Zhe(e)||e.source!==`panel`)return;let t=e.payload;if(Qhe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if($he(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new 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(ege(e.type),e.requestId,new un(`EACCES`,`vfs-rpc-host has no writable backend wired`),tge(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 Zhe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qhe(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-read-dir`||t===`vfs-read-file`||t===`vfs-stat`}function $he(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`vfs-write-file`||t===`vfs-mkdir`||t===`vfs-rm`||t===`vfs-flush`||t===`vfs-list-mount-points`}function ege(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 tge(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 nge(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=zhe(e.bind(globalThis),t,rge)}function rge(){let e=l();if(!e)return null;try{return new URL(e).origin}catch{return null}}function ige(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 age=Uhe(e=>cge(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&age.handle(e.data)});function oge(e){let t=Aee(e.pageBuildId,`6.76.0-mt39fh80`);return()=>{t&&xee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.76.0-mt39fh80`)}}function sge(e){nge(),m(e.localApiBaseUrl??null),v(e.bridgeToken??null),aG(e.syncFsBridgeEnabled??!1),u(e.extensionDelegateId??null),ige(e.localStorageSeed??{}),e.flagFloat&&Va(e.flagFloat)}async function cge(e){Oee(e.instanceId);let t=oge(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{sge(e),Cee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=Mee(e.kernelPort),a=new C_(r),o=C_.createCallbacks(a),c=new Nee(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new va(c);Y9=await Ihe({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(wa(i));let m=await uge({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){lge(e.kernelPort,t)}}function lge(e,t){kee(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 uge(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=Jhe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Yhe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await dge(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function dge(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-tfN1ILpq.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CWqWgyRG.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});