sliccy 5.67.2 → 5.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/assets/__vite-browser-external-CtuZSfo7.js +1 -0
- package/dist/ui/assets/{account-store-CovklOkk.js → account-store-CoA-EjrR.js} +1 -1
- package/dist/ui/assets/{account-store-BIF64n8-.js → account-store-Cw-Kdlic.js} +2 -2
- package/dist/ui/assets/{adobe-17vWB0a6.js → adobe-B4gTTma2.js} +1 -1
- package/dist/ui/assets/{adobe-TXieKYY5.js → adobe-CqST5E4B.js} +1 -1
- package/dist/ui/assets/{apps-BIcLdFeM.js → apps-BtS9MYxU.js} +1 -1
- package/dist/ui/assets/{azure-openai-C1W6dEpq.js → azure-openai-CKRM23oV.js} +1 -1
- package/dist/ui/assets/{azure-openai-DWOa9B_t.js → azure-openai-CcIDDU6v.js} +1 -1
- package/dist/ui/assets/bedrock-camp-D_7EbOFH.js +1 -0
- package/dist/ui/assets/{bedrock-camp-BuUxtnu3.js → bedrock-camp-PMQ4Iu6f.js} +1 -1
- package/dist/ui/assets/{cerebras-CztfMhyd.js → cerebras-Cjamhn6S.js} +1 -1
- package/dist/ui/assets/{cerebras-QbxVz39_.js → cerebras-DsAtsb2V.js} +1 -1
- package/dist/ui/assets/compat-Spvv5tCW.js +2 -0
- package/dist/ui/assets/{composer-speech-CWgEvzia.js → composer-speech-BSy_wbJC.js} +1 -1
- package/dist/ui/assets/{connect-surface-CHYTf_sk.js → connect-surface-C6I8TboO.js} +1 -1
- package/dist/ui/assets/{context-compaction-2cZIhnSb.js → context-compaction-CW5AQ9bv.js} +1 -1
- package/dist/ui/assets/{dip-CxC1oNbs.js → dip-D3QakWLH.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-Wr0NmhbD.js → ensure-speech-assets-8cWrra0n.js} +1 -1
- package/dist/ui/assets/{fs-DXkVA9oH.js → fs-Bmq507Od.js} +1 -1
- package/dist/ui/assets/{fs-CanwjxXu.js → fs-WTyVMSI7.js} +2 -2
- package/dist/ui/assets/{github-BuNlwy6Z.js → github-B6i7fX-k.js} +1 -1
- package/dist/ui/assets/{github-Dr94t9Ca.js → github-D7xWsi2X.js} +2 -2
- package/dist/ui/assets/{github-copilot-WImjMwBU.js → github-copilot-Bo5sSGEf.js} +1 -1
- package/dist/ui/assets/{github-copilot-DRg525a9.js → github-copilot-DgH4lVlG.js} +1 -1
- package/dist/ui/assets/{hear-C1RTIY9q.js → hear-B5lURJtR.js} +1 -1
- package/dist/ui/assets/{hear-BxiGt0Ct.js → hear-DI5vlKdf.js} +1 -1
- package/dist/ui/assets/{installer-FOVSBgCf.js → installer-kDSMsl2T.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-DFnuhv4z.js → js-realm-worker-d_SDr24a.js} +7 -7
- package/dist/ui/assets/{kernel-worker-0dC64i4h.js → kernel-worker-DNk5pbO8.js} +405 -405
- package/dist/ui/assets/{kokoro-engine-8rE8HqhM.js → kokoro-engine-DX7VicqD.js} +1 -1
- package/dist/ui/assets/{legacy-api-aliases-CaOObRpi.js → legacy-api-aliases-CRTuRAqQ.js} +1 -1
- package/dist/ui/assets/{legacy-api-aliases-CI-iGRFs.js → legacy-api-aliases-CdGTJw-r.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-CZk5y_uS.js → lick-ws-bridge-BVIYLuDJ.js} +1 -1
- package/dist/ui/assets/{local-llm-CvlXyUsR.js → local-llm-4lJSiK5z.js} +1 -1
- package/dist/ui/assets/{local-llm-Dz9k2lTQ.js → local-llm-BHmd5Fd7.js} +1 -1
- package/dist/ui/assets/{magick-wasm-BiCoSTdr.js → magick-wasm-Daq1kpb4.js} +1 -1
- package/dist/ui/assets/{main-Nb-8QjGQ.js → main-CrR9ucLa.js} +3 -3
- package/dist/ui/assets/{mount-DvJJTEk6.js → mount-Bt1UFWjP.js} +2 -2
- package/dist/ui/assets/{mount-ClX16Vqy.js → mount-Cvxu87k0.js} +1 -1
- package/dist/ui/assets/{mount-recovery-_mFoJDg1.js → mount-recovery-2ElXrqlr.js} +1 -1
- package/dist/ui/assets/new-session-CiuddhGl.js +2 -0
- package/dist/ui/assets/oauth-bootstrap-BKh-w2bl.js +2 -0
- package/dist/ui/assets/{openai-codex-Dmvgi9kk.js → openai-codex-BTjoLqTw.js} +1 -1
- package/dist/ui/assets/{openai-codex-qgJYbHcs.js → openai-codex-ChonaqJh.js} +1 -1
- package/dist/ui/assets/openrouter-BG0ZjAOt.js +1 -0
- package/dist/ui/assets/openrouter-DuD25f7F.js +1 -0
- package/dist/ui/assets/openrouter-models-B8MWxzTa.js +1 -0
- package/dist/ui/assets/openrouter-models-DM9v24kQ.js +1 -0
- package/dist/ui/assets/openrouter-oauth-CK60lvKj.js +1 -0
- package/dist/ui/assets/openrouter-oauth-COmvA0Z1.js +1 -0
- package/dist/ui/assets/openrouter.models-Bi9GV7Zn.js +1 -0
- package/dist/ui/assets/openrouter.models-D41M1z_D.js +1 -0
- package/dist/ui/assets/{page-follower-tray-BblmGsa_.js → page-follower-tray-9fFxBm3_.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-L5pGVFBu.js → panel-rpc-handlers-CFg5NA3F.js} +2 -2
- package/dist/ui/assets/{provider-m1X4CbVe.js → provider-4BBnXotd.js} +2 -2
- package/dist/ui/assets/{provider-DAA4g3_k.js → provider-DXnAAcyy.js} +1 -1
- package/dist/ui/assets/{provider-settings-Cuugd-fj.js → provider-settings-Bv01tMmE.js} +1 -1
- package/dist/ui/assets/{provider-settings-Cf7eXAWa.js → provider-settings-DsZhN2JS.js} +1 -1
- package/dist/ui/assets/{provider-store-access-CgDL1cUd.js → provider-store-access-JTv_TUOb.js} +2 -2
- package/dist/ui/assets/provider-store-access-saWse80P.js +1 -0
- package/dist/ui/assets/providers-BoV1YFxZ.js +1 -0
- package/dist/ui/assets/providers-u1yhVbk3.js +2 -0
- package/dist/ui/assets/py-realm-worker-C9yzXwPb.js +244 -0
- package/dist/ui/assets/{pyodide-BahZNzwn.js → pyodide-B9hoVXZ4.js} +2 -2
- package/dist/ui/assets/{quick-llm-CmF1euCZ.js → quick-llm-CXqHh13i.js} +1 -1
- package/dist/ui/assets/{session-freezer-CvrIXOah.js → session-freezer-Dd9Vda0R.js} +3 -3
- package/dist/ui/assets/setup-sudo-CDu03XrJ.js +2 -0
- package/dist/ui/assets/shared-BYVJAPbn.js +1 -0
- package/dist/ui/assets/shared-pjIf7b3g.js +4 -0
- package/dist/ui/assets/{skills-3PZmUeNA.js → skills-CW8kM1BJ.js} +1 -1
- package/dist/ui/assets/{speak-BeDix5EH.js → speak-B4wyr-p6.js} +1 -1
- package/dist/ui/assets/{speak-CkvZB0fq.js → speak-aEIq7SEP.js} +1 -1
- package/dist/ui/assets/{sprinkle-bridge-YYPWJ55I.js → sprinkle-bridge-DziYRsuS.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-CK0eo6zp.js → sprinkle-manager-354rS3Fe.js} +1 -1
- package/dist/ui/assets/{store-DdPbOMzR.js → store-J9T9BcgY.js} +1 -1
- package/dist/ui/assets/{sudo--Rx9zaD2.js → sudo-DzRD7NyW.js} +1 -1
- package/dist/ui/assets/{transformers-env-C77NUYNM.js → transformers-env-CeJN6XlP.js} +1 -1
- package/dist/ui/assets/{transformers-env-RUMoBRzi.js → transformers-env-DZtq7i0I.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-Dy4tXX0j.js → upgrade-detection-BIhXOe-Q.js} +1 -1
- package/dist/ui/assets/{voice-reply-RJ5RbAjY.js → voice-reply-6cMxpz9H.js} +1 -1
- package/dist/ui/assets/{wc-extension-RKYMPCAR.js → wc-extension-DrjbYKDl.js} +2 -2
- package/dist/ui/assets/wc-follower-Ss6qgVMU.js +17 -0
- package/dist/ui/assets/{wc-live-huAxuC_m.js → wc-live-DALR9RxO.js} +3 -3
- package/dist/ui/assets/wc-nav-rD7F67u7.js +2 -0
- package/dist/ui/assets/{wc-onboarding-sj3cY89G.js → wc-onboarding-D3EwB9c1.js} +2 -2
- package/dist/ui/assets/wc-placeholder-BEIr39eF.js +4 -0
- package/dist/ui/assets/{wc-settings-BmoBEcXH.js → wc-settings-CZc7gWTY.js} +2 -2
- package/dist/ui/assets/{wc-shell-BpzhLQbu.js → wc-shell-BgYP6QNP.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-COGCgdJj.js → wc-sprinkles-DtnXjTrx.js} +2 -2
- package/dist/ui/assets/wc-tray-DDa-t_xi.js +2 -0
- package/dist/ui/assets/{whisper-engine-6Ks_tvV1.js → whisper-engine-G1YfvaDM.js} +1 -1
- package/dist/ui/assets/{whisper-session-36PZh-9m.js → whisper-session-Ds5v74N9.js} +2 -2
- package/dist/ui/assets/{xai-grok-B5OVP1_6.js → xai-grok-Co4pMrel.js} +1 -1
- package/dist/ui/assets/{xai-grok-D7tkzbHx.js → xai-grok-HbxyqvtP.js} +1 -1
- package/dist/ui/index.html +9 -8
- package/dist/ui/packages/webapp/index.html +9 -8
- package/package.json +1 -1
- package/dist/ui/assets/__vite-browser-external-DZX1xHt-.js +0 -1
- package/dist/ui/assets/bedrock-camp-Dn7pj03H.js +0 -1
- package/dist/ui/assets/compat-D-WVLG85.js +0 -2
- package/dist/ui/assets/new-session-D0IePVky.js +0 -2
- package/dist/ui/assets/oauth-bootstrap-zfn3CvH_.js +0 -2
- package/dist/ui/assets/provider-store-access-D9WNmF0Z.js +0 -1
- package/dist/ui/assets/providers-BuWMF3xT.js +0 -2
- package/dist/ui/assets/providers-Lwh3Mkv2.js +0 -1
- package/dist/ui/assets/py-realm-worker-VuYxvTG9.js +0 -244
- package/dist/ui/assets/setup-sudo-C9KnyJVv.js +0 -2
- package/dist/ui/assets/shared-Bs3KpKjW.js +0 -4
- package/dist/ui/assets/shared-CR9p6ivA.js +0 -1
- package/dist/ui/assets/wc-follower-Bmun4Cco.js +0 -17
- package/dist/ui/assets/wc-nav-C6eP4gqM.js +0 -2
- package/dist/ui/assets/wc-placeholder-CfRJDlgb.js +0 -4
- package/dist/ui/assets/wc-tray-Cx2T5bzX.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s}from"./providers-
|
|
1
|
+
import{i as e,n as t,t as n}from"./rolldown-runtime-aKtaBQYM.js";import{t as r}from"./logger-LESFN7Hj.js";import{n as i,r as a,t as o}from"./panel-rpc-CjFVE0nK.js";import{a as s}from"./providers-BoV1YFxZ.js";import{a as c,c as l,d as u,f as d,h as f,i as p,l as m,m as h,n as g,p as _,r as v,s as y,t as b,u as x}from"./proxied-fetch-ldIfAeIb.js";import{r as S,t as C}from"./src-Dk1QVJRd.js";import{D as w,E as T,F as E,I as D,L as O,M as k,N as ee,P as te,T as A,_ as ne,h as re,i as ie,j as ae,o as oe,v as se}from"./account-store-Cw-Kdlic.js";import{t as ce}from"./runtime-env-byAg9ij-.js";import{n as le,r as ue,t as de}from"./fetch-body-DDu_AU5I.js";import{a as j,i as M,n as fe,r as pe}from"./transcript-limits-D0M7bLr9.js";import{n as me,o as he,s as ge}from"./tool-ui-t6ocn6AG.js";import{a as _e,i as ve,n as ye,o as N,r as be,t as xe}from"./backend-local-D4WZgy4J.js";import{t as P}from"./types-idfTVsM8.js";import{n as F,t as Se}from"./mime-types-D7IV6i7k.js";import{a as I,i as Ce,n as L,r as R}from"./mount-Cvxu87k0.js";import{o as we}from"./mount-table-store-CTrzlrNn.js";import{t as Te}from"./remote-cache-D59F5FOx.js";import{r as Ee,t as De}from"./mount-recovery-2ElXrqlr.js";import{S as z,a as Oe,b as ke,g as Ae,h as je,i as Me,l as Ne,m as Pe,n as Fe,o as Ie,p as Le,t as Re,u as ze,v as Be,w as Ve,x as He}from"./db-DjAqlQ2I.js";import{a as Ue,i as We,n as Ge,r as Ke}from"./tray-runtime-config-DEUlxEec.js";import{a as qe,i as Je,n as Ye,o as Xe,r as Ze}from"./runtime-mode-CEuVQ26O.js";import{a as Qe,c as $e,d as et,i as tt,l as nt,n as rt,o as it,s as at,t as ot,u as st}from"./lick-manager-Ct3WOtut.js";import{i as ct,n as lt,t as ut}from"./path-utils-DU6QhF_k.js";import{u as dt}from"./transform-messages-Bp94o3FD.js";import{l as ft,m as pt}from"./bedrock-camp-D_7EbOFH.js";import{t as mt}from"./__vite-browser-external-SwrSgYTf.js";import{a as ht,n as gt,r as _t}from"./fs-Bmq507Od.js";import{a as vt,c as yt,i as B,n as bt,o as xt,r as St,s as Ct}from"./cost-command-Cpg2Em0Q.js";import{a as wt,c as Tt,d as Et,f as Dt,i as Ot,l as kt,m as At,n as jt,o as Mt,p as Nt,r as Pt,s as Ft,u as It}from"./skills-CW8kM1BJ.js";import{n as Lt,t as Rt}from"./llm-session-id-ZObKEXzb.js";import{a as zt,c as Bt,d as Vt,f as Ht,i as Ut,l as Wt,n as Gt,o as Kt,r as qt,s as Jt,t as Yt,u as Xt}from"./installer-kDSMsl2T.js";import{n as Zt,t as Qt}from"./safe-buffer-C0pSmFaz.js";import{t as $t}from"./global-db-DvmmimLY.js";import{a as en,i as tn,r as nn,t as rn}from"./git-config-Lj0BT7Oc.js";import{t as an}from"./process-manager-B5dz0PkO.js";import{C as on,O as sn,S as cn,_ as ln,a as un,b as dn,c as fn,d as pn,f as mn,g as hn,h as gn,i as _n,k as vn,l as yn,m as bn,n as xn,o as Sn,p as Cn,r as wn,s as Tn,t as En,u as Dn,v as On,x as kn,y as An}from"./shared-pjIf7b3g.js";import{i as jn,r as Mn,t as Nn}from"./magick-wasm-Daq1kpb4.js";import{a as Pn,i as Fn,r as In,t as Ln}from"./script-catalog-BYXhqRAc.js";import{t as Rn}from"./local-llm-4lJSiK5z.js";import{t as zn}from"./client-BliYDaDA.js";const Bn=r(`cdp`);var Vn=class{ws=null;nextId=1;_superseded=!1;pending=new Map;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,Bn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Bn.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(),Bn.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};return t&&(a.params=t),n&&(a.sessionId=n),Bn.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}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 new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Bn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Bn.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Bn.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,Bn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Bn.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`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Hn=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -4854,13 +4854,13 @@ except BaseException:
|
|
|
4854
4854
|
`)?t:`${t}\n`);return}try{e.writeStdout(`${JSON.stringify(t,null,2)}\n`)}catch{e.writeStdout(`${String(t)}\n`)}},warn(n,i){let a=typeof i==`object`&&i&&`prefix`in i?i.prefix:void 0;e.writeStderr(r(a,t(n)))},help(t){throw e.writeStdout(t.endsWith(`
|
|
4855
4855
|
`)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const pW={reset:`\x1B[0m`,green:`\x1B[32m`,red:`\x1B[31m`,yellow:`\x1B[33m`,gray:`\x1B[90m`,bold:`\x1B[1m`,cyan:`\x1B[36m`,dim:`\x1B[2m`};function mW(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${pW.reset}`:String(n);return{enabled:t,green:n(pW.green),red:n(pW.red),yellow:n(pW.yellow),gray:n(pW.gray),bold:n(pW.bold),cyan:n(pW.cyan),dim:n(pW.dim)}}const hW={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function gW(e){if(typeof e==`number`&&Number.isFinite(e))return Math.trunc(e);if(typeof e!=`string`)throw TypeError(`time.parseDuration: spec must be string or number`);let t=e.trim(),n=/^([0-9]+(?:\.[0-9]+)?)\s*(ms|s|m|h|d|w|M|y)?$/.exec(t);if(!n)throw RangeError(`time.parseDuration: unrecognized spec "${e}"`);let r=Number(n[1]),i=n[2]??`ms`;return Math.trunc(r*hW[i])}function _W(e){return e<10?`0${e}`:String(e)}const vW={parseDuration:gW,ago(e,t=new Date){return new Date(t.getTime()-gW(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-gW(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+gW(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-gW(e));return`${n.getFullYear()}/${_W(n.getMonth()+1)}/${_W(n.getDate())}`}},yW=/\u001b\[[0-9;]*m/g;function bW(e){return e.replace(yW,``)}function xW(e){return bW(e).length}function SW(e,t){let n=String(e??``);return t<=0?``:xW(n)<=t?n:t<=1?n.slice(0,t):`${bW(n).slice(0,t-1)}…`}function CW(e,t){let n=String(e??``),r=xW(n);return r===t?n:r>t?SW(n,t):n+` `.repeat(t-r)}function wW(e,t){if(!e.length)return``;let n=Math.max(...e.map(e=>e.length)),r=[];for(let i=0;i<n;i++)if(t&&t[i]!==void 0)r[i]=t[i];else{let t=0;for(let n of e){let e=i<n.length?String(n[i]??``):``;t=Math.max(t,xW(e))}r[i]=t}return e.map(e=>r.map((t,n)=>CW(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
|
|
4856
4856
|
`)}function TW(e){return e instanceof Date?e:new Date(e)}function EW(e,t=`short`){let n=TW(e);if(Number.isNaN(n.getTime()))return String(e);if(t===`iso`)return n.toISOString();if(t===`locale`)return new Intl.DateTimeFormat(void 0,{dateStyle:`medium`}).format(n);if(t===`human`){let e=Date.now()-n.getTime(),t=Math.abs(e);if(t<6e4)return e>=0?`just now`:`in a moment`;let r=(t,n)=>e>=0?`${t} ${n}${t===1?``:`s`} ago`:`in ${t} ${n}${t===1?``:`s`}`;return t<36e5?r(Math.round(t/6e4),`minute`):t<864e5?r(Math.round(t/36e5),`hour`):t<26298e5?r(Math.round(t/864e5),`day`):t<315576e5?r(Math.round(t/26298e5),`month`):r(Math.round(t/315576e5),`year`)}return`${n.getFullYear()}-${_W(n.getMonth()+1)}-${_W(n.getDate())}`}const DW={trunc:SW,col:CW,table:wW,date:EW},OW=async(e,t,n)=>{let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=[],s=async()=>{for(;;){let e=a++;if(e>=t.length)return;i[e]=await n(t[e],e)}};for(let e=0;e<Math.min(r,t.length);e++)o.push(s());return await Promise.all(o),i};function kW(e,t){let n=[];for(let r of e)r===``||r===`.`||(r===`..`?n.length>0&&n[n.length-1]!==`..`?n.pop():t&&n.push(`..`):n.push(r));return n}function AW(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=kW(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function jW(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:AW(t)}function MW(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=-1,r=!0;for(let t=e.length-1;t>=1;t--)if(e.charCodeAt(t)===47){if(!r){n=t;break}}else r=!1;return n===-1?t?`/`:`.`:t&&n===1?`//`:e.slice(0,n)}function NW(e,t){let n=0,r=-1,i=!0;for(let t=e.length-1;t>=0;t--)if(e.charCodeAt(t)===47){if(!i){n=t+1;break}}else r===-1&&(i=!1,r=t+1);let a=r===-1?``:e.slice(n,r);return t&&a.endsWith(t)&&a!==t?a.slice(0,a.length-t.length):a}function PW(e){let t=NW(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function FW(...e){let t=``,n=!1;for(let r=e.length-1;r>=0&&!n;r--){let i=e[r];typeof i!=`string`||i.length===0||(t=t.length>0?`${i}/${t}`:i,n=i.charCodeAt(0)===47)}n||(t=t.length>0?`/${t}`:`/`);let r=kW(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function IW(e,t){let n=FW(e),r=FW(t);if(n===r)return``;let i=n.split(`/`).filter(Boolean),a=r.split(`/`).filter(Boolean),o=0;for(;o<i.length&&o<a.length&&i[o]===a[o];)o++;return[...i.slice(o).map(()=>`..`),...a.slice(o)].join(`/`)}function LW(e){let t=e.charCodeAt(0)===47?`/`:``,n=NW(e),r=PW(e),i=r?n.slice(0,n.length-r.length):n,a=MW(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function RW(e){let t=e.dir||e.root||``,n=e.base||`${e.name||``}${e.ext||``}`;return t?t===e.root?`${t}${n}`:`${t}/${n}`:n}const zW={sep:`/`,delimiter:`:`,basename:NW,dirname:MW,extname:PW,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:jW,normalize:AW,resolve:FW,relative:IW,parse:LW,format:RW},BW=65536,VW={md5:kB.md5,sha1:AB.sha1,sha256:jB.sha256};function HW(e,t){let n=globalThis.Buffer;if(!n)throw Error(`crypto.createHash: Buffer is unavailable in this environment`);return t?n.from(e,t):n.from(e)}function UW(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(HW(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function WW(e){let t=String(e).toLowerCase().replace(`-`,``),n=VW[t];if(!n)throw Error(`Digest method not supported: ${e}`);let r=n.create(),i=!1,a={update(e,t){if(i)throw Error(`Digest already called`);return r.update(UW(e,t)),a},digest(e){i=!0;let t=HW(r.array());return e?t.toString(e):t}};return a}function GW(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function KW(e){return GW().getRandomValues(e)}function qW(e){for(let t=0;t<e.length;t+=BW){let n=Math.min(t+BW,e.length);KW(e.subarray(t,n))}}function JW(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const YW=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function XW(){let e=GW();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=KW(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${YW[t[0]]}${YW[t[1]]}${YW[t[2]]}${YW[t[3]]}-${YW[t[4]]}${YW[t[5]]}-${YW[t[6]]}${YW[t[7]]}-${YW[t[8]]}${YW[t[9]]}-${YW[t[10]]}${YW[t[11]]}${YW[t[12]]}${YW[t[13]]}${YW[t[14]]}${YW[t[15]]}`}const ZW={randomFillSync(e,t=0,n){let r=JW(e),i=t,a=n===void 0?r.length:i+n;return qW(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return qW(JW(n)),n},randomUUID:XW,getRandomValues(e){return KW(e)},createHash:WW,get webcrypto(){return GW()},get subtle(){return GW().subtle}};var QW=class extends Error{actual;expected;operator;generatedMessage;code;constructor(e={}){let t=!e.message;super(e.message||`${$W(e.actual)} ${e.operator||`!=`} ${$W(e.expected)}`),this.name=`AssertionError`,this.actual=e.actual,this.expected=e.expected,this.operator=e.operator||``,this.generatedMessage=t,this.code=`ERR_ASSERTION`}};function $W(e){if(typeof e==`string`)return JSON.stringify(e);if(e==null)return String(e);if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function eG(e,t){return e instanceof Error?e:typeof e==`string`?new QW({message:e}):t()}function tG(e,t,n,r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!rG(e[i],t[i],n,r))return!1;return!0}function nG(e,t,n,r){let i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(let a of i){if(!Object.prototype.hasOwnProperty.call(t,a))return!1;let i=e[a],o=t[a];if(!rG(i,o,n,r))return!1}return!0}function rG(e,t,n,r){if((n?Object.is(e,t):e===t)||!n&&e==t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;let i=e,a=t;return n&&Object.getPrototypeOf(i)!==Object.getPrototypeOf(a)?!1:r.get(i)===a?!0:(r.set(i,a),Array.isArray(e)===Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)?tG(e,t,n,r):nG(i,a,n,r):!1)}function iG(e,t){try{if(e instanceof t)return!0}catch{}try{return!!t(e)}catch{return!1}}function aG(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(r instanceof RegExp){if(typeof t!=`string`||!r.test(t))return!1}else if(t!==r)return!1}return!0}function oG(e,t){if(t===void 0)return!0;if(t instanceof RegExp){let n=e instanceof Error?e.message:String(e);return t.test(n)}return typeof t==`function`?iG(e,t):t&&typeof t==`object`?!e||typeof e!=`object`?!1:aG(e,t):!1}function sG(e){let t=(e,t)=>{if(!e)throw eG(t,()=>new QW({message:`The expression evaluated to a falsy value`,actual:e,expected:!0,operator:`==`}))},n=((e,n)=>t(e,n)),r=(e,t,n)=>{if(!Object.is(e,t))throw eG(n,()=>new QW({actual:e,expected:t,operator:`strictEqual`}))},i=(t,n,i)=>{if(e){r(t,n,i);return}if(t!=n)throw eG(i,()=>new QW({actual:t,expected:n,operator:`==`}))},a=(e,t,n)=>{if(Object.is(e,t))throw eG(n,()=>new QW({actual:e,expected:t,operator:`notStrictEqual`}))},o=(t,n,r)=>{if(e){a(t,n,r);return}if(t==n)throw eG(r,()=>new QW({actual:t,expected:n,operator:`!=`}))},s=(e,t,n)=>{if(!rG(e,t,!0,new WeakMap))throw eG(n,()=>new QW({actual:e,expected:t,operator:`deepStrictEqual`}))},c=(t,n,r)=>{if(e){s(t,n,r);return}if(!rG(t,n,!1,new WeakMap))throw eG(r,()=>new QW({actual:t,expected:n,operator:`deepEqual`}))},l=(e,t,n)=>{if(rG(e,t,!0,new WeakMap))throw eG(n,()=>new QW({actual:e,expected:t,operator:`notDeepStrictEqual`}))};return n.ok=t,n.equal=i,n.notEqual=o,n.strictEqual=r,n.notStrictEqual=a,n.deepEqual=c,n.deepStrictEqual=s,n.notDeepEqual=(t,n,r)=>{if(e){l(t,n,r);return}if(rG(t,n,!1,new WeakMap))throw eG(r,()=>new QW({actual:t,expected:n,operator:`notDeepEqual`}))},n.notDeepStrictEqual=l,n.throws=(e,t,n)=>{let r,i=!1;try{e()}catch(e){r=e,i=!0}if(!i)throw eG(typeof t==`string`?t:n,()=>new QW({message:`Missing expected exception`,operator:`throws`}));if(!(typeof t==`string`||t instanceof Error)&&!oG(r,t))throw eG(n,()=>new QW({message:`Got unwanted exception`,actual:r,operator:`throws`}))},n.doesNotThrow=(e,t)=>{try{e()}catch(e){throw eG(t,()=>new QW({message:`Got unwanted exception`,actual:e,operator:`doesNotThrow`}))}},n.fail=e=>{throw eG(e,()=>new QW({message:`Failed`,operator:`fail`}))},n.AssertionError=QW,n}const cG=sG(!0);cG.strict=cG;const lG=sG(!1);lG.strict=cG;const uG=Symbol.for(`nodejs.util.inspect.custom`),dG=Symbol.for(`nodejs.util.promisify.custom`);function fG(e){return`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}'`}function pG(e){if(e===null)return`null`;let t=typeof e;if(t===`string`)return fG(e);if(t===`number`)return Object.is(e,-0)?`-0`:String(e);if(t===`bigint`)return`${String(e)}n`;if(t===`boolean`||t===`undefined`)return String(e);if(t===`symbol`)return e.toString();if(t===`function`){let t=e.name;return t?`[Function: ${t}]`:`[Function (anonymous)]`}return null}function mG(e){return e instanceof RegExp?e.toString():e instanceof Date?Number.isNaN(e.getTime())?`Invalid Date`:e.toISOString():e instanceof Error?e.stack||`${e.name}: ${e.message}`:null}function hG(e,t,n){if(Array.isArray(e))return e.length===0?`[]`:`[ ${e.map(e=>gG(e,t+1,n)).join(`, `)} ]`;if(e instanceof Map){let r=[...e].map(([e,r])=>`${gG(e,t+1,n)} => ${gG(r,t+1,n)}`);return`Map(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}if(e instanceof Set){let r=[...e].map(e=>gG(e,t+1,n));return`Set(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}let r=Object.keys(e),i=e.constructor?e.constructor.name:``,a=i&&i!==`Object`?`${i} `:``;return r.length===0?`${a}{}`:`${a}{ ${r.map(r=>`${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?r:fG(r)}: ${gG(e[r],t+1,n)}`).join(`, `)} }`}function gG(e,t,n){let r=pG(e);if(r!==null)return r;let i=e,a=mG(i);if(a!==null)return a;let o=i[uG];if(typeof o==`function`)try{return String(o.call(i,n.maxDepth,n.opts))}catch{}if(n.seen.has(e))return`[Circular *1]`;if(n.maxDepth!==null&&t>n.maxDepth)return Array.isArray(e)?`[Array]`:`[Object]`;n.seen.add(e);try{return hG(i,t,n)}finally{n.seen.delete(e)}}function _G(e,t={}){let n=t.depth===void 0?2:t.depth;return gG(e,0,{seen:new Set,maxDepth:n,opts:t})}function vG(e,t,n,r){if(e===`%%`)return`%`;if(n.i>=t.length)return e;let i=t[n.i];switch(e){case`%s`:return n.i++,typeof i==`string`?i:typeof i==`bigint`?`${String(i)}n`:i==null||typeof i==`number`||typeof i==`boolean`?String(i):_G(i,{depth:r.depth===void 0?2:r.depth});case`%d`:return n.i++,typeof i==`bigint`?`${String(i)}n`:Number.isNaN(Number(i))?`NaN`:String(Number(i));case`%i`:return n.i++,typeof i==`bigint`?`${String(i)}n`:String(Number.parseInt(i,10));case`%f`:return n.i++,String(typeof i==`bigint`?i:Number.parseFloat(i));case`%j`:n.i++;try{return JSON.stringify(i)??`undefined`}catch{return`[Circular]`}case`%o`:return n.i++,_G(i,{depth:4});case`%O`:return n.i++,_G(i,{depth:null});case`%c`:return n.i++,``;default:return e}}function yG(e,...t){let n=t[0];if(typeof n!=`string`)return t.map(e=>typeof e==`string`?e:_G(e)).join(` `);let r={i:1},i=n.replace(/%[sdifjoOc%]/g,n=>vG(n,t,r,e));for(;r.i<t.length;r.i++){let e=t[r.i];i+=` ${typeof e==`string`?e:_G(e)}`}return i}function bG(...e){return yG({},...e)}function xG(e,t){if(e==null)throw TypeError(`The constructor to "inherits" must not be null or undefined`);if(t==null)throw TypeError(`The super constructor to "inherits" must not be null or undefined`);if(t.prototype===void 0)throw TypeError(`The super constructor to "inherits" must have a prototype`);e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype)}function SG(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type function`);let t=e[dG];if(t){if(typeof t!=`function`)throw TypeError(`The [util.promisify.custom] property must be of type function`);return t}function n(...t){return new Promise((n,r)=>{e.call(this,...t,(e,...t)=>{if(e){r(e);return}n(t.length>1?t:t[0])})})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),n}const CG=_G;CG.custom=uG;const wG=SG;wG.custom=dG;const TG={format:bG,formatWithOptions:yG,inspect:CG,inherits:xG,promisify:wG};function EG(e){return typeof e==`string`?new Uint8Array(HW(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function DG(e){let t={};return e&&(typeof e.level==`number`&&(t.level=e.level),typeof e.windowBits==`number`&&(t.windowBits=e.windowBits),typeof e.memLevel==`number`&&(t.memLevel=e.memLevel),typeof e.strategy==`number`&&(t.strategy=e.strategy)),t}function OG(e,t,n){return HW(e(EG(t),DG(n)))}function kG(e,t,n,r){let i=typeof n==`function`?n:r,a=typeof n==`function`?void 0:n;if(typeof i!=`function`)throw TypeError(`zlib: callback is required`);let o;try{o=OG(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const AG={gzipSync:(e,t)=>OG(iW,e,t),gunzipSync:(e,t)=>OG(cW,e,t),deflateSync:(e,t)=>OG(nW,e,t),inflateSync:(e,t)=>OG(cW,e,t),deflateRawSync:(e,t)=>OG(rW,e,t),inflateRawSync:(e,t)=>OG(lW,e,t),gzip:(e,t,n)=>kG(iW,e,t,n),gunzip:(e,t,n)=>kG(cW,e,t,n),deflate:(e,t,n)=>kG(nW,e,t,n),inflate:(e,t,n)=>kG(cW,e,t,n),deflateRaw:(e,t,n)=>kG(rW,e,t,n),inflateRaw:(e,t,n)=>kG(lW,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}},jG={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
|
|
4857
|
-
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function MG(e){let t=typeof e==`string`?e:e.href;if(!t.startsWith(`file://`))throw TypeError(`fileURLToPath: not a file URL`);let n=t.slice(7);return decodeURIComponent(n)}function NG(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const PG={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:MG,pathToFileURL:NG};var FG=class{_events=new Map;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}addListener(e,t){return this.on(e,t)}off(e,t){let n=this._events.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this._events.delete(e)}return this}removeListener(e,t){return this.off(e,t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}removeAllListeners(e){return e===void 0?this._events.clear():this._events.delete(e),this}listenerCount(e){return this._events.get(e)?.length??0}listeners(e){return[...this._events.get(e)??[]]}};const IG=Object.assign(FG,{EventEmitter:FG,default:FG});var LG=class{_events=new Map;writable=!0;readable=!0;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}off(e,t){let n=this._events.get(e);if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}return this}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}pipe(e){return e}removeListener(e,t){return this.off(e,t)}removeAllListeners(){return this._events.clear(),this}},RG=class extends LG{read(){return null}destroy(){return this}},zG=class extends LG{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},BG=class extends LG{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const VG={Readable:RG,Writable:zG,Transform:BG,PassThrough:class extends BG{},Stream:LG};let HG=1;function UG(e){if(typeof e==`string`)return e;if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return e==null?``:String(e)}function WG(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?HW(e):HW(e).toString(t)}function GG(e,t){if(e.length===0)return WG(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function KG(e,t,n){t.length>0&&e.emit(`data`,WG(t,n)),e.readable=!1,e.emit(`end`)}function qG(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(UG(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(UG(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var JG=class extends FG{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=HG++,this.spawnfile=n,this.spawnargs=r,this.stdout=new RG,this.stderr=new RG,this.stdin=qG(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){KG(this.stdout,e.stdout,t),KG(this.stderr,e.stderr,t),this.exitCode=e.exitCode;let n=this.killed?null:e.exitCode,r=this.killed?this.signalCode:null;this.emit(`exit`,n,r),this.emit(`close`,n,r)}kill(e=`SIGTERM`){return this.killed=!0,this.signalCode=e,this.handle.kill(e).catch(()=>{}),!0}};function YG(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new JG(o,r,i,a);return n.input!==void 0&&s.stdin.write(UG(n.input)),queueMicrotask(()=>o.stdin.end()),s},n=(e,t,n,r)=>{if(typeof r!=`function`)return;let i=[],a=[];e.stdout.on(`data`,e=>i.push(e)),e.stderr.on(`data`,e=>a.push(e)),e.once(`error`,e=>r(e,GG(i,t),GG(a,t))),e.once(`close`,(o,s)=>{let c=GG(i,t),l=GG(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${UG(l)}`),{code:o===null?void 0:o,killed:e.killed,signal:s??null,cmd:n}),c,l)})},r=(e,r,i)=>{let a=typeof r==`function`?r:i,o=r&&typeof r==`object`?r:{},s=o.encoding===void 0?`utf8`:o.encoding,c=t(e,o,s,e,[]);return n(c,s,e,a),c},i=(e,r,i,a)=>{let o=[],s={},c;Array.isArray(r)?(o=r,typeof i==`function`?c=i:(s=i??{},c=typeof a==`function`?a:void 0)):typeof r==`function`?c=r:r&&typeof r==`object`&&(s=r,c=typeof i==`function`?i:void 0);let l=s.encoding===void 0?`utf8`:s.encoding,u=[e,...o],d=t(u,s,l,e,o);return n(d,l,u.join(` `),c),d},a=(e,n,r)=>{let i=[],a={};Array.isArray(n)?(i=n,a=r??{}):n&&typeof n==`object`&&(a=n);let o=a.encoding===void 0?`buffer`:a.encoding,s=a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i];return t(s,a,o,e,i)},o=(e,t)=>new Promise((n,i)=>{r(e,t,(e,t,r)=>{if(e){i(Object.assign(e,{stdout:t,stderr:r}));return}n({stdout:t,stderr:r})})}),s=(e,t,n)=>new Promise((r,a)=>{i(e,Array.isArray(t)?t:[],Array.isArray(t)?n:t,(e,t,n)=>{if(e){a(Object.assign(e,{stdout:t,stderr:n}));return}r({stdout:t,stderr:n})})}),c=e=>()=>{throw Error(`child_process.${e} is not available in the browser realm`)},l=(e,t)=>{Object.defineProperty(e,dG,{value:t,enumerable:!1,configurable:!0})};return l(r,o),l(i,s),{exec:r,execFile:i,spawn:a,execSync:c(`execSync`),spawnSync:c(`spawnSync`),execFileSync:c(`execFileSync`),fork:c(`fork`),ChildProcess:JG}}function XG(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 ZG(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`,XG(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 QG(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(ZG(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 $G(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 eK(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:$G(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function tK(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:$G(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:$G(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:$G(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await eK(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function nK(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 rK(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 iK(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 tK(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=nK(c),d=rK(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function aK(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 oK(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=aK(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 sK(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 cK(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 cK(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:lK(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:lK(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:lK(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 lK(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 uK(e){return{findTab:t=>e.call(`browser`,`findTab`,[fK(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,pK(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[aK(t),dK(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[aK(t),dK(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[aK(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[aK(t),n]),fetch:(t,n,r={})=>iK(n,r).then(n=>e.call(`browser`,`evalAsync`,[aK(t),n])),websocket:oK(e)}}function dK(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 fK(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 pK(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function mK(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function hK(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),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:mK(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function gK(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function _K(e){let t=gK(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function vK(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function yK(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function bK(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var xK=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;tombstones=new Set;removedDirs=new Set;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.tombstones=new Set,this.removedDirs=new Set,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=gK(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated,size:t.size}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=_K(gK(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=_K(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=_K(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}commitWrite(e,t){this.writeFile(e,t);let n=gK(e);for(this.initialContent.set(n,t);n!==`/`;){let e=this.tree.get(n);e&&(this.initialPaths.add(n),this.initialIsDirectory.set(n,e.isDirectory)),n=_K(n)}}readFile(e){this.touched=!0;let t=gK(e),n=this.tree.get(t);if(!n||n.isDirectory)throw vK(t);if(n.truncated)throw yK(t);return n.content}writeFile(e,t){this.touched=!0;let n=gK(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1}),this.tombstones.delete(n),this.removedDirs.delete(n)}exists(e){this.touched=!0;let t=gK(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=gK(e),n=this.tree.get(t);if(!n)throw vK(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.size??n.content.byteLength}}readdir(e){this.touched=!0;let t=gK(e);if(!this.tree.get(t)?.isDirectory)throw vK(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=gK(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=_K(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw vK(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0}),this.tombstones.delete(n),this.removedDirs.delete(n)}rm(e,t){this.touched=!0;let n=gK(e),r=this.tree.get(n);if(!r)throw vK(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e),this.tombstones.add(e);t&&this.removedDirs.add(n)}this.tree.delete(n),this.tombstones.add(n)}copyFile(e,t){this.touched=!0;let n=gK(e),r=this.tree.get(n);if(!r||r.isDirectory)throw vK(n);if(r.truncated)throw yK(n);let i=gK(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1}),this.tombstones.delete(i),this.removedDirs.delete(i)}rename(e,t){this.touched=!0;let n=gK(e),r=this.tree.get(n);if(!r)throw vK(n);let i=gK(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}this.tombstones.add(n),this.removedDirs.add(n),this.tombstones.delete(i),this.removedDirs.delete(i);return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n),this.tombstones.add(n),this.tombstones.delete(i),this.removedDirs.delete(i)}unlink(e){this.touched=!0;let t=gK(e),n=this.tree.get(t);if(!n)throw vK(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t),this.tombstones.add(t)}isTombstoned(e){let t=gK(e);if(this.tombstones.has(t))return!0;for(let e of this.removedDirs)if(t===e||t.startsWith(`${e}/`))return!0;return!1}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=gK(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!bK(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function SK(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function CK(e,t,n=``){return Object.assign(Error(`${e}: sync-fs, ${n?`${n} `:``}'${t}'`),{code:e})}function wK(e){if(typeof e==`string`)return new TextEncoder().encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new TextEncoder().encode(String(e))}function TK(e,t,n){function r(e){return gK(e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e)}function i(t){try{return e.readFile(t)}catch(r){let i=r?.code;if(n&&!e.isTombstoned(t)&&(i===`ENOENT`||i===`ENOSYNC`))return n.readFile(t);throw r}}function a(t,r){n?(n.writeFile(t,r),e.commitWrite(t,r)):e.writeFile(t,r)}function o(t){if(e.exists(t))return!0;if(!n||e.isTombstoned(t))return!1;try{return n.exists(t)}catch{return!1}}function s(t){try{return e.stat(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.stat(t)}}function c(t){try{return e.readdir(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.readdir(t)}}let l=e=>({isFile:()=>e.isFile,isDirectory:()=>e.isDirectory,size:e.size}),u=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`;function d(t,n){if(!s(t).isDirectory){a(n,i(t));return}e.mkdir(n,!0);for(let e of c(t))d(u(t,e),u(n,e))}return{readFileSync(e,t){let n=typeof t==`string`?t:t?.encoding,a=i(r(e));if(n===`utf8`||n===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(e,t){a(r(e),wK(t))},appendFileSync(e,t){let n=r(e),o=new Uint8Array;try{o=i(n)}catch(e){if(e?.code!==`ENOENT`)throw e}let s=wK(t),c=new Uint8Array(o.byteLength+s.byteLength);c.set(o),c.set(s,o.byteLength),a(n,c)},truncateSync(e,t=0){let n=r(e),o=i(n),s=new Uint8Array(t);s.set(o.subarray(0,Math.min(t,o.byteLength))),a(n,s)},existsSync(e){return o(r(e))},accessSync(e){let t=r(e);if(!o(t))throw CK(`ENOENT`,t,`access`)},mkdirSync(t,n){e.mkdir(r(t),n?.recursive)},statSync(e){return l(s(r(e)))},lstatSync(e){return l(s(r(e)))},realpathSync(e){let t=r(e);if(!o(t))throw CK(`ENOENT`,t,`realpath`);return t},readdirSync(e){return c(r(e))},rmSync(t,n){let i=r(t);n?.force&&!e.exists(i)||e.rm(i,n?.recursive)},rmdirSync(t,n){let i=r(t);if(o(i)&&!s(i).isDirectory)throw CK(`ENOTDIR`,i,`rmdir`);e.rm(i,n?.recursive)},copyFileSync(e,t){a(r(t),i(r(e)))},cpSync(e,t){d(r(e),r(t))},chmodSync(e){let t=r(e);if(!o(t))throw CK(`ENOENT`,t,`chmod`)},mkdtempSync(t){return e.mkdtemp(r(t))},unlinkSync(t){e.unlink(r(t))},renameSync(t,n){e.rename(r(t),r(n))}}}function EK(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 DK(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function OK(e){return e==null?[]:Array.isArray(e)?e:[e]}function kK(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:DK(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,EK(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,EK(r)]),receiveFeatureReport:async t=>DK((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 AK(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>kK(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[OK(t)]))[0];if(!n)throw Error(`No device selected.`);return kK(e,n)}}}function jK(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 MK=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 };`)}},NK=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=jK(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 MK(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 MK(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?.())}},PK=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 NK(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()}},FK=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 NK(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 PK(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 IK(e){let t=async t=>new FK(e),n=async(t,n)=>new FK(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}function LK(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var RK=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function zK(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function BK(e,t){return{log:(...t)=>e(`${t.map(zK).join(` `)}
|
|
4858
|
-
`),info:(...t)=>e(`${t.map(
|
|
4859
|
-
`),warn:(...e)=>t(`${e.map(
|
|
4860
|
-
`),error:(...e)=>t(`${e.map(
|
|
4861
|
-
`)}}function
|
|
4862
|
-
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof
|
|
4863
|
-
`),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 ${uq(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})}function pq(e){return`slicc-sync-fs-`+e}const mq=`sync-fs-ack`,hq=`sync-fs-res`;function gq(e,t){return Object.assign(Error(`${e}: sync-fs bridge, '${t}'`),{code:e})}function _q(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function vq(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){let o=new XMLHttpRequest;try{o.open(t,_q(r,a),!1),o.responseType=`arraybuffer`,o.timeout=n,o.setRequestHeader(`x-slicc-fs-token`,e),i?o.send(new Uint8Array(i)):o.send()}catch{throw gq(`EIO`,r)}return o}function i(e,t){try{let t=new Uint8Array(e.response);return JSON.parse(new TextDecoder().decode(t))}catch{throw gq(`EIO`,t)}}function a(e,t){throw gq(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function o(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}return{readFile(e){let t=r(`GET`,e);if(o(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw gq(`EIO`,e);a(t,e)},writeFile(e,t){let n=r(`POST`,e,t);if(!o(n)){if(n.status>=200&&n.status<300)throw gq(`EIO`,e);a(n,e)}},stat(e){let t=r(`GET`,e,void 0,`stat`);if(o(t)){let n=i(t,e);if(!n||typeof n.isFile!=`boolean`||typeof n.isDirectory!=`boolean`||typeof n.size!=`number`)throw gq(`EIO`,e);return{isFile:n.isFile,isDirectory:n.isDirectory,size:n.size}}if(t.status>=200&&t.status<300)throw gq(`EIO`,e);a(t,e)},readdir(e){let t=r(`GET`,e,void 0,`readdir`);if(o(t)){let n=i(t,e);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw gq(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw gq(`EIO`,e);a(t,e)},exists(e){let t=r(`GET`,e,void 0,`exists`);if(o(t)){let n=i(t,e);if(typeof n!=`boolean`)throw gq(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw gq(`EIO`,e);a(t,e)}}}async function yq(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 xK(r)}function bq(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function xq(e){return e.syncFsToken?vq(e.syncFsToken):void 0}function Sq(e){return{usbBridge:cq(e),serialBridge:oq(e),hidBridge:AK(e)}}async function Cq(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=BK(i,a),{processShim:s,getDidCallProcessExit:c}=VK(e,i,a),l=!!e.env?.NO_COLOR,u=mW({isTTY:!l,noColor:l}),d=fW({writeStdout:i,writeStderr:a,exit:e=>{throw new RK(e)},color:u}),f=new Mz(t),p=SK(f,C),m=await yq(f,e.cwd,bq(e,a));Object.assign(p,TK(m,e.cwd,xq(e)));let h=hK(f,m,e.cwd,a),g=QG(h,{cwd:e.cwd}),_=fq({argv:e.argv,fs:p,exec:h}),v=uK(f),{usbBridge:y,serialBridge:b,hidBridge:x}=Sq(f),S=TB({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,await sK(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=KK({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=LK(T),D=await YK(f,e.code,e.cwd,T),O=QK({graph:D,fsBridge:p,processShim:s,childProcess:YG(h),nodeConsole:o,sliccyModules:w,shimmedPackages:ZK(f)}).require,k={exports:{},filename:e.filename},ee=D.entrySource!==void 0,te=D.entrySource??e.code,A=globalThis;A.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let ne=await iq(te,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,ee);await wq(f,m,a),c()||await Tq(f),delete A.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function wq(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 Tq(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 Eq(){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 Dq(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=Eq(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&Cq(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 Oq(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=Eq(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Uz(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 kq=Dq(),Aq=Oq();function jq(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?Nq():Aq({kind:e,ctx:t}):typeof Worker<`u`?Mq():kq({kind:e,ctx:t})}function Mq(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return Pq(new Worker(new URL(`/assets/js-realm-worker-DFnuhv4z.js`,``+import.meta.url),{type:`module`}))}function Nq(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return Pq(new Worker(new URL(`/assets/py-realm-worker-VuYxvTG9.js`,``+import.meta.url),{type:`module`}))}function Pq(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,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 Fq(){if(Cn())return decodeURIComponent(hn(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var Iq=e(n(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Ne,analyzeMetafileSync:()=>Le,build:()=>ke,buildSync:()=>Pe,context:()=>Ae,default:()=>Ge,formatMessages:()=>Me,formatMessagesSync:()=>Ie,initialize:()=>Ue,stop:()=>Re,transform:()=>je,transformSync:()=>Fe,version:()=>Oe}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4857
|
+
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`},MG={isatty:e=>!1,ReadStream:class{},WriteStream:class{}};function NG(e){let t=typeof e==`string`?e:e.href;if(!t.startsWith(`file://`))throw TypeError(`fileURLToPath: not a file URL`);let n=t.slice(7);return decodeURIComponent(n)}function PG(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const FG={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:NG,pathToFileURL:PG};var IG=class{_events=new Map;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}addListener(e,t){return this.on(e,t)}off(e,t){let n=this._events.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this._events.delete(e)}return this}removeListener(e,t){return this.off(e,t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}removeAllListeners(e){return e===void 0?this._events.clear():this._events.delete(e),this}listenerCount(e){return this._events.get(e)?.length??0}listeners(e){return[...this._events.get(e)??[]]}};const LG=Object.assign(IG,{EventEmitter:IG,default:IG});var RG=class{_events=new Map;writable=!0;readable=!0;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}off(e,t){let n=this._events.get(e);if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}return this}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}pipe(e){return e}removeListener(e,t){return this.off(e,t)}removeAllListeners(){return this._events.clear(),this}},zG=class extends RG{read(){return null}destroy(){return this}},BG=class extends RG{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},VG=class extends RG{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const HG={Readable:zG,Writable:BG,Transform:VG,PassThrough:class extends VG{},Stream:RG};let UG=1;function WG(e){if(typeof e==`string`)return e;if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return e==null?``:String(e)}function GG(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?HW(e):HW(e).toString(t)}function KG(e,t){if(e.length===0)return GG(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function qG(e,t,n){t.length>0&&e.emit(`data`,GG(t,n)),e.readable=!1,e.emit(`end`)}function JG(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(WG(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(WG(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var YG=class extends IG{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=UG++,this.spawnfile=n,this.spawnargs=r,this.stdout=new zG,this.stderr=new zG,this.stdin=JG(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){qG(this.stdout,e.stdout,t),qG(this.stderr,e.stderr,t),this.exitCode=e.exitCode;let n=this.killed?null:e.exitCode,r=this.killed?this.signalCode:null;this.emit(`exit`,n,r),this.emit(`close`,n,r)}kill(e=`SIGTERM`){return this.killed=!0,this.signalCode=e,this.handle.kill(e).catch(()=>{}),!0}};function XG(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new YG(o,r,i,a);return n.input!==void 0&&s.stdin.write(WG(n.input)),queueMicrotask(()=>o.stdin.end()),s},n=(e,t,n,r)=>{if(typeof r!=`function`)return;let i=[],a=[];e.stdout.on(`data`,e=>i.push(e)),e.stderr.on(`data`,e=>a.push(e)),e.once(`error`,e=>r(e,KG(i,t),KG(a,t))),e.once(`close`,(o,s)=>{let c=KG(i,t),l=KG(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${WG(l)}`),{code:o===null?void 0:o,killed:e.killed,signal:s??null,cmd:n}),c,l)})},r=(e,r,i)=>{let a=typeof r==`function`?r:i,o=r&&typeof r==`object`?r:{},s=o.encoding===void 0?`utf8`:o.encoding,c=t(e,o,s,e,[]);return n(c,s,e,a),c},i=(e,r,i,a)=>{let o=[],s={},c;Array.isArray(r)?(o=r,typeof i==`function`?c=i:(s=i??{},c=typeof a==`function`?a:void 0)):typeof r==`function`?c=r:r&&typeof r==`object`&&(s=r,c=typeof i==`function`?i:void 0);let l=s.encoding===void 0?`utf8`:s.encoding,u=[e,...o],d=t(u,s,l,e,o);return n(d,l,u.join(` `),c),d},a=(e,n,r)=>{let i=[],a={};Array.isArray(n)?(i=n,a=r??{}):n&&typeof n==`object`&&(a=n);let o=a.encoding===void 0?`buffer`:a.encoding,s=a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i];return t(s,a,o,e,i)},o=(e,t)=>new Promise((n,i)=>{r(e,t,(e,t,r)=>{if(e){i(Object.assign(e,{stdout:t,stderr:r}));return}n({stdout:t,stderr:r})})}),s=(e,t,n)=>new Promise((r,a)=>{i(e,Array.isArray(t)?t:[],Array.isArray(t)?n:t,(e,t,n)=>{if(e){a(Object.assign(e,{stdout:t,stderr:n}));return}r({stdout:t,stderr:n})})}),c=e=>()=>{throw Error(`child_process.${e} is not available in the browser realm`)},l=(e,t)=>{Object.defineProperty(e,dG,{value:t,enumerable:!1,configurable:!0})};return l(r,o),l(i,s),{exec:r,execFile:i,spawn:a,execSync:c(`execSync`),spawnSync:c(`spawnSync`),execFileSync:c(`execFileSync`),fork:c(`fork`),ChildProcess:YG}}function ZG(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 QG(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`,ZG(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 $G(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(QG(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 eK(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 tK(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:eK(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function nK(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:eK(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:eK(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:eK(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await tK(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function rK(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 iK(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 aK(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 nK(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=rK(c),d=iK(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function oK(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 sK(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=oK(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 cK(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 lK(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 lK(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:uK(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:uK(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:uK(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 uK(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 dK(e){return{findTab:t=>e.call(`browser`,`findTab`,[pK(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,mK(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[oK(t),fK(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[oK(t),fK(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[oK(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[oK(t),n]),fetch:(t,n,r={})=>aK(n,r).then(n=>e.call(`browser`,`evalAsync`,[oK(t),n])),websocket:sK(e)}}function fK(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 pK(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 mK(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function hK(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function gK(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),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:hK(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function _K(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function vK(e){let t=_K(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function yK(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function bK(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function xK(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var SK=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;tombstones=new Set;removedDirs=new Set;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.tombstones=new Set,this.removedDirs=new Set,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=_K(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated,size:t.size}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=vK(_K(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=vK(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=vK(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}commitWrite(e,t){this.writeFile(e,t);let n=_K(e);for(this.initialContent.set(n,t);n!==`/`;){let e=this.tree.get(n);e&&(this.initialPaths.add(n),this.initialIsDirectory.set(n,e.isDirectory)),n=vK(n)}}readFile(e){this.touched=!0;let t=_K(e),n=this.tree.get(t);if(!n||n.isDirectory)throw yK(t);if(n.truncated)throw bK(t);return n.content}writeFile(e,t){this.touched=!0;let n=_K(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1}),this.tombstones.delete(n),this.removedDirs.delete(n)}exists(e){this.touched=!0;let t=_K(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=_K(e),n=this.tree.get(t);if(!n)throw yK(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.size??n.content.byteLength}}readdir(e){this.touched=!0;let t=_K(e);if(!this.tree.get(t)?.isDirectory)throw yK(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=_K(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=vK(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw yK(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0}),this.tombstones.delete(n),this.removedDirs.delete(n)}rm(e,t){this.touched=!0;let n=_K(e),r=this.tree.get(n);if(!r)throw yK(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e),this.tombstones.add(e);t&&this.removedDirs.add(n)}this.tree.delete(n),this.tombstones.add(n)}copyFile(e,t){this.touched=!0;let n=_K(e),r=this.tree.get(n);if(!r||r.isDirectory)throw yK(n);if(r.truncated)throw bK(n);let i=_K(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1}),this.tombstones.delete(i),this.removedDirs.delete(i)}rename(e,t){this.touched=!0;let n=_K(e),r=this.tree.get(n);if(!r)throw yK(n);let i=_K(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}this.tombstones.add(n),this.removedDirs.add(n),this.tombstones.delete(i),this.removedDirs.delete(i);return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n),this.tombstones.add(n),this.tombstones.delete(i),this.removedDirs.delete(i)}unlink(e){this.touched=!0;let t=_K(e),n=this.tree.get(t);if(!n)throw yK(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t),this.tombstones.add(t)}isTombstoned(e){let t=_K(e);if(this.tombstones.has(t))return!0;for(let e of this.removedDirs)if(t===e||t.startsWith(`${e}/`))return!0;return!1}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=_K(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!xK(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function CK(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function wK(e,t,n=``){return Object.assign(Error(`${e}: sync-fs, ${n?`${n} `:``}'${t}'`),{code:e})}function TK(e){if(typeof e==`string`)return new TextEncoder().encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new TextEncoder().encode(String(e))}function EK(e,t,n){function r(e){return _K(e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e)}function i(t){try{return e.readFile(t)}catch(r){let i=r?.code;if(n&&!e.isTombstoned(t)&&(i===`ENOENT`||i===`ENOSYNC`))return n.readFile(t);throw r}}function a(t,r){n?(n.writeFile(t,r),e.commitWrite(t,r)):e.writeFile(t,r)}function o(t){if(e.exists(t))return!0;if(!n||e.isTombstoned(t))return!1;try{return n.exists(t)}catch{return!1}}function s(t){try{return e.stat(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.stat(t)}}function c(t){try{return e.readdir(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.readdir(t)}}let l=e=>({isFile:()=>e.isFile,isDirectory:()=>e.isDirectory,size:e.size}),u=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`;function d(t,n){if(!s(t).isDirectory){a(n,i(t));return}e.mkdir(n,!0);for(let e of c(t))d(u(t,e),u(n,e))}return{readFileSync(e,t){let n=typeof t==`string`?t:t?.encoding,a=i(r(e));if(n===`utf8`||n===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(e,t){a(r(e),TK(t))},appendFileSync(e,t){let n=r(e),o=new Uint8Array;try{o=i(n)}catch(e){if(e?.code!==`ENOENT`)throw e}let s=TK(t),c=new Uint8Array(o.byteLength+s.byteLength);c.set(o),c.set(s,o.byteLength),a(n,c)},truncateSync(e,t=0){let n=r(e),o=i(n),s=new Uint8Array(t);s.set(o.subarray(0,Math.min(t,o.byteLength))),a(n,s)},existsSync(e){return o(r(e))},accessSync(e){let t=r(e);if(!o(t))throw wK(`ENOENT`,t,`access`)},mkdirSync(t,n){e.mkdir(r(t),n?.recursive)},statSync(e){return l(s(r(e)))},lstatSync(e){return l(s(r(e)))},realpathSync(e){let t=r(e);if(!o(t))throw wK(`ENOENT`,t,`realpath`);return t},readdirSync(e){return c(r(e))},rmSync(t,n){let i=r(t);n?.force&&!e.exists(i)||e.rm(i,n?.recursive)},rmdirSync(t,n){let i=r(t);if(o(i)&&!s(i).isDirectory)throw wK(`ENOTDIR`,i,`rmdir`);e.rm(i,n?.recursive)},copyFileSync(e,t){a(r(t),i(r(e)))},cpSync(e,t){d(r(e),r(t))},chmodSync(e){let t=r(e);if(!o(t))throw wK(`ENOENT`,t,`chmod`)},mkdtempSync(t){return e.mkdtemp(r(t))},unlinkSync(t){e.unlink(r(t))},renameSync(t,n){e.rename(r(t),r(n))}}}function DK(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 OK(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function kK(e){return e==null?[]:Array.isArray(e)?e:[e]}function AK(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:OK(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,DK(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,DK(r)]),receiveFeatureReport:async t=>OK((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 jK(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>AK(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[kK(t)]))[0];if(!n)throw Error(`No device selected.`);return AK(e,n)}}}function MK(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 NK=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 };`)}},PK=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=MK(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 NK(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 NK(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?.())}},FK=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 PK(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()}},IK=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 PK(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 FK(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 LK(e){let t=async t=>new IK(e),n=async(t,n)=>new IK(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}function RK(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var zK=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function BK(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function VK(e,t){return{log:(...t)=>e(`${t.map(BK).join(` `)}
|
|
4858
|
+
`),info:(...t)=>e(`${t.map(BK).join(` `)}
|
|
4859
|
+
`),warn:(...e)=>t(`${e.map(BK).join(` `)}
|
|
4860
|
+
`),error:(...e)=>t(`${e.map(BK).join(` `)}
|
|
4861
|
+
`)}}function HK(e,t,n){let r=!!e.env?.NO_COLOR,i=UK(e.stdin??``),a=dW(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new zK(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function UK(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}const WK=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`]),GK={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 KK(e,t){let n=GK[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function qK(e){return{...e,time:vW,fmt:DW,pool:OW}}function JK(e,t){return e?.startsWith(`/`)?RK(e):t}function YK(e){return e.includes(`require`)||e.includes(`import`)}async function XK(e,t,n,r){return YK(t)?e.call(`module`,`buildGraph`,[t,JK(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function ZK(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 QK(e){return{playwright:LK(e)}}function $K(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={}}=e,c=new Map(t.files.map(e=>[e.path,e.cjsSource])),l=new Map(t.files.map(e=>[e.path,e.kind])),u=new Map,d=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:nq(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=eq(t,n,r,i);if(a.hit)return a;if(WK.has(t))throw KK(e,t);if(vn.has(t))throw iq(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},f=(e,n)=>{let r=d(n);if(r.hit)return r.value;let i=e?.[n];if(i)return p(i);throw n in t.errors?Error(t.errors[n]):tq(n)};function p(e){let n=u.get(e);if(n)return n.exports;let i=c.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};u.set(e,o);let s=n=>f(t.edges[e],n),d=RK(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,d,e,r,a,globalThis.Buffer,globalThis),l.get(e)===`cjs`&&ZK(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function eq(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:zW}:e===`crypto`?{hit:!0,value:ZW}: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:lG}:e===`assert/strict`?{hit:!0,value:cG}:e===`util`?{hit:!0,value:TG}:e===`events`?{hit:!0,value:LG}:e===`os`?{hit:!0,value:jG}:e===`tty`?{hit:!0,value:MG}:e===`stream`?{hit:!0,value:HG}:e===`url`?{hit:!0,value:FG}:e===`zlib`?{hit:!0,value:AG}:{hit:!1}}function tq(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 nq(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 rq={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function iq(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${rq[t]||``}`)}async function aq(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";
|
|
4862
|
+
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof zK?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function oq(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?DK(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,DK(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function sq(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>oq(e,t)),request:async t=>oq(e,await e.call(`serial`,`request`,[kK(t)]))}}function cq(e,t){let n=t.handle,r=e=>({status:e.status,data:OK(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,DK(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,DK(r)])}}function lq(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>cq(e,t)),request:async t=>cq(e,await e.call(`usb`,`request`,[kK(t)]))}}function uq(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function dq(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function fq(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function pq(e){let t=uq(e.argv[1]??``),n=fq(t,`references`),r=fq(t,`assets`),i=fq(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)+`
|
|
4863
|
+
`),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 ${dq(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})}function mq(e){return`slicc-sync-fs-`+e}const hq=`sync-fs-ack`,gq=`sync-fs-res`;function _q(e,t){return Object.assign(Error(`${e}: sync-fs bridge, '${t}'`),{code:e})}function vq(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function yq(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){let o=new XMLHttpRequest;try{o.open(t,vq(r,a),!1),o.responseType=`arraybuffer`,o.timeout=n,o.setRequestHeader(`x-slicc-fs-token`,e),i?o.send(new Uint8Array(i)):o.send()}catch{throw _q(`EIO`,r)}return o}function i(e,t){try{let t=new Uint8Array(e.response);return JSON.parse(new TextDecoder().decode(t))}catch{throw _q(`EIO`,t)}}function a(e,t){throw _q(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function o(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}return{readFile(e){let t=r(`GET`,e);if(o(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw _q(`EIO`,e);a(t,e)},writeFile(e,t){let n=r(`POST`,e,t);if(!o(n)){if(n.status>=200&&n.status<300)throw _q(`EIO`,e);a(n,e)}},stat(e){let t=r(`GET`,e,void 0,`stat`);if(o(t)){let n=i(t,e);if(!n||typeof n.isFile!=`boolean`||typeof n.isDirectory!=`boolean`||typeof n.size!=`number`)throw _q(`EIO`,e);return{isFile:n.isFile,isDirectory:n.isDirectory,size:n.size}}if(t.status>=200&&t.status<300)throw _q(`EIO`,e);a(t,e)},readdir(e){let t=r(`GET`,e,void 0,`readdir`);if(o(t)){let n=i(t,e);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw _q(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw _q(`EIO`,e);a(t,e)},exists(e){let t=r(`GET`,e,void 0,`exists`);if(o(t)){let n=i(t,e);if(typeof n!=`boolean`)throw _q(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw _q(`EIO`,e);a(t,e)}}}async function bq(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 SK(r)}function xq(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function Sq(e){return e.syncFsToken?yq(e.syncFsToken):void 0}function Cq(e){return{usbBridge:lq(e),serialBridge:sq(e),hidBridge:jK(e)}}async function wq(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=VK(i,a),{processShim:s,getDidCallProcessExit:c}=HK(e,i,a),l=!!e.env?.NO_COLOR,u=mW({isTTY:!l,noColor:l}),d=fW({writeStdout:i,writeStderr:a,exit:e=>{throw new zK(e)},color:u}),f=new Mz(t),p=CK(f,C),m=await bq(f,e.cwd,xq(e,a));Object.assign(p,EK(m,e.cwd,Sq(e)));let h=gK(f,m,e.cwd,a),g=$G(h,{cwd:e.cwd}),_=pq({argv:e.argv,fs:p,exec:h}),v=dK(f),{usbBridge:y,serialBridge:b,hidBridge:x}=Cq(f),S=TB({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,await cK(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=qK({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=RK(T),D=await XK(f,e.code,e.cwd,T),O=$K({graph:D,fsBridge:p,processShim:s,childProcess:XG(h),nodeConsole:o,sliccyModules:w,shimmedPackages:QK(f)}).require,k={exports:{},filename:e.filename},ee=D.entrySource!==void 0,te=D.entrySource??e.code,A=globalThis;A.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let ne=await aq(te,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,ee);await Tq(f,m,a),c()||await Eq(f),delete A.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ne})}async function Tq(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 Eq(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 Dq(){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 Oq(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=Dq(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&wq(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 kq(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=Dq(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Uz(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 Aq=Oq(),jq=kq();function Mq(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?Pq():jq({kind:e,ctx:t}):typeof Worker<`u`?Nq():Aq({kind:e,ctx:t})}function Nq(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return Fq(new Worker(new URL(`/assets/js-realm-worker-d_SDr24a.js`,``+import.meta.url),{type:`module`}))}function Pq(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return Fq(new Worker(new URL(`/assets/py-realm-worker-C9yzXwPb.js`,``+import.meta.url),{type:`module`}))}function Fq(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,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 Iq(){if(Cn())return decodeURIComponent(hn(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var Lq=e(n(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Ne,analyzeMetafileSync:()=>Le,build:()=>ke,buildSync:()=>Pe,context:()=>Ae,default:()=>Ge,formatMessages:()=>Me,formatMessagesSync:()=>Ie,initialize:()=>Ue,stop:()=>Re,transform:()=>je,transformSync:()=>Fe,version:()=>Oe}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4864
4864
|
|
|
4865
4865
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
4866
4866
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
@@ -5554,8 +5554,8 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
5554
5554
|
})(postMessage)`],{type:`text/javascript`});r=new Worker(URL.createObjectURL(e))}else{let e=(e=>{var t=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});let n,r={};for(let e=self;e;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e))t in r||Object.defineProperty(r,t,{get:()=>self[t]});(()=>{let e=()=>{let e=Error(`not implemented`);return e.code=`ENOSYS`,e};if(!r.fs){let t=``;r.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(e,n){t+=i.decode(n);let r=t.lastIndexOf(`
|
|
5555
5555
|
`);return r!=-1&&(console.log(t.substring(0,r)),t=t.substring(r+1)),n.length},write(t,n,r,i,a,o){if(r!==0||i!==n.length||a!==null){o(e());return}o(null,this.writeSync(t,n))},chmod(t,n,r){r(e())},chown(t,n,r,i){i(e())},close(t,n){n(e())},fchmod(t,n,r){r(e())},fchown(t,n,r,i){i(e())},fstat(t,n){n(e())},fsync(e,t){t(null)},ftruncate(t,n,r){r(e())},lchown(t,n,r,i){i(e())},link(t,n,r){r(e())},lstat(t,n){n(e())},mkdir(t,n,r){r(e())},open(t,n,r,i){i(e())},read(t,n,r,i,a,o){o(e())},readdir(t,n){n(e())},readlink(t,n){n(e())},rename(t,n,r){r(e())},rmdir(t,n){n(e())},stat(t,n){n(e())},symlink(t,n,r){r(e())},truncate(t,n,r){r(e())},unlink(t,n){n(e())},utimes(t,n,r,i){i(e())}}}if(r.process||={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}},r.path||={resolve(...e){return e.join(`/`)}},!r.crypto)throw Error(`globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)`);if(!r.performance)throw Error(`globalThis.performance is not available, polyfill required (performance.now only)`);if(!r.TextEncoder)throw Error(`globalThis.TextEncoder is not available, polyfill required`);if(!r.TextDecoder)throw Error(`globalThis.TextDecoder is not available, polyfill required`);let n=new TextEncoder(`utf-8`),i=new TextDecoder(`utf-8`);r.Go=class{constructor(){this.argv=[`js`],this.env={},this.exit=e=>{e!==0&&console.warn(`exit code:`,e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let e=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},t=e=>this.mem.getUint32(e+0,!0)+this.mem.getInt32(e+4,!0)*4294967296,a=e=>{let t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;let n=this.mem.getUint32(e,!0);return this._values[n]},o=(e,t)=>{let n=2146959360;if(typeof t==`number`&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,n,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let r=this._ids.get(t);r===void 0&&(r=this._idPool.pop(),r===void 0&&(r=this._values.length),this._values[r]=t,this._goRefCounts[r]=0,this._ids.set(t,r)),this._goRefCounts[r]++;let i=0;switch(typeof t){case`object`:t!==null&&(i=1);break;case`string`:i=2;break;case`symbol`:i=3;break;case`function`:i=4;break}this.mem.setUint32(e+4,n|i,!0),this.mem.setUint32(e,r,!0)},s=e=>{let n=t(e+0),r=t(e+8);return new Uint8Array(this._inst.exports.mem.buffer,n,r)},c=e=>{let n=t(e+0),r=t(e+8),i=Array(r);for(let e=0;e<r;e++)i[e]=a(n+e*8);return i},l=e=>{let n=t(e+0),r=t(e+8);return i.decode(new DataView(this._inst.exports.mem.buffer,n,r))},u=(e,t)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(e,t)),d=Date.now()-performance.now();this.importObject={_gotest:{add:(e,t)=>e+t,callExport:u},gojs:{"runtime.wasmExit":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;let n=t(e+8),i=t(e+16),a=this.mem.getInt32(e+24,!0);r.fs.writeSync(n,new Uint8Array(this._inst.exports.mem.buffer,i,a))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":t=>{t>>>=0,e(t+8,(d+performance.now())*1e6)},"runtime.walltime":t=>{t>>>=0;let n=new Date().getTime();e(t+8,n/1e3),this.mem.setInt32(t+16,n%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;let n=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(n,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(n);)console.warn(`scheduleTimeoutEvent: missed timeout event`),this._resume()},t(e+8))),this.mem.setInt32(e+16,n,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(s(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;let t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){let e=this._values[t];this._values[t]=null,this._ids.delete(e),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,o(e+24,l(e+8))},"syscall/js.valueGet":e=>{e>>>=0;let t=Reflect.get(a(e+8),l(e+16));e=this._inst.exports.getsp()>>>0,o(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(a(e+8),l(e+16),a(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(a(e+8),l(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,o(e+24,Reflect.get(a(e+8),t(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(a(e+8),t(e+16),a(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{let t=a(e+8),n=Reflect.get(t,l(e+16)),r=c(e+32),i=Reflect.apply(n,t,r);e=this._inst.exports.getsp()>>>0,o(e+56,i),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.apply(t,void 0,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.construct(t,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":t=>{t>>>=0,e(t+16,parseInt(a(t+8).length))},"syscall/js.valuePrepareString":t=>{t>>>=0;let r=n.encode(String(a(t+8)));o(t+16,r),e(t+24,r.length)},"syscall/js.valueLoadString":e=>{e>>>=0;let t=a(e+8);s(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,+(a(e+8)instanceof a(e+16)))},"syscall/js.copyBytesToGo":t=>{t>>>=0;let n=s(t+8),r=a(t+32);if(!(r instanceof Uint8Array||r instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},"syscall/js.copyBytesToJS":t=>{t>>>=0;let n=a(t+8),r=s(t+16);if(!(n instanceof Uint8Array||n instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},debug:e=>{console.log(e)}}}}run(e){return t(this,null,function*(){if(!(e instanceof WebAssembly.Instance))throw Error(`Go.run: WebAssembly.Instance expected`);this._inst=e,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,r,this],this._goRefCounts=Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[r,5],[this,6]]),this._idPool=[],this.exited=!1;let t=4096,i=e=>{let r=t,i=n.encode(e+`\0`);return new Uint8Array(this.mem.buffer,t,i.length).set(i),t+=i.length,t%8!=0&&(t+=8-t%8),r},a=this.argv.length,o=[];this.argv.forEach(e=>{o.push(i(e))}),o.push(0),Object.keys(this.env).sort().forEach(e=>{o.push(i(`${e}=${this.env[e]}`))}),o.push(0);let s=t;if(o.forEach(e=>{this.mem.setUint32(t,e,!0),this.mem.setUint32(t+4,0,!0),t+=8}),t>=12288)throw Error(`total length of command line and environment variables exceeds limit`);this._inst.exports.run(a,s),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw Error(`Go program has already exited`);this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(e){let t=this;return function(){let n={id:e,this:this,args:arguments};return t._pendingEvent=n,t._resume(),n.result}}}})(),n=({data:t})=>{let a=new TextDecoder,o=r.fs,s=``;o.writeSync=(t,n)=>{if(t===1)e(n);else if(t===2){s+=a.decode(n);let e=s.split(`
|
|
5556
5556
|
`);e.length>1&&console.log(e.slice(0,-1).join(`
|
|
5557
|
-
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=ye({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Be=()=>{r.terminate(),ze=void 0,Be=void 0,Ve=void 0},Ve={build:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`build`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),context:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`context`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),transform:(e,t)=>new Promise((n,r)=>{a.then(r),d.transform({callName:`transform`,refs:null,input:e,options:t||{},isTTY:!1,fs:{readFile(e,t){t(Error(`Internal error`),null)},writeFile(e,t){t(null)}},callback:(e,t)=>e?r(e):n(t)})}),formatMessages:(e,t)=>new Promise((n,r)=>{a.then(r),d.formatMessages({callName:`formatMessages`,refs:null,messages:e,options:t,callback:(e,t)=>e?r(e):n(t)})}),analyzeMetafile:(e,t)=>new Promise((n,r)=>{a.then(r),d.analyzeMetafile({callName:`analyzeMetafile`,refs:null,metafile:typeof e==`string`?e:JSON.stringify(e),options:t,callback:(e,t)=>e?r(e):n(t)})})}}),Ge=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);const Lq
|
|
5558
|
-
`);return t===-1?``:e.slice(t+1)}function eJ(e){return ct(e).dir}const tJ=[`node`,`require`,`default`],nJ=[`node`,`import`,`default`],rJ=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,iJ=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,aJ=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,oJ=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,sJ=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function cJ(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function lJ(e){let t=cn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!cJ(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(rJ,`require`,`require`),r(iJ,`import`,`import`),r(aJ,`import`,`import`),r(oJ,`import`,`export`),r(sJ,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function uJ(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=$q(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 dJ(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??tJ,s=e.importConditions??nJ,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 uJ(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=eJ(e),p={};for(let{specifier:t,kind:i}of lJ(n)){let n;try{n=await on(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 on(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 fJ(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||sn.has(e)||UK.has(e))}async function pJ(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 lJ(t))if(fJ(e))try{let t=await dJ({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?nJ:tJ,requireConditions:tJ,importConditions:nJ});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&&(kn(t)||dn(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 mJ(){return globalThis.navigator?.hid??null}function hJ(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function gJ(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&hJ(e)===hJ(t)&&!!e.productName}var _J=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(gJ(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 vJ=null;function yJ(){return vJ||=new _J,vJ}const bJ=4*1024*1024;function xJ(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 SJ(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function CJ(e){e.opened||await e.open()}function wJ(e,t){if(e>4194304)throw Error(`${t} exceeds the ${bJ}-byte (4 MiB) v1 limit`)}function TJ(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function EJ(e,t){return(await t.getDevices()).map(t=>xJ(e.register(t),t))}async function DJ(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>xJ(e.register(t),t))}function OJ(e,t){return xJ(t,SJ(e,t))}async function kJ(e,t){await SJ(e,t).open()}async function AJ(e,t){await SJ(e,t).close()}async function jJ(e,t,n,r){wJ(r.byteLength,`send report payload`);let i=SJ(e,t);await CJ(i),await i.sendReport(n,r)}async function MJ(e,t,n,r){wJ(r.byteLength,`send feature report payload`);let i=SJ(e,t);await CJ(i),await i.sendFeatureReport(n,r)}async function NJ(e,t,n){let r=SJ(e,t);return await CJ(r),{reportId:n,bytes:TJ(await r.receiveFeatureReport(n))}}async function PJ(e,t,n){let r=SJ(e,t);await CJ(r);let i=e=>{n({reportId:e.reportId,bytes:TJ(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const FJ=6e4;function IJ(){return ve()}function LJ(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),FJ);_e(`hid-device`,e??[],void 0,{timeoutMs:FJ}).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 RJ(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var zJ=class{registry;constructor(e){this.registry=e}hid(){let e=mJ();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return EJ(this.registry,this.hid())}async request(e){if(IJ()){let t=await LJ(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=>xJ(this.registry.register(e),e))}return DJ(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(OJ(this.registry,e))}open(e){return kJ(this.registry,e)}close(e){return AJ(this.registry,e)}sendReport(e,t,n){return jJ(this.registry,e,t,RJ(n))}sendFeatureReport(e,t,n){return MJ(this.registry,e,t,RJ(n))}async receiveFeatureReport(e,t){let n=await NJ(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return PJ(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},BJ=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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:RJ(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:RJ(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 VJ(e,t){return e&&mJ()?new zJ(yJ()):t?new BJ(t):null}function HJ(e){return async function(t,n){let r=t instanceof Request?t:null,i=UJ(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=GJ(r?.headers,n?.headers),s=await JJ(n,r,a,o);s.defaultContentType&&!KJ(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 UJ(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function WJ(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 GJ(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=WJ(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function KJ(e,t){return qJ(e,t)!==void 0}function qJ(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function JJ(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=ZJ(e.body,n);return{body:await YJ(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=qJ(r,`content-type`)??``,a=e&&(!i||!c(i));return{body:n.byteLength===0?void 0:a?QJ(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function YJ(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 QJ(e);if(e instanceof ArrayBuffer)return QJ(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return QJ(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return QJ(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 XJ(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function ZJ(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!XJ(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function QJ(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 $J(){return globalThis.navigator?.serial??null}var eY=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 tY=null;function nY(){return tY||=new eY,tY}const rY=4*1024*1024;function iY(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 aY(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function oY(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function sY(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 cY(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return iY(n,e.get(n))})}async function lY(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return iY(i,e.get(i))}function uY(e,t){return iY(t,aY(e,t))}async function dY(e,t,n){let r=aY(e,t);await r.port.open(n),r.opened=!0}async function fY(e,t){let n=aY(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 pY(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 mY(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 hY(e,t,n){let r=aY(e,t),i=Math.min(n.maxBytes??4194304,rY),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=sY(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=pY(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=oY(c,a.value);let e=u();if(e)return e}}return c}async function gY(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${rY}-byte (4 MiB) v1 limit`);return await mY(aY(e,t)).write(n),n.length}async function _Y(e,t){return aY(e,t).port.getSignals()}async function vY(e,t,n){await aY(e,t).port.setSignals(n)}const yY=6e4;function bY(){return ve()}function xY(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),yY);_e(`serial-port`,e??[],void 0,{timeoutMs:yY}).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 SY(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var CY=class{registry;constructor(e){this.registry=e}serial(){let e=$J();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return cY(this.registry,this.serial())}async request(e){if(bY()){let t=await xY(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 iY(r,this.registry.get(r))}return lY(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(uY(this.registry,e))}open(e,t){return dY(this.registry,e,t)}close(e){return fY(this.registry,e)}read(e,t){return hY(this.registry,e,t)}write(e,t){return gY(this.registry,e,t)}getSignals(e){return _Y(this.registry,e)}setSignals(e,t){return vY(this.registry,e,t)}},wY=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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?SY(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:SY(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 TY(e,t){return e&&$J()?new CY(nY()):t?new wY(t):null}function EY(){return globalThis.navigator?.usb??null}function DY(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var OY=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(DY(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 kY=null;function AY(){return kY||=new OY,kY}const jY=4*1024*1024;function MY(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 NY(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function PY(e,t){if(e>4194304)throw Error(`${t} exceeds the ${jY}-byte (4 MiB) v1 limit`)}function FY(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function IY(e,t){return(await t.getDevices()).map(t=>MY(e.register(t),t))}async function LY(e,t,n){let r=await t.requestDevice({filters:n});return MY(e.register(r),r)}function RY(e,t){return MY(t,NY(e,t))}async function zY(e,t){await NY(e,t).open()}async function BY(e,t){await NY(e,t).close()}async function VY(e,t,n){await NY(e,t).selectConfiguration(n)}async function HY(e,t,n){await NY(e,t).claimInterface(n)}async function UY(e,t,n){await NY(e,t).releaseInterface(n)}async function WY(e,t,n,r){PY(r,`control-in length`);let i=await NY(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?FY(i.data):new ArrayBuffer(0)}}async function GY(e,t,n,r){PY(r.byteLength,`control-out payload`);let i=await NY(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function KY(e,t,n,r){PY(r,`transfer-in length`);let i=await NY(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?FY(i.data):new ArrayBuffer(0)}}async function qY(e,t,n,r){PY(r.byteLength,`transfer-out payload`);let i=await NY(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function JY(e,t){await NY(e,t).reset()}const YY=6e4;function XY(){return ve()}function ZY(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),YY);_e(`usb-device`,e??[],void 0,{timeoutMs:YY}).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 QY(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var $Y=class{registry;constructor(e){this.registry=e}usb(){let e=EY();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return IY(this.registry,this.usb())}async request(e){if(XY()){let t=await ZY(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 MY(this.registry.register(n),n)}return LY(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(RY(this.registry,e))}open(e){return zY(this.registry,e)}close(e){return BY(this.registry,e)}selectConfig(e,t){return VY(this.registry,e,t)}claim(e,t){return HY(this.registry,e,t)}release(e,t){return UY(this.registry,e,t)}async controlIn(e,t,n){let r=await WY(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return GY(this.registry,e,t,QY(n))}async transferIn(e,t,n){let r=await KY(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return qY(this.registry,e,t,QY(n))}reset(e){return JY(this.registry,e)}},eX=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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:QY(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:QY(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function tX(e,t){return e&&EY()?new $Y(AY()):t?new eX(t):null}const nX=new Map;function rX(e){let t=crypto.randomUUID();return nX.set(t,e),t}function iX(e){return nX.get(e)??null}function aX(e){nX.delete(e)}const oX=r(`realm-host`);function sX(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?rX({fs:t.fs,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;cX(e,i,t,n,o,c)};return e.addEventListener(`message`,l),e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,i&&aX(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 cX(e,t,n,r,i,a){try{let o=await lX(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=XX(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 lX(e,t,n,r,i){switch(e.channel){case`vfs`:return hX(e.op,e.args,t);case`exec`:return EX(e.op,e.args,t,i);case`fetch`:return AX(e.op,e.args,t);case`browser`:return PX(e.op,e.args,uX(n),n);case`usb`:return qX(e.op,e.args,fX(n));case`serial`:return JX(e.op,e.args,pX(n));case`hid`:return YX(e.op,e.args,mX(n),r);case`module`:return MX(e.op,e.args,t);case`wasm`:return NX(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function uX(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 dX(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 fX(e){if(e.usbBackend)return e.usbBackend;let t=tX(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function pX(e){if(e.serialBackend)return e.serialBackend;let t=TY(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function mX(e){if(e.hidBackend)return e.hidBackend;let t=VJ(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function hX(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 SX(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await CX(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const gX=10485760;function _X(e){return e.fileCount>=500||e.totalBytes>=gX}function vX(e){return e.entries.length>=2e4}async function yX(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 bX(e,t,n,r){if(n>1048576||_X(r)||r.totalBytes+n>gX){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function xX(e,t,n){if(vX(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(vX(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await yX(e,t,r,n):i.isFile&&await bX(e,t,i.size,n)}}async function SX(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await xX(e,t,n),t!==`/tmp`&&await xX(e,`/tmp`,n),{entries:n.entries}}async function CX(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const wX=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),TX=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function EX(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 OX(t,n,r);if(e===`kill`)return kX(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function DX(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 OX(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??{};DX(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 kX(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&wX.has(r)?r:`SIGTERM`;TX.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 AX(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?HJ(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 jX(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 MX(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=jX(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return pJ({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:Zq({ipk:s}),transpileEntry:Qq({ipk:s})})}async function NX(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`);return Mn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function PX(e,t,n,r){switch(e){case`findTab`:return LX(n,t[0]??{});case`ensureTab`:{let e=t[0];return RX(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return zX(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return zX(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return UX(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return WX(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await dX(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return dX(r).update(e,n)}case`wsClose`:{let e=t[0];return dX(r).close(e)}case`wsList`:return dX(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 HX(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function FX(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function IX(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=FX()?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){oX.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function LX(e,t){let n=await IX(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=GX(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 RX(e,t,n){let r=await IX(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=KX(t);if(e){let t=r.find(t=>KX(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function zX(e,t,n,r){return e.withTab(t,async()=>BX(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function BX(e){if(typeof e!=`string`)return e;let t=VX(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=VX(t);if(typeof e==`object`&&e)return e}return t}return e}function VX(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 HX(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(){
|
|
5557
|
+
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=ye({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Be=()=>{r.terminate(),ze=void 0,Be=void 0,Ve=void 0},Ve={build:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`build`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),context:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`context`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),transform:(e,t)=>new Promise((n,r)=>{a.then(r),d.transform({callName:`transform`,refs:null,input:e,options:t||{},isTTY:!1,fs:{readFile(e,t){t(Error(`Internal error`),null)},writeFile(e,t){t(null)}},callback:(e,t)=>e?r(e):n(t)})}),formatMessages:(e,t)=>new Promise((n,r)=>{a.then(r),d.formatMessages({callName:`formatMessages`,refs:null,messages:e,options:t,callback:(e,t)=>e?r(e):n(t)})}),analyzeMetafile:(e,t)=>new Promise((n,r)=>{a.then(r),d.analyzeMetafile({callName:`analyzeMetafile`,refs:null,metafile:typeof e==`string`?e:JSON.stringify(e),options:t,callback:(e,t)=>e?r(e):n(t)})})}}),Ge=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);const Rq=Lq.version;let zq=null;async function Bq(e={}){return zq||=Hq(e.onProgress,e.ipk).catch(e=>{throw zq=null,e}),zq}async function Vq(e){let t;try{t=await on(`esbuild-wasm/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=`${ct(t.path).dir}/esbuild.wasm`;if(!await e.reader.exists(n))return null;try{return await e.readBytes(n)}catch{return null}}async function Hq(e,t){let n=e??(()=>{});if(Cn())return n(`esbuild ready (node service)`),Lq;if(!t)throw Error("esbuild-wasm is not available: install via `ipk add esbuild-wasm` or invoke through `ipx esbuild`");let r=await Vq(t);if(!r)throw Error("esbuild-wasm is not installed in node_modules: run `ipk add esbuild-wasm` or invoke through `ipx esbuild`");n(`esbuild.wasm loaded from ipk node_modules (${r.byteLength} bytes)`);let i=await jn(r);return await Lq.initialize({wasmModule:i,worker:!pn()}),n(`esbuild ready`),Lq}function Uq(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function Wq(e){return e instanceof Error?e.message:String(e)}function Gq(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function Kq(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:Gq(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function qq(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:Gq(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const Jq=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,Yq=/\bimport\s*\.\s*meta\b/g;function Xq(e,t){let n=JSON.stringify(t);return e.replace(Jq,n).replace(Yq,`({ url: ${n} })`)}async function Zq(e,t,n,r){let i=await e();return i.transpileModule(Xq(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function Qq(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Bq(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Dn(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!kn(e))return e;let a=Uq(t),o;try{return await Kq(n,e,t,a)}catch(e){o=e}try{return await Zq(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${Wq(o)}; typescript fallback: ${Wq(e)}`)}}}function $q(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Bq(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Dn(t));return async({source:e,filename:t})=>{if(!kn(e)&&!dn(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?Uq(t):void 0,o=i?t:`[eval].js`,s;try{return await qq(n,e,t,a)}catch(e){s=e}try{return await Zq(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${Wq(s)}; typescript fallback: ${Wq(e)}`)}}}function eJ(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5558
|
+
`);return t===-1?``:e.slice(t+1)}function tJ(e){return ct(e).dir}const nJ=[`node`,`require`,`default`],rJ=[`node`,`import`,`default`],iJ=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,aJ=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,oJ=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,sJ=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,cJ=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function lJ(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function uJ(e){let t=cn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!lJ(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(iJ,`require`,`require`),r(aJ,`import`,`import`),r(oJ,`import`,`import`),r(sJ,`import`,`export`),r(cJ,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function dJ(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=eJ(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 fJ(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??nJ,s=e.importConditions??rJ,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 dJ(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=tJ(e),p={};for(let{specifier:t,kind:i}of uJ(n)){let n;try{n=await on(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 on(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 pJ(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||sn.has(e)||WK.has(e))}async function mJ(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 uJ(t))if(pJ(e))try{let t=await fJ({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?rJ:nJ,requireConditions:nJ,importConditions:rJ});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&&(kn(t)||dn(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 hJ(){return globalThis.navigator?.hid??null}function gJ(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function _J(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&gJ(e)===gJ(t)&&!!e.productName}var vJ=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(_J(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 yJ=null;function bJ(){return yJ||=new vJ,yJ}const xJ=4*1024*1024;function SJ(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 CJ(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function wJ(e){e.opened||await e.open()}function TJ(e,t){if(e>4194304)throw Error(`${t} exceeds the ${xJ}-byte (4 MiB) v1 limit`)}function EJ(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function DJ(e,t){return(await t.getDevices()).map(t=>SJ(e.register(t),t))}async function OJ(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>SJ(e.register(t),t))}function kJ(e,t){return SJ(t,CJ(e,t))}async function AJ(e,t){await CJ(e,t).open()}async function jJ(e,t){await CJ(e,t).close()}async function MJ(e,t,n,r){TJ(r.byteLength,`send report payload`);let i=CJ(e,t);await wJ(i),await i.sendReport(n,r)}async function NJ(e,t,n,r){TJ(r.byteLength,`send feature report payload`);let i=CJ(e,t);await wJ(i),await i.sendFeatureReport(n,r)}async function PJ(e,t,n){let r=CJ(e,t);return await wJ(r),{reportId:n,bytes:EJ(await r.receiveFeatureReport(n))}}async function FJ(e,t,n){let r=CJ(e,t);await wJ(r);let i=e=>{n({reportId:e.reportId,bytes:EJ(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const IJ=6e4;function LJ(){return ve()}function RJ(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),IJ);_e(`hid-device`,e??[],void 0,{timeoutMs:IJ}).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 zJ(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var BJ=class{registry;constructor(e){this.registry=e}hid(){let e=hJ();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return DJ(this.registry,this.hid())}async request(e){if(LJ()){let t=await RJ(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=>SJ(this.registry.register(e),e))}return OJ(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(kJ(this.registry,e))}open(e){return AJ(this.registry,e)}close(e){return jJ(this.registry,e)}sendReport(e,t,n){return MJ(this.registry,e,t,zJ(n))}sendFeatureReport(e,t,n){return NJ(this.registry,e,t,zJ(n))}async receiveFeatureReport(e,t){let n=await PJ(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return FJ(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},VJ=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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:zJ(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:zJ(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 HJ(e,t){return e&&hJ()?new BJ(bJ()):t?new VJ(t):null}function UJ(e){return async function(t,n){let r=t instanceof Request?t:null,i=WJ(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=KJ(r?.headers,n?.headers),s=await YJ(n,r,a,o);s.defaultContentType&&!qJ(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 WJ(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function GJ(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 KJ(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=GJ(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function qJ(e,t){return JJ(e,t)!==void 0}function JJ(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function YJ(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=QJ(e.body,n);return{body:await XJ(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=JJ(r,`content-type`)??``,a=e&&(!i||!c(i));return{body:n.byteLength===0?void 0:a?$J(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function XJ(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 $J(e);if(e instanceof ArrayBuffer)return $J(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return $J(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return $J(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 ZJ(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function QJ(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!ZJ(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function $J(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 eY(){return globalThis.navigator?.serial??null}var tY=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 nY=null;function rY(){return nY||=new tY,nY}const iY=4*1024*1024;function aY(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 oY(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function sY(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function cY(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 lY(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return aY(n,e.get(n))})}async function uY(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return aY(i,e.get(i))}function dY(e,t){return aY(t,oY(e,t))}async function fY(e,t,n){let r=oY(e,t);await r.port.open(n),r.opened=!0}async function pY(e,t){let n=oY(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 mY(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 hY(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 gY(e,t,n){let r=oY(e,t),i=Math.min(n.maxBytes??4194304,iY),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=cY(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=mY(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=sY(c,a.value);let e=u();if(e)return e}}return c}async function _Y(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${iY}-byte (4 MiB) v1 limit`);return await hY(oY(e,t)).write(n),n.length}async function vY(e,t){return oY(e,t).port.getSignals()}async function yY(e,t,n){await oY(e,t).port.setSignals(n)}const bY=6e4;function xY(){return ve()}function SY(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),bY);_e(`serial-port`,e??[],void 0,{timeoutMs:bY}).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 CY(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var wY=class{registry;constructor(e){this.registry=e}serial(){let e=eY();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return lY(this.registry,this.serial())}async request(e){if(xY()){let t=await SY(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 aY(r,this.registry.get(r))}return uY(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(dY(this.registry,e))}open(e,t){return fY(this.registry,e,t)}close(e){return pY(this.registry,e)}read(e,t){return gY(this.registry,e,t)}write(e,t){return _Y(this.registry,e,t)}getSignals(e){return vY(this.registry,e)}setSignals(e,t){return yY(this.registry,e,t)}},TY=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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?CY(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:CY(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 EY(e,t){return e&&eY()?new wY(rY()):t?new TY(t):null}function DY(){return globalThis.navigator?.usb??null}function OY(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var kY=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(OY(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 AY=null;function jY(){return AY||=new kY,AY}const MY=4*1024*1024;function NY(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 PY(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function FY(e,t){if(e>4194304)throw Error(`${t} exceeds the ${MY}-byte (4 MiB) v1 limit`)}function IY(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function LY(e,t){return(await t.getDevices()).map(t=>NY(e.register(t),t))}async function RY(e,t,n){let r=await t.requestDevice({filters:n});return NY(e.register(r),r)}function zY(e,t){return NY(t,PY(e,t))}async function BY(e,t){await PY(e,t).open()}async function VY(e,t){await PY(e,t).close()}async function HY(e,t,n){await PY(e,t).selectConfiguration(n)}async function UY(e,t,n){await PY(e,t).claimInterface(n)}async function WY(e,t,n){await PY(e,t).releaseInterface(n)}async function GY(e,t,n,r){FY(r,`control-in length`);let i=await PY(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?IY(i.data):new ArrayBuffer(0)}}async function KY(e,t,n,r){FY(r.byteLength,`control-out payload`);let i=await PY(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function qY(e,t,n,r){FY(r,`transfer-in length`);let i=await PY(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?IY(i.data):new ArrayBuffer(0)}}async function JY(e,t,n,r){FY(r.byteLength,`transfer-out payload`);let i=await PY(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function YY(e,t){await PY(e,t).reset()}const XY=6e4;function ZY(){return ve()}function QY(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),XY);_e(`usb-device`,e??[],void 0,{timeoutMs:XY}).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 $Y(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var eX=class{registry;constructor(e){this.registry=e}usb(){let e=DY();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return LY(this.registry,this.usb())}async request(e){if(ZY()){let t=await QY(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 NY(this.registry.register(n),n)}return RY(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(zY(this.registry,e))}open(e){return BY(this.registry,e)}close(e){return VY(this.registry,e)}selectConfig(e,t){return HY(this.registry,e,t)}claim(e,t){return UY(this.registry,e,t)}release(e,t){return WY(this.registry,e,t)}async controlIn(e,t,n){let r=await GY(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return KY(this.registry,e,t,$Y(n))}async transferIn(e,t,n){let r=await qY(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return JY(this.registry,e,t,$Y(n))}reset(e){return YY(this.registry,e)}},tX=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;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:$Y(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:$Y(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function nX(e,t){return e&&DY()?new eX(jY()):t?new tX(t):null}const rX=new Map;function iX(e){let t=crypto.randomUUID();return rX.set(t,e),t}function aX(e){return rX.get(e)??null}function oX(e){rX.delete(e)}const sX=r(`realm-host`);function cX(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?iX({fs:t.fs,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;lX(e,i,t,n,o,c)};return e.addEventListener(`message`,l),e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,i&&oX(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 lX(e,t,n,r,i,a){try{let o=await uX(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=ZX(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 uX(e,t,n,r,i){switch(e.channel){case`vfs`:return gX(e.op,e.args,t);case`exec`:return DX(e.op,e.args,t,i);case`fetch`:return jX(e.op,e.args,t);case`browser`:return FX(e.op,e.args,dX(n),n);case`usb`:return JX(e.op,e.args,pX(n));case`serial`:return YX(e.op,e.args,mX(n));case`hid`:return XX(e.op,e.args,hX(n),r);case`module`:return NX(e.op,e.args,t);case`wasm`:return PX(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function dX(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 fX(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 pX(e){if(e.usbBackend)return e.usbBackend;let t=nX(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function mX(e){if(e.serialBackend)return e.serialBackend;let t=EY(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function hX(e){if(e.hidBackend)return e.hidBackend;let t=HJ(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function gX(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 CX(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await wX(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const _X=10485760;function vX(e){return e.fileCount>=500||e.totalBytes>=_X}function yX(e){return e.entries.length>=2e4}async function bX(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 xX(e,t,n,r){if(n>1048576||vX(r)||r.totalBytes+n>_X){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function SX(e,t,n){if(yX(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(yX(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await bX(e,t,r,n):i.isFile&&await xX(e,t,i.size,n)}}async function CX(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await SX(e,t,n),t!==`/tmp`&&await SX(e,`/tmp`,n),{entries:n.entries}}async function wX(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const TX=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),EX=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function DX(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 kX(t,n,r);if(e===`kill`)return AX(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function OX(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 kX(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??{};OX(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 AX(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&TX.has(r)?r:`SIGTERM`;EX.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 jX(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?UJ(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 MX(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 NX(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=MX(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return mJ({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:Qq({ipk:s}),transpileEntry:$q({ipk:s})})}async function PX(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`);return Mn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function FX(e,t,n,r){switch(e){case`findTab`:return RX(n,t[0]??{});case`ensureTab`:{let e=t[0];return zX(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return BX(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return BX(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return WX(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return GX(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await fX(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return fX(r).update(e,n)}case`wsClose`:{let e=t[0];return fX(r).close(e)}case`wsList`:return fX(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 UX(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function IX(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function LX(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=IX()?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){sX.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function RX(e,t){let n=await LX(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=KX(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 zX(e,t,n){let r=await LX(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=qX(t);if(e){let t=r.find(t=>qX(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function BX(e,t,n,r){return e.withTab(t,async()=>VX(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function VX(e){if(typeof e!=`string`)return e;let t=HX(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=HX(t);if(typeof e==`object`&&e)return e}return t}return e}function HX(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 UX(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(){
|
|
5559
5559
|
try {
|
|
5560
5560
|
var entries = performance.getEntriesByType('resource');
|
|
5561
5561
|
var now = performance.now();
|
|
@@ -5568,14 +5568,14 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
5568
5568
|
} catch (e) {
|
|
5569
5569
|
return true;
|
|
5570
5570
|
}
|
|
5571
|
-
})()`,{returnByValue:!0}))return})}async function
|
|
5571
|
+
})()`,{returnByValue:!0}))return})}async function WX(e,t,n){return e.withTab(t,async()=>{let t=((await e.sendCDP(`Network.getCookies`)).cookies??[]).find(e=>e.name===n);return t&&typeof t.value==`string`?t.value:null})}async function GX(e,t,n){return e.withTab(t,async()=>{let t=await e.evaluate(`(function(){try{var v=window.localStorage.getItem(${JSON.stringify(n)});return v===null?null:String(v);}catch(e){return null;}})()`,{returnByValue:!0});return t==null?null:typeof t==`string`?t:String(t)})}function KX(e){try{return new URL(e).hostname}catch{return null}}function qX(e){try{return new URL(e).origin}catch{return null}}async function JX(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`reset`:return n.reset(t[0]);case`selectConfig`:return n.selectConfig(t[0],t[1]);case`claim`:return n.claim(t[0],t[1]);case`release`:return n.release(t[0],t[1]);case`controlIn`:return n.controlIn(t[0],t[1],t[2]);case`controlOut`:return n.controlOut(t[0],t[1],t[2]);case`transferIn`:return n.transferIn(t[0],t[1],t[2]);case`transferOut`:return n.transferOut(t[0],t[1],t[2]);default:throw Error(`realm-host: unknown usb op '${e}'`)}}async function YX(e,t,n){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0],t[1]);case`close`:return n.close(t[0]);case`read`:{let e=t[1]??{};return n.read(t[0],e)}case`write`:return n.write(t[0],t[1]);case`getSignals`:return n.getSignals(t[0]);case`setSignals`:return n.setSignals(t[0],t[1]);default:throw Error(`realm-host: unknown serial op '${e}'`)}}async function XX(e,t,n,r){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`sendReport`:return n.sendReport(t[0],t[1],t[2]);case`sendFeatureReport`:return n.sendFeatureReport(t[0],t[1],t[2]);case`receiveFeatureReport`:return n.receiveFeatureReport(t[0],t[1]);case`subscribeInputReports`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=await n.subscribeInputReports(e,t=>{let n=t.bytes instanceof Uint8Array?t.bytes:new Uint8Array(t.bytes),i={type:`realm-event`,channel:`hid-input-report`,payload:{handle:e,reportId:t.reportId,bytes:n}};r.pushEvent(i,[n.buffer])});return r.subscriptions.set(e,i),!0}case`unsubscribeInputReports`:{let e=t[0],n=r.subscriptions.get(e);return n?(r.subscriptions.delete(e),await n(),!0):!0}default:throw Error(`realm-host: unknown hid op '${e}'`)}}function ZX(e){if(e instanceof Uint8Array)return[e.buffer];if(e&&typeof e==`object`){let t=e;if(t.body instanceof Uint8Array)return[t.body.buffer];if(t.bytes instanceof Uint8Array)return[t.bytes.buffer]}return[]}async function QX(e){let t=e.procKind??`jsh`,n=e.pm.spawn({kind:t,argv:e.argv,cwd:e.cwd,env:e.env,owner:e.owner,ppid:e.ppid}),r;try{r=await e.realmFactory({kind:e.kind,ctx:e.ctx})}catch(t){let r=t instanceof Error?t.message:String(t);return e.pm.exit(n.pid,1),{stdout:``,stderr:`realm-runner: ${r}\n`,exitCode:1}}let i=cX(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:e.syncFsBridgeEnabled});return new Promise(t=>{let a=!1,o=null,s=null,c=null,l=null,u=()=>{s&&r.controlPort.removeEventListener(`message`,s),r.removeEventListener&&(c&&r.removeEventListener(`error`,c),l&&r.removeEventListener(`messageerror`,l)),o?.(),i.dispose()},d=(i,o)=>{if(!a){a=!0,u();try{r.terminate()}catch{}e.pm.exit(n.pid,o),t(i)}};s=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;d({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;d({stdout:``,stderr:t.message+`
|
|
5572
5572
|
`,exitCode:1},1)}},c=e=>{let t=e.message??`realm error`;d({stdout:``,stderr:t+`
|
|
5573
5573
|
`,exitCode:1},1)},l=()=>{d({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
5574
|
-
`,exitCode:1},1)},o=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?d({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?d({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&d({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,s),r.addEventListener&&(r.addEventListener(`error`,c),r.addEventListener(`messageerror`,l));let f={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...i.syncFsToken===void 0?{}:{syncFsToken:i.syncFsToken}};r.controlPort.postMessage(f)})}let QX=!1;function $X(e){QX=e}function eZ(){return QX}const tZ=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function nZ(e){let t=e;if(t.length===0)return``;let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return tZ.decode(n)}function rZ(e){return e}async function iZ(e,t,n,r,i={}){return await n.fs.exists(e)?aZ(await n.fs.readFile(e),[`node`,e,...t],n,r,{...i,filename:e}):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function aZ(e,t,n,r,i={}){let a=i.realmFactory??oZ(),o=r?.processManager??lZ()??cZ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await ZX({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:Object.fromEntries(n.env.entries()),cwd:n.cwd,filename:c,stdin:rZ(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:eZ()})}function oZ(){return typeof Worker<`u`||typeof document<`u`?jq():Dq()}let sZ=null;function cZ(){return sZ||=new an,sZ}function lZ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function uZ(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}async function dZ(e,t){let n=e.trim();if(!n||Ft(It(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:`sudo: approval denied`};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const fZ=`https://api.tessl.io`,pZ=`https://browse.sh/api/skills`,mZ=`/workspace/skills`,hZ=$t,gZ=`application/vnd.github.v3+json`,_Z=`https://www.sliccy.com/skills/`,vZ=`${_Z}catalog.json`;function yZ(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function bZ(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function xZ(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0,installAll:bZ(e.installAll)},affinity:{apps:yZ(e.apps),tasks:yZ(e.tasks),role:yZ(e.role),purpose:yZ(e.purpose)},priority:n}})}const SZ={apps:3,tasks:2,role:1,purpose:1};function CZ(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*SZ.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*SZ.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=SZ.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=SZ.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function wZ(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.installAll?t+=` --all`:e.skill&&(t+=` --skill ${e.skill}`),t}async function TZ(e){let t=new Set;try{let n=await e.readDir(mZ);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}function EZ(e){return{purpose:e.purpose??``,role:e.role??``,tasks:Array.isArray(e.tasks)?e.tasks:[],apps:Array.isArray(e.apps)?e.apps:[],name:e.name??``,company:typeof e.company==`string`?e.company:void 0}}function DZ(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function OZ(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}function kZ(e,t){let n=e instanceof Error?e.message:String(e),r;try{r=new URL(t).host}catch{return n}return!r||n.includes(r)?n:`${n} (host: ${r} — network or CORS error)`}let AZ;function jZ(){return AZ||=gt.create({dbName:hZ}),AZ}async function MZ(){try{return(await(await jZ()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{return}}function NZ(e,t=gZ){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function PZ(e){let t=await MZ();return{hasToken:!!t,request:async(n,r=gZ)=>{try{return await e(n,{headers:NZ(t,r)})}catch(e){throw Error(kZ(e,n))}}}}function FZ(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}async function IZ(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}async function LZ(){try{let e=globalThis.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function RZ(){await LZ(),await IZ()}async function zZ(e,t,n,r,i=!1){let a=`${mZ}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}function BZ(e){let t=de(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function VZ(e,t,n){let r=BZ(e.body),i=r?` GitHub said: ${r}`:``,a=FZ(e.headers,`retry-after`),o=FZ(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}async function HZ(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a;try{a=await n(i,{headers:{"User-Agent":`slicc-upskill`}})}catch(e){return{status:`error`,message:kZ(e,i)}}if(a.status===404)return r===`main`?HZ(e,t,n,`master`):{status:`error`,message:`codeload returned HTTP 404`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=_(i);o||=le(a.body);try{return{status:`ok`,files:Vt(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function UZ(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function WZ(e,t,n,r){let i=0;for(let[a,o]of Object.entries(e)){if(!a.startsWith(t))continue;let e=a.slice(t.length);if(!e||a.endsWith(`/`))continue;let s=`${n}/${e}`,c=s.substring(0,s.lastIndexOf(`/`));c!==n&&await r.mkdir(c,{recursive:!0}),await r.writeFile(s,o),i++}return i}async function GZ(e,t,n,r,i,a,o){for(let s of e)if(s.type===`file`&&s.download_url){let e=await o.request(s.download_url,`*/*`);if(e.status!==200)throw Error(VZ(e,`${n}/${r}/${s.path}`,o.hasToken));let i=_(s.download_url);await a.writeFile(`${t}/${s.name}`,i??e.body)}else if(s.type===`dir`){let e=`https://api.github.com/repos/${n}/${r}/contents/${s.path}`,c=i?`${e}?ref=${encodeURIComponent(i)}`:e,l=await o.request(c);if(l.status!==200)throw Error(VZ(l,`${n}/${r}/${s.path}`,o.hasToken));let u=ue(l.body);await a.mkdir(`${t}/${s.name}`,{recursive:!0}),await GZ(u,`${t}/${s.name}`,n,r,i,a,o)}}function KZ(e){let t=e.match(/github\.com\/([^/?#]+)\/([^/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function qZ(e,t,n,r,i,a){if(i){let n=await HZ(e,t,i,a);if(n.status===`ok`){let e=UZ(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(VZ(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=ue(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function JZ(e,t,n,r,i,a,o=!1,s,c){try{let l=`${mZ}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await HZ(e,t,s,c);if(a.status===`ok`){let o=UZ(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;if(await i.mkdir(l,{recursive:!0}),await WZ(o,s,l,i)>0)return await LZ(),await IZ(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${VZ(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=ue(f.body);await i.mkdir(l,{recursive:!0});try{await GZ(p,l,e,t,c,i,a)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await RZ(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function YZ(e){let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+?)(?:\/(.+?))?)?\/?$/);if(t)return{owner:t[1],repo:t[2],branch:t[3],path:t[4]};let n=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./-]+))?$/);return n?{owner:n[1],repo:n[2],branch:n[3]}:null}async function XZ(e,t){try{let n=DZ(t);if(!n)return[];let r=await e(`${_Z}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?xZ(ue(r.body).data):[]}catch{return[]}}async function ZZ(e){let t;try{t=await e(vZ,{headers:{Accept:`application/json`}})}catch(e){throw Error(kZ(e,vZ))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return xZ(ue(t.body).data)}function QZ(e,t,n){let r=e.entry.source;if(r.skill){let e=n.get(r.skill);return e?{skillPath:e,skillName:r.skill}:r.path?{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:r.skill}:{error:`skill "${r.skill}" not found in ${t}`}}if(r.path)return{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:e.entry.name};let i=n.get(e.entry.name);return i?{skillPath:i,skillName:e.entry.name}:{error:`skill "${e.entry.name}" not found in ${t} and no explicit path provided`}}async function $Z(e,t,n,r,i,a,o,s,c){let l=e.entry.source,u=l.path.replace(/^\/|\/$/g,``),d=o<s?` (~${Math.round((s-o)*(Date.now()-c)/o/1e3)}s remaining)`:``,f=[];for(let[e,t]of r)(t===u||t.startsWith(`${u}/`))&&f.push({name:e,path:t});if(f.length===0){let n=`no skills found under "${l.path}" in ${t}`;return{results:[{ok:!1,name:e.entry.name,error:n}],line:`[${o}/${s}] Failed "${e.entry.name}" bundle from ${t}: ${n}${d}\n`}}let p=Date.now(),m=0,h=0,g=[];for(let e of f){if(i.has(e.name))continue;let t=await zZ(e.path,e.name,n,a,!1);t.ok?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.error}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${o}/${s}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${o}/${s}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${o}/${s}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function eQ(e,t,n,r,i,a,o,s,c,l){let u=e.entry.source,d=s<c?` (~${Math.round((c-s)*(Date.now()-l)/s/1e3)}s remaining)`:``,f=await qZ(n,r,i,u.path);if(f.error)return{results:[{ok:!1,name:e.entry.name,error:f.error}],line:`[${s}/${c}] Failed "${e.entry.name}" bundle from ${t}: ${f.error}${d}\n`};let p=Date.now(),m=0,h=0,g=[];for(let e of f.skills){if(a.has(e.name))continue;let t=await JZ(n,r,e.path,e.name,o,i,!1);t.exitCode===0?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.stderr.trim()}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${s}/${c}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${s}/${c}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${s}/${c}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function tQ(e,t,n,r,i,a,o,s){let c=new Map;for(let e of Object.keys(n))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``);c.set(t.split(`/`).pop()||t,t)}let l=[],u=``;for(let d of t){let t=d.entry.source;if(t.installAll&&t.path){r.count++;let t=await $Z(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=QZ(d,e,c);if(`error`in f){l.push({ok:!1,name:d.entry.name,error:f.error}),r.count++;let t=r.count<i?` (~${Math.round((i-r.count)*(Date.now()-a)/r.count/1e3)}s remaining)`:``;u+=`[${r.count}/${i}] Failed "${d.entry.name}" from ${e}: ${f.error}${t}\n`;continue}let{skillPath:p,skillName:m}=f,h=Date.now(),g=await zZ(p,m,n,s,!1);r.count++;let _=((Date.now()-h)/1e3).toFixed(1),v=(Date.now()-a)/r.count,y=Math.round((i-r.count)*v/1e3),b=r.count<i?` (~${y}s remaining)`:``;g.ok?(l.push({ok:!0,name:m}),u+=`[${r.count}/${i}] Installed "${m}" from ${e} (${_}s)${b}\n`):(l.push({ok:!1,name:m,error:g.error}),u+=`[${r.count}/${i}] Failed "${m}" from ${e}: ${g.error}${b}\n`)}return{errors:[],results:l,output:u}}async function nQ(e,t,n,r,i,a,o,s,c,l){let u=await PZ(c),d=[],f=``;for(let c of t){let t=c.entry.source;i.count++;let p=i.count<a?` (~${Math.round((a-i.count)*(Date.now()-o)/i.count/1e3)}s remaining)`:``;if(t.installAll&&t.path){let t=await eQ(c,e,n,r,u,s,l,i.count,a,o);d.push(...t.results),f+=t.line;continue}let m=t.path?t.path.replace(/^\/|\/$/g,``):c.entry.name,h=t.skill||c.entry.name,g=await JZ(n,r,m,h,l,u,!1);g.exitCode===0?(f+=`[${i.count}/${a}] Installed "${h}" from ${e}${p}\n`,d.push({ok:!0,name:h})):(f+=`[${i.count}/${a}] Failed "${h}" from ${e}: ${g.stderr.trim()}${p}\n`,d.push({ok:!1,name:h,error:g.stderr.trim()}))}return{errors:[],results:d,output:f}}function rQ(e,t,n){let r=``;for(let i of e){if(i.status===`rejected`){t.push(`upskill: unexpected error: ${i.reason}`);continue}r+=i.value.output;for(let e of i.value.errors)t.push(e);for(let e of i.value.results)e.ok?n.push(e.name):e.error&&t.push(`upskill: ${e.error}`)}return r}async function iQ(e,t,n){let r=Date.now(),i=(e,t=[])=>({installedNames:[],errors:t,skipped:e,log:``,elapsedSeconds:(Date.now()-r)/1e3}),a=null;if(n)a=EZ(n);else try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);a=EZ(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([ZZ(t),XZ(t,a.company),TZ(e)]);o=OZ(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${vZ}: ${e instanceof Error?e.message:String(e)}`])}let c=CZ(o,a).filter(e=>!s.has(e.entry.name));if(c.length===0)return i(`all-installed`);let l=new Map;for(let e of c){let t=e.entry.source.repo,n=l.get(t);n?n.push(e):l.set(t,[e])}let u=c.length,d={count:0},f=[],p=[],m=``;m=rQ(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await HZ(a,o,t);return c.status===`error`?nQ(n,i,a,o,d,u,r,s,t,e):tQ(n,i,UZ(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await RZ(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function aQ(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let oQ,sQ;async function cQ(e){if(oQ)return oQ;if(sQ)return sQ;sQ=(async()=>{let t;try{t=await e(pZ,{headers:{Accept:`application/json`}})}catch(e){throw Error(kZ(e,pZ))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=ue(t.body),r=Array.isArray(n)?n:n.skills??[];return oQ=r,r})();try{return await sQ}catch(e){throw sQ=void 0,e}}async function lQ(e,t){let n=await cQ(t),r=e.trim().toLowerCase();return r?n.filter(e=>[e.title??``,e.name??``,e.description??``,e.hostname??``,...e.tags??[]].join(` `).toLowerCase().includes(r)).map(e=>({name:e.slug,displayName:e.title||e.name||e.task||e.slug,summary:e.description||``,source:`browseSh`,qualityScore:null,installHint:`upskill browse:${e.hostname}/${e.task}`,sourceRepo:e.hostname})):[]}const uQ=/^[A-Za-z0-9._-]+$/;function dQ(e){return!e||e===`.`||e===`..`?!1:uQ.test(e)}function fQ(e){let t;if(e.startsWith(`browse:`))t=e.slice(7);else{let n=e.match(/^https:\/\/browse\.sh\/skills\/([^/?#]+)\/([^/?#]+?)\/?$/);n&&(t=`${n[1]}/${n[2]}`)}if(!t)return null;let n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n),i=t.slice(n+1);if(!r||!i||i.includes(`/`)||!dQ(r)||!dQ(i))return null;let a=aQ(r);return dQ(a)?{hostname:a,task:i}:null}function pQ(e,t){let n=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(n)for(let e of n[1].split(/\r?\n/)){let n=e.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!n||n[1]!==t)continue;let r=n[2].trim();return(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))&&(r=r.slice(1,-1)),r||void 0}}function mQ(e,t){let n=e.updated?` · updated ${e.updated}`:``;return[`> [!NOTE] **Imported from browse.sh** — original slug: \`${t}\``,`>`,"> **SLICC adaptation:** use `playwright-cli` — you are running inside the user's real browser session, so the bot-detection workarounds the upstream skill assumes are usually unnecessary.",`>`,`> Source: <https://browse.sh/skills/${t}>${n}`].join(`
|
|
5575
|
-
`)}function
|
|
5576
|
-
`}\n${t}\n\n${e.slice(n[0].length)}`:`${t}\n\n${e}`}async function
|
|
5577
|
-
`}function
|
|
5578
|
-
`;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function
|
|
5574
|
+
`,exitCode:1},1)},o=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?d({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?d({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&d({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,s),r.addEventListener&&(r.addEventListener(`error`,c),r.addEventListener(`messageerror`,l));let f={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...i.syncFsToken===void 0?{}:{syncFsToken:i.syncFsToken}};r.controlPort.postMessage(f)})}let $X=!1;function eZ(e){$X=e}function tZ(){return $X}const nZ=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function rZ(e){let t=e;if(t.length===0)return``;let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return nZ.decode(n)}function iZ(e){return e}async function aZ(e,t,n,r,i={}){return await n.fs.exists(e)?oZ(await n.fs.readFile(e),[`node`,e,...t],n,r,{...i,filename:e}):{stdout:``,stderr:`jsh: cannot find script '${e}'\n`,exitCode:127}}async function oZ(e,t,n,r,i={}){let a=i.realmFactory??sZ(),o=r?.processManager??uZ()??lZ(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await QX({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:Object.fromEntries(n.env.entries()),cwd:n.cwd,filename:c,stdin:iZ(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:tZ()})}function sZ(){return typeof Worker<`u`||typeof document<`u`?Mq():Oq()}let cZ=null;function lZ(){return cZ||=new an,cZ}function uZ(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function dZ(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}async function fZ(e,t){let n=e.trim();if(!n||Ft(It(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:`sudo: approval denied`};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const pZ=`https://api.tessl.io`,mZ=`https://browse.sh/api/skills`,hZ=`/workspace/skills`,gZ=$t,_Z=`application/vnd.github.v3+json`,vZ=`https://www.sliccy.com/skills/`,yZ=`${vZ}catalog.json`;function bZ(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function xZ(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function SZ(e){return e.map(e=>{let t=e.boost?parseFloat(e.boost):NaN,n=Number.isFinite(t)?t:void 0;return{name:e.name,displayName:e.displayName||e.name,description:e.description||``,source:{repo:e.repo,path:e.path||void 0,skill:e.skill||void 0,installAll:xZ(e.installAll)},affinity:{apps:bZ(e.apps),tasks:bZ(e.tasks),role:bZ(e.role),purpose:bZ(e.purpose)},priority:n}})}const CZ={apps:3,tasks:2,role:1,purpose:1};function wZ(e,t){return e.map(e=>{let n=0,r=[],i=(e.affinity.apps??[]).filter(e=>t.apps.includes(e));i.length&&(n+=i.length*CZ.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*CZ.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=CZ.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=CZ.purpose,r.push(`purpose(${t.purpose})`)),n*=e.priority??1,{entry:e,score:n,matchReasons:r}}).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)}function TZ(e){let t=`upskill ${e.repo}`;return e.path&&(t+=` --path ${e.path}`),e.installAll?t+=` --all`:e.skill&&(t+=` --skill ${e.skill}`),t}async function EZ(e){let t=new Set;try{let n=await e.readDir(hZ);for(let e of n)e.type===`directory`&&t.add(e.name)}catch{}let n=[`.agents`,`.claude`];try{let r=await e.readDir(`/`);for(let i of r)if(i.type===`directory`)for(let r of n)try{let n=`/${i.name}/${r}/skills`,a=await e.readDir(n);for(let e of a)e.type===`directory`&&t.add(e.name)}catch{}}catch{}return t}function DZ(e){return{purpose:e.purpose??``,role:e.role??``,tasks:Array.isArray(e.tasks)?e.tasks:[],apps:Array.isArray(e.apps)?e.apps:[],name:e.name??``,company:typeof e.company==`string`?e.company:void 0}}function OZ(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function kZ(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}function AZ(e,t){let n=e instanceof Error?e.message:String(e),r;try{r=new URL(t).host}catch{return n}return!r||n.includes(r)?n:`${n} (host: ${r} — network or CORS error)`}let jZ;function MZ(){return jZ||=gt.create({dbName:gZ}),jZ}async function NZ(){try{return(await(await MZ()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{return}}function PZ(e,t=_Z){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function FZ(e){let t=await NZ();return{hasToken:!!t,request:async(n,r=_Z)=>{try{return await e(n,{headers:PZ(t,r)})}catch(e){throw Error(AZ(e,n))}}}}function IZ(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}async function LZ(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}async function RZ(){try{let e=globalThis.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function zZ(){await RZ(),await LZ()}async function BZ(e,t,n,r,i=!1){let a=`${hZ}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}function VZ(e){let t=de(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function HZ(e,t,n){let r=VZ(e.body),i=r?` GitHub said: ${r}`:``,a=IZ(e.headers,`retry-after`),o=IZ(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}async function UZ(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,a;try{a=await n(i,{headers:{"User-Agent":`slicc-upskill`}})}catch(e){return{status:`error`,message:AZ(e,i)}}if(a.status===404)return r===`main`?UZ(e,t,n,`master`):{status:`error`,message:`codeload returned HTTP 404`};if(a.status!==200)return{status:`error`,message:`codeload returned HTTP ${a.status}`};let o=_(i);o||=le(a.body);try{return{status:`ok`,files:Vt(o)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function WZ(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function GZ(e,t,n,r){let i=0;for(let[a,o]of Object.entries(e)){if(!a.startsWith(t))continue;let e=a.slice(t.length);if(!e||a.endsWith(`/`))continue;let s=`${n}/${e}`,c=s.substring(0,s.lastIndexOf(`/`));c!==n&&await r.mkdir(c,{recursive:!0}),await r.writeFile(s,o),i++}return i}async function KZ(e,t,n,r,i,a,o){for(let s of e)if(s.type===`file`&&s.download_url){let e=await o.request(s.download_url,`*/*`);if(e.status!==200)throw Error(HZ(e,`${n}/${r}/${s.path}`,o.hasToken));let i=_(s.download_url);await a.writeFile(`${t}/${s.name}`,i??e.body)}else if(s.type===`dir`){let e=`https://api.github.com/repos/${n}/${r}/contents/${s.path}`,c=i?`${e}?ref=${encodeURIComponent(i)}`:e,l=await o.request(c);if(l.status!==200)throw Error(HZ(l,`${n}/${r}/${s.path}`,o.hasToken));let u=ue(l.body);await a.mkdir(`${t}/${s.name}`,{recursive:!0}),await KZ(u,`${t}/${s.name}`,n,r,i,a,o)}}function qZ(e){let t=e.match(/github\.com\/([^/?#]+)\/([^/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function JZ(e,t,n,r,i,a){if(i){let n=await UZ(e,t,i,a);if(n.status===`ok`){let e=WZ(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(HZ(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=ue(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function YZ(e,t,n,r,i,a,o=!1,s,c){try{let l=`${hZ}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await UZ(e,t,s,c);if(a.status===`ok`){let o=WZ(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;if(await i.mkdir(l,{recursive:!0}),await GZ(o,s,l,i)>0)return await RZ(),await LZ(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${HZ(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=ue(f.body);await i.mkdir(l,{recursive:!0});try{await KZ(p,l,e,t,c,i,a)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await zZ(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function XZ(e){let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+?)(?:\/(.+?))?)?\/?$/);if(t)return{owner:t[1],repo:t[2],branch:t[3],path:t[4]};let n=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./-]+))?$/);return n?{owner:n[1],repo:n[2],branch:n[3]}:null}async function ZZ(e,t){try{let n=OZ(t);if(!n)return[];let r=await e(`${vZ}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?SZ(ue(r.body).data):[]}catch{return[]}}async function QZ(e){let t;try{t=await e(yZ,{headers:{Accept:`application/json`}})}catch(e){throw Error(AZ(e,yZ))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return SZ(ue(t.body).data)}function $Z(e,t,n){let r=e.entry.source;if(r.skill){let e=n.get(r.skill);return e?{skillPath:e,skillName:r.skill}:r.path?{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:r.skill}:{error:`skill "${r.skill}" not found in ${t}`}}if(r.path)return{skillPath:r.path.replace(/^\/|\/$/g,``),skillName:e.entry.name};let i=n.get(e.entry.name);return i?{skillPath:i,skillName:e.entry.name}:{error:`skill "${e.entry.name}" not found in ${t} and no explicit path provided`}}async function eQ(e,t,n,r,i,a,o,s,c){let l=e.entry.source,u=l.path.replace(/^\/|\/$/g,``),d=o<s?` (~${Math.round((s-o)*(Date.now()-c)/o/1e3)}s remaining)`:``,f=[];for(let[e,t]of r)(t===u||t.startsWith(`${u}/`))&&f.push({name:e,path:t});if(f.length===0){let n=`no skills found under "${l.path}" in ${t}`;return{results:[{ok:!1,name:e.entry.name,error:n}],line:`[${o}/${s}] Failed "${e.entry.name}" bundle from ${t}: ${n}${d}\n`}}let p=Date.now(),m=0,h=0,g=[];for(let e of f){if(i.has(e.name))continue;let t=await BZ(e.path,e.name,n,a,!1);t.ok?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.error}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${o}/${s}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${o}/${s}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${o}/${s}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function tQ(e,t,n,r,i,a,o,s,c,l){let u=e.entry.source,d=s<c?` (~${Math.round((c-s)*(Date.now()-l)/s/1e3)}s remaining)`:``,f=await JZ(n,r,i,u.path);if(f.error)return{results:[{ok:!1,name:e.entry.name,error:f.error}],line:`[${s}/${c}] Failed "${e.entry.name}" bundle from ${t}: ${f.error}${d}\n`};let p=Date.now(),m=0,h=0,g=[];for(let e of f.skills){if(a.has(e.name))continue;let t=await YZ(n,r,e.path,e.name,o,i,!1);t.exitCode===0?(g.push({ok:!0,name:e.name}),m++):(g.push({ok:!1,name:e.name,error:t.stderr.trim()}),h++)}let _=((Date.now()-p)/1e3).toFixed(1),v;return v=m===0&&h===0?`[${s}/${c}] Skipped "${e.entry.name}" bundle from ${t}: all sub-skills already installed${d}\n`:h===0?`[${s}/${c}] Installed "${e.entry.name}" bundle (${m} skill(s)) from ${t} (${_}s)${d}\n`:`[${s}/${c}] Installed "${e.entry.name}" bundle (${m}/${m+h} skill(s)) from ${t} (${_}s)${d}\n`,{results:g,line:v}}async function nQ(e,t,n,r,i,a,o,s){let c=new Map;for(let e of Object.keys(n))if(e.endsWith(`/SKILL.md`)){let t=e.replace(/\/SKILL\.md$/,``);c.set(t.split(`/`).pop()||t,t)}let l=[],u=``;for(let d of t){let t=d.entry.source;if(t.installAll&&t.path){r.count++;let t=await eQ(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=$Z(d,e,c);if(`error`in f){l.push({ok:!1,name:d.entry.name,error:f.error}),r.count++;let t=r.count<i?` (~${Math.round((i-r.count)*(Date.now()-a)/r.count/1e3)}s remaining)`:``;u+=`[${r.count}/${i}] Failed "${d.entry.name}" from ${e}: ${f.error}${t}\n`;continue}let{skillPath:p,skillName:m}=f,h=Date.now(),g=await BZ(p,m,n,s,!1);r.count++;let _=((Date.now()-h)/1e3).toFixed(1),v=(Date.now()-a)/r.count,y=Math.round((i-r.count)*v/1e3),b=r.count<i?` (~${y}s remaining)`:``;g.ok?(l.push({ok:!0,name:m}),u+=`[${r.count}/${i}] Installed "${m}" from ${e} (${_}s)${b}\n`):(l.push({ok:!1,name:m,error:g.error}),u+=`[${r.count}/${i}] Failed "${m}" from ${e}: ${g.error}${b}\n`)}return{errors:[],results:l,output:u}}async function rQ(e,t,n,r,i,a,o,s,c,l){let u=await FZ(c),d=[],f=``;for(let c of t){let t=c.entry.source;i.count++;let p=i.count<a?` (~${Math.round((a-i.count)*(Date.now()-o)/i.count/1e3)}s remaining)`:``;if(t.installAll&&t.path){let t=await tQ(c,e,n,r,u,s,l,i.count,a,o);d.push(...t.results),f+=t.line;continue}let m=t.path?t.path.replace(/^\/|\/$/g,``):c.entry.name,h=t.skill||c.entry.name,g=await YZ(n,r,m,h,l,u,!1);g.exitCode===0?(f+=`[${i.count}/${a}] Installed "${h}" from ${e}${p}\n`,d.push({ok:!0,name:h})):(f+=`[${i.count}/${a}] Failed "${h}" from ${e}: ${g.stderr.trim()}${p}\n`,d.push({ok:!1,name:h,error:g.stderr.trim()}))}return{errors:[],results:d,output:f}}function iQ(e,t,n){let r=``;for(let i of e){if(i.status===`rejected`){t.push(`upskill: unexpected error: ${i.reason}`);continue}r+=i.value.output;for(let e of i.value.errors)t.push(e);for(let e of i.value.results)e.ok?n.push(e.name):e.error&&t.push(`upskill: ${e.error}`)}return r}async function aQ(e,t,n){let r=Date.now(),i=(e,t=[])=>({installedNames:[],errors:t,skipped:e,log:``,elapsedSeconds:(Date.now()-r)/1e3}),a=null;if(n)a=DZ(n);else try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);a=DZ(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([QZ(t),ZZ(t,a.company),EZ(e)]);o=kZ(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${yZ}: ${e instanceof Error?e.message:String(e)}`])}let c=wZ(o,a).filter(e=>!s.has(e.entry.name));if(c.length===0)return i(`all-installed`);let l=new Map;for(let e of c){let t=e.entry.source.repo,n=l.get(t);n?n.push(e):l.set(t,[e])}let u=c.length,d={count:0},f=[],p=[],m=``;m=iQ(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await UZ(a,o,t);return c.status===`error`?rQ(n,i,a,o,d,u,r,s,t,e):nQ(n,i,WZ(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await zZ(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function oQ(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let sQ,cQ;async function lQ(e){if(sQ)return sQ;if(cQ)return cQ;cQ=(async()=>{let t;try{t=await e(mZ,{headers:{Accept:`application/json`}})}catch(e){throw Error(AZ(e,mZ))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=ue(t.body),r=Array.isArray(n)?n:n.skills??[];return sQ=r,r})();try{return await cQ}catch(e){throw cQ=void 0,e}}async function uQ(e,t){let n=await lQ(t),r=e.trim().toLowerCase();return r?n.filter(e=>[e.title??``,e.name??``,e.description??``,e.hostname??``,...e.tags??[]].join(` `).toLowerCase().includes(r)).map(e=>({name:e.slug,displayName:e.title||e.name||e.task||e.slug,summary:e.description||``,source:`browseSh`,qualityScore:null,installHint:`upskill browse:${e.hostname}/${e.task}`,sourceRepo:e.hostname})):[]}const dQ=/^[A-Za-z0-9._-]+$/;function fQ(e){return!e||e===`.`||e===`..`?!1:dQ.test(e)}function pQ(e){let t;if(e.startsWith(`browse:`))t=e.slice(7);else{let n=e.match(/^https:\/\/browse\.sh\/skills\/([^/?#]+)\/([^/?#]+?)\/?$/);n&&(t=`${n[1]}/${n[2]}`)}if(!t)return null;let n=t.indexOf(`/`);if(n<0)return null;let r=t.slice(0,n),i=t.slice(n+1);if(!r||!i||i.includes(`/`)||!fQ(r)||!fQ(i))return null;let a=oQ(r);return fQ(a)?{hostname:a,task:i}:null}function mQ(e,t){let n=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(n)for(let e of n[1].split(/\r?\n/)){let n=e.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!n||n[1]!==t)continue;let r=n[2].trim();return(r.startsWith(`"`)&&r.endsWith(`"`)||r.startsWith(`'`)&&r.endsWith(`'`))&&(r=r.slice(1,-1)),r||void 0}}function hQ(e,t){let n=e.updated?` · updated ${e.updated}`:``;return[`> [!NOTE] **Imported from browse.sh** — original slug: \`${t}\``,`>`,"> **SLICC adaptation:** use `playwright-cli` — you are running inside the user's real browser session, so the bot-detection workarounds the upstream skill assumes are usually unnecessary.",`>`,`> Source: <https://browse.sh/skills/${t}>${n}`].join(`
|
|
5575
|
+
`)}function gQ(e,t){let n=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return n?`${n[1]}${n[2]||`
|
|
5576
|
+
`}\n${t}\n\n${e.slice(n[0].length)}`:`${t}\n\n${e}`}async function _Q(e,t,n,r,i=!1){let a=`${e}/${t}`,o=`${mZ}/${e}/${t}`,s;try{let e=await r(o,{headers:{Accept:`application/json`}});if(e.status===404)return{stdout:``,stderr:`upskill: browse.sh skill "${a}" not found\n`,exitCode:1};if(e.status!==200)return{stdout:``,stderr:`upskill: browse.sh returned HTTP ${e.status} for "${a}"\n`,exitCode:1};s=ue(e.body)}catch(e){return{stdout:``,stderr:`upskill: failed to fetch browse.sh skill "${a}": ${AZ(e,o)}\n`,exitCode:1}}let c;if(s.skillMdUrl)try{let e=await r(s.skillMdUrl,{headers:{Accept:`text/plain`}});e.status===200&&(c=de(e.body))}catch{}if(!c&&s.skillMd&&(c=s.skillMd),!c)return{stdout:``,stderr:`upskill: browse.sh skill "${a}" has no SKILL.md content\n`,exitCode:1};let l=mQ(c,`name`),u=t.replace(/-[A-Za-z0-9]{4,8}$/,``),d=l||u||t;if(!fQ(d)||d.length>64)return{stdout:``,stderr:`upskill: refusing to install browse.sh skill with unsafe name "${d}"\n`,exitCode:1};if(!fQ(e))return{stdout:``,stderr:`upskill: refusing to install browse.sh skill with unsafe hostname "${e}"\n`,exitCode:1};let f=`browse-${e}-${d}`,p=`${hZ}/${f}`;try{if(await n.stat(p),!i)return{stdout:``,stderr:`upskill: skill "${f}" already exists (use --force to overwrite)\n`,exitCode:1};await n.rm(p,{recursive:!0})}catch{}let m=hQ(s,a),h=gQ(c,m);return await n.mkdir(p,{recursive:!0}),await n.writeFile(`${p}/SKILL.md`,h),await zZ(),{stdout:`Installed skill "${f}" from browse.sh (${a})\n`,stderr:``,exitCode:0}}function vQ(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/*, **/.claude/skills/*, and **/.claude-plugin/marketplace.json skill collections anywhere in the VFS.
|
|
5577
|
+
`}function yQ(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`;case`marketplace`:return`marketplace`}}function bQ(e,t){let n=Math.max(4,...e.map(e=>e.name.length)),r=Math.max(20,97-n-2-11-1),i=`NAME`.padEnd(n),a=`─`.repeat(2+n+2+11+1+r),o=`${t}:\n\n`;o+=` ${i} SOURCE DESCRIPTION\n`,o+=`${a}\n`;for(let t of e){let e=t.description||``,i=e.length>r?`${e.slice(0,r-1)}…`:e;o+=` ${t.name.padEnd(n)} ${yQ(t.source).padEnd(11)} ${i}\n`}return o+=`\n${vQ()}`,o}function xQ(e){let t=`Skill: ${e.name}\n`;if(t+=`Description: ${e.description||`(none)`}\n`,t+=`Source: ${yQ(e.source)}\n`,t+=`Source root: ${e.sourceRoot}\n`,e.skillFilePath&&(t+=`Instructions: ${e.skillFilePath}\n`),e.shadowedPaths?.length){t+=`Shadowed paths:
|
|
5578
|
+
`;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function SQ(){return{stdout:`usage: upskill <command> [options]
|
|
5579
5579
|
|
|
5580
5580
|
Install skills from GitHub repositories, the Tessl registry, or browse.sh.
|
|
5581
5581
|
|
|
@@ -5589,7 +5589,7 @@ Commands:
|
|
|
5589
5589
|
tessl:<name> Install skill from Tessl registry
|
|
5590
5590
|
browse:<hostname>/<task> Install site-specific skill from browse.sh
|
|
5591
5591
|
|
|
5592
|
-
${
|
|
5592
|
+
${vQ()}
|
|
5593
5593
|
GitHub Installation:
|
|
5594
5594
|
upskill owner/repo List available skills in repo
|
|
5595
5595
|
upskill owner/repo --skill name Install specific skill
|
|
@@ -5631,14 +5631,14 @@ Examples:
|
|
|
5631
5631
|
upskill aemcoder/skills@fix/stateless-tab-targeting --all
|
|
5632
5632
|
upskill tessl:postgres-pro
|
|
5633
5633
|
upskill browse:weather.gov/get-forecast-1uezib
|
|
5634
|
-
`,stderr:``,exitCode:0}}function
|
|
5634
|
+
`,stderr:``,exitCode:0}}function CQ(e){return B(`skill`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return{stdout:`usage: skill <command> [options]
|
|
5635
5635
|
|
|
5636
5636
|
Commands:
|
|
5637
5637
|
list List discoverable skills
|
|
5638
5638
|
info <name> Show details about a skill
|
|
5639
5639
|
read <name> Read the SKILL.md instructions
|
|
5640
5640
|
|
|
5641
|
-
${
|
|
5641
|
+
${vQ()}
|
|
5642
5642
|
For installing skills from registries or GitHub, use 'upskill':
|
|
5643
5643
|
upskill search "query" Search registries (Tessl + browse.sh)
|
|
5644
5644
|
upskill owner/repo --list List skills in GitHub repo
|
|
@@ -5650,53 +5650,53 @@ Examples:
|
|
|
5650
5650
|
skill list
|
|
5651
5651
|
skill info bluebubbles
|
|
5652
5652
|
skill read bluebubbles
|
|
5653
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5654
|
-
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:
|
|
5653
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-CW8kM1BJ.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${vQ()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:bQ(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5654
|
+
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:xQ(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
|
|
5655
5655
|
`,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+`
|
|
5656
|
-
`,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}}})}async function
|
|
5656
|
+
`,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}}})}async function wQ(e,t){let n=`${pZ}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(AZ(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=ue(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=qZ(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function TQ(e,t){let n=`${pZ}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${AZ(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=ue(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=qZ(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const EQ=[{label:`Tessl`,host:new URL(pZ).host,fetch:wQ},{label:`browse.sh`,host:new URL(mZ).host,fetch:uQ}];function DQ(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function OQ(e,t,n=1){let r=await Promise.allSettled(EQ.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=DQ(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=EQ[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
|
|
5657
5657
|
`}return u<l&&(p+=`Showing ${d+1}-${d+f.length} of ${c}. `,p+=`Next page: upskill search ${e} --page ${u+1}\n\n`),p+=`To install:
|
|
5658
5658
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
5659
5659
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
5660
|
-
`,{stdout:p,stderr:``,exitCode:0}}function
|
|
5660
|
+
`,{stdout:p,stderr:``,exitCode:0}}function kQ(e,t,n){let r=`upskill ${e}`;return t&&(r+=` --branch ${t}`),n&&(r+=` --path ${n}`),r}async function AQ(e,t){let n=[],r;try{r=await t(e,{method:`GET`})}catch(t){return n.push({rel:Qe,href:e,error:t instanceof Error?t.message:String(t)}),{links:[],failures:n}}let i=[];for(let[e,t]of Object.entries(r.headers||{}))e.toLowerCase()===`link`&&typeof t==`string`&&t.length>0&&i.push(t);if(i.length===0)return{links:[],failures:n};let a=et(i,e),o=[];for(let e of a){if(!e.rel.includes(Qe))continue;let t=it([e]);t?.verb===`upskill`&&o.push({target:t.target,branch:t.branch,path:t.path,instruction:t.instruction,installHint:kQ(t.target,t.branch,t.path)})}return{links:o,failures:n}}function jQ(e,t,n){if(!e||t.length===0)return[];let r=[];for(let i of t){if(!i.hostname||oQ(i.hostname)!==e)continue;let t=i.name||i.task.replace(/-[A-Za-z0-9]{4,8}$/,``)||i.task,a=`browse-${i.hostname}-${t}`;r.push({slug:i.slug,hostname:i.hostname,task:i.task,title:i.title||i.name||i.task,description:i.description,installed:n.has(a),installHint:`upskill browse:${i.hostname}/${i.task}`})}return r}function MQ(e){let t=e.active?` [active]`:``,n=`${e.title||`(untitled)`}${t}\n`;if(n+=` ${e.url}\n`,e.origin.length>0){n+=` Origin-advertised:
|
|
5661
5661
|
`;for(let t of e.origin)n+=` ${t.installHint}`,t.instruction&&(n+=` # ${t.instruction}`),n+=`
|
|
5662
5662
|
`}if(e.catalog.length>0){n+=` Browse.sh catalog:
|
|
5663
5663
|
`;for(let t of e.catalog){let e=t.installed?`✓`:` `;n+=` ${e} ${t.title.padEnd(40)} ${t.installHint}\n`}}e.origin.length===0&&e.catalog.length===0&&!e.failures.length&&(n+=` No skill suggestions for this tab.
|
|
5664
5664
|
`);for(let t of e.failures)n+=` (discovery failed: ${t.error})\n`;return n+=`
|
|
5665
|
-
`,n}async function
|
|
5665
|
+
`,n}async function NQ(e,t,n,r){if(!n)return{stdout:``,stderr:`upskill: browser APIs unavailable in this environment
|
|
5666
5666
|
`,exitCode:1};let i;try{i=await n.listPages()}catch{try{i=await n.listAllTargets()}catch(e){return{stdout:``,stderr:`upskill: failed to list browser tabs: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}if(i.length===0)return r?{stdout:JSON.stringify({tabs:[]},null,2)+`
|
|
5667
5667
|
`,stderr:``,exitCode:0}:{stdout:`No open browser tabs.
|
|
5668
|
-
`,stderr:``,exitCode:0};let a=[],o=``;try{a=await
|
|
5669
|
-
`,stderr:o,exitCode:0};let l=``;for(let e of c)l+=
|
|
5668
|
+
`,stderr:``,exitCode:0};let a=[],o=``;try{a=await lQ(t)}catch(e){o=`upskill: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}\n`}let s=await EZ(e),c=[];for(let e of i){let n=``;try{n=new URL(e.url).hostname}catch{}let r=n?oQ(n):``,i=[],o=[];if(n&&/^https?:/i.test(e.url)){let n=await AQ(e.url,t);i=n.links,o=n.failures}let l=jQ(r,a,s);c.push({targetId:e.targetId,title:e.title,url:e.url,hostname:r,active:e.active,origin:i,catalog:l,failures:o})}if(r)return{stdout:JSON.stringify({tabs:c},null,2)+`
|
|
5669
|
+
`,stderr:o,exitCode:0};let l=``;for(let e of c)l+=MQ(e);return{stdout:l,stderr:o,exitCode:0}}async function PQ(e,t,n){if(n){let n=await aQ(e,t);return n.skipped===`no-profile`?{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
|
|
5670
5670
|
`,exitCode:1}:n.skipped===`catalog-fetch`?{stdout:``,stderr:n.errors.map(e=>`${e}\n`).join(``),exitCode:1}:n.skipped===`all-installed`?{stdout:`No new skill recommendations — all matching skills are already installed.
|
|
5671
5671
|
`,stderr:``,exitCode:0}:{stdout:n.log,stderr:n.errors.map(e=>`${e}\n`).join(``),exitCode:+(n.errors.length>0)}}let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
|
|
5672
|
-
`,exitCode:1};let i,a;try{let[n,o,s]=await Promise.all([(async()=>{let e=await t(
|
|
5672
|
+
`,exitCode:1};let i,a;try{let[n,o,s]=await Promise.all([(async()=>{let e=await t(yZ,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return SZ(ue(e.body).data)})(),ZZ(t,r.company),EZ(e)]);i=kZ(n,o),a=s}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${yZ}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=wZ(i,r).filter(e=>!a.has(e.entry.name));if(o.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
|
|
5673
5673
|
`,stderr:``,exitCode:0};let s=`Recommended skills for you:
|
|
5674
5674
|
|
|
5675
|
-
`,c=0;for(let e of o){c++;let t=
|
|
5676
|
-
`,{stdout:s,stderr:``,exitCode:0}}function
|
|
5675
|
+
`,c=0;for(let e of o){c++;let t=TZ(e.entry.source);s+=` ${c}. ${e.entry.displayName.padEnd(35)} score: ${Math.round(e.score)}\n`,s+=` ${e.entry.description}\n`,s+=` Match: ${e.matchReasons.join(`, `)}\n`,s+=` Install: ${t}\n\n`}return s+=`To install all recommended: upskill recommendations --install
|
|
5676
|
+
`,{stdout:s,stderr:``,exitCode:0}}function FQ(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5677
5677
|
`,exitCode:1}:$e(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
|
|
5678
|
-
`,exitCode:1}}function
|
|
5679
|
-
`,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=
|
|
5680
|
-
`,stderr:``,exitCode:0}}async function
|
|
5681
|
-
`,exitCode:1};let a=await
|
|
5678
|
+
`,exitCode:1}}function IQ(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`||!nt(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
|
|
5679
|
+
`,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=FQ(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 LQ(e){let t=await(await import(`./skills-CW8kM1BJ.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${vQ()}`,stderr:``,exitCode:0}:{stdout:bQ(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function RQ(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-CW8kM1BJ.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:xQ(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
5680
|
+
`,stderr:``,exitCode:0}}async function zQ(e,t,n,r,i,a,o){let s=``,c=``,l=0,u=e.length;for(let d=0;d<e.length;d++){let f=e[d],p=await BZ(f.path,f.name,r,i,a),m=d+1,h=((Date.now()-o)/1e3).toFixed(1),g=(Date.now()-o)/m,_=m<u?` (~${Math.round((u-m)*g/1e3)}s remaining)`:``;p.ok?(s+=`[${m}/${u}] Installed "${f.name}" from ${t}/${n} (${h}s)${_}\n`,l++):(s+=`[${m}/${u}] Failed "${f.name}": ${p.error}${_}\n`,c+=`upskill: ${p.error}\n`)}return{output:s,errors:c,successCount:l}}async function BQ(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 YZ(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 VQ(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await YZ(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 HQ(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 UQ(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await FZ(r),l=await JZ(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:HQ(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:HQ(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 UZ(i,a,r,o);if(e.status===`ok`){let r=await zQ(u,i,a,WZ(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await BQ(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await VQ(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 zZ()),{stdout:p,stderr:m,exitCode:+!!m}}function WQ(e,t,n){return B(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return SQ();if(r[0]===`tabs`)return NQ(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return PQ(e,t,r.includes(`--install`));if(r[0]===`list`)return LQ(e);if(r[0]===`info`||r[0]===`read`)return RQ(r[0],r[1],e);if(r[0]===`search`)return GQ(r,t);let a=IQ(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return SQ();if(a.sourceRef.startsWith(`tessl:`))return KQ(a.sourceRef,a.force,e,t);let o=pQ(a.sourceRef);if(o)return _Q(o.hostname,o.task,e,t,a.force);let s=XZ(a.sourceRef);return s?UQ(s,a,e,t):{stdout:``,stderr:`upskill: unrecognized source "${a.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function GQ(e,t){let n=[...e.slice(1)],r=n.indexOf(`--page`),i=1;r>=0&&(i=parseInt(n[r+1],10)||1,n.splice(r,2));let a=n.join(` `);return a?OQ(a,t,i):SQ()}async function KQ(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5681
|
+
`,exitCode:1};let a=await TQ(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await FZ(r);return YZ(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function qQ(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5682
5682
|
|
|
5683
5683
|
Plays an audio file using the Web Audio API.
|
|
5684
5684
|
-v volume Volume level (0 to 1, default 1)
|
|
5685
5685
|
-r rate Playback rate (0.25 to 4, default 1)
|
|
5686
|
-
`,stderr:``,exitCode:0}}let
|
|
5687
|
-
`,exitCode:1};let c=r.fs.resolvePath(r.cwd,e),l;try{l=new Uint8Array(await r.fs.readFileBuffer(c))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}let u=_n(c);if(!u.startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};if(!o)try{let e=new ArrayBuffer(l.byteLength);return new Uint8Array(e).set(l),await s.call(`play-audio`,{bytes:e,mimeType:u,volume:t},{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}try{let e=
|
|
5686
|
+
`,stderr:``,exitCode:0}}let JQ=null;function YQ(){return(!JQ||JQ.state===`closed`)&&(JQ=new AudioContext),JQ}async function XQ(e,t,n,r){let o=a()&&typeof AudioContext<`u`,s=i();if(!o&&!s)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
|
|
5687
|
+
`,exitCode:1};let c=r.fs.resolvePath(r.cwd,e),l;try{l=new Uint8Array(await r.fs.readFileBuffer(c))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}let u=_n(c);if(!u.startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};if(!o)try{let e=new ArrayBuffer(l.byteLength);return new Uint8Array(e).set(l),await s.call(`play-audio`,{bytes:e,mimeType:u,volume:t},{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}try{let e=YQ();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(l.byteLength);new Uint8Array(r).set(l);let i=await e.decodeAudioData(r),a=e.createBufferSource();a.buffer=i,a.playbackRate.value=n;let o=e.createGain();return o.gain.value=t,a.connect(o),o.connect(e.destination),new Promise(e=>{a.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},a.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function ZQ(){return B(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return qQ();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
|
|
5688
5688
|
`,exitCode:1};if(n=parseFloat(e[++t]),isNaN(n)||n<0||n>1)return{stdout:``,stderr:`afplay: volume must be between 0 and 1
|
|
5689
5689
|
`,exitCode:1}}else if(a===`-r`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -r requires a rate value
|
|
5690
5690
|
`,exitCode:1};if(r=parseFloat(e[++t]),isNaN(r)||r<.25||r>4)return{stdout:``,stderr:`afplay: rate must be between 0.25 and 4
|
|
5691
5691
|
`,exitCode:1}}else if(a.startsWith(`-`))return{stdout:``,stderr:`afplay: unknown option: ${a}\n`,exitCode:1};else{if(i!==null)return{stdout:``,stderr:`afplay: only one file can be specified
|
|
5692
|
-
`,exitCode:1};i=a}}return i?
|
|
5692
|
+
`,exitCode:1};i=a}}return i?XQ(i,n,r,t):qQ()})}function QQ(){return B(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
|
|
5693
5693
|
|
|
5694
5694
|
Plays a notification chime sound.
|
|
5695
5695
|
Alias for: afplay /shared/sounds/chime.mp3
|
|
5696
|
-
`,stderr:``,exitCode:0}:
|
|
5696
|
+
`,stderr:``,exitCode:0}:XQ(`/shared/sounds/chime.mp3`,1,1,t))}const $Q=r(`agent-command`);function e$(e,t,n){let r=t[n+1];return r===void 0||r.length>0&&r.startsWith(`-`)?{error:`agent: ${e} requires a value`}:r===``?{error:`agent: ${e} requires a non-empty value`}:{value:r,consumed:2}}function t$(e,t,n){let r=e$(e,t,n);return`error`in r?{error:r.error,consumed:0}:sE(r.value)?{value:r.value,consumed:r.consumed}:{error:`agent: ${e} must be one of: ${oE.join(`, `)}`,consumed:0}}function n$(e,t){let n=e$(`--read-only`,e,t);if(`error`in n)return{error:n.error,consumed:0};let r=o$(n.value);return r.length===0?{error:`agent: --read-only requires a non-empty value`,consumed:0}:{value:r,consumed:n.consumed}}function dre(e,t){let n=e[t+1];if(n===void 0||n===``||n.length>0&&n.startsWith(`-`))return{error:`agent: --schema-b64 requires a value`,consumed:0};try{let e=atob(n),t=JSON.parse(new TextDecoder().decode(Uint8Array.from(e,e=>e.charCodeAt(0))));return typeof t!=`object`||!t?{error:`agent: --schema-b64 must decode to a JSON object`,consumed:0}:{value:t,consumed:2}}catch{return{error:`agent: --schema-b64 must be valid base64-encoded JSON`,consumed:0}}}function r$(e,t,n,r){if(r.positionals.length===2)return r.positionals.push(e),{consumed:1};if(e===`-h`||e===`--help`)return r.help=!0,{consumed:1};if(e===`--model`){let i=e$(e,t,n);return`error`in i?{error:i.error,consumed:0}:(r.modelId=i.value,{consumed:i.consumed})}if(e===`--thinking`||e===`--effort`){let i=t$(e,t,n);return i.error?{error:i.error,consumed:0}:(r.thinkingLevel=i.value,{consumed:i.consumed})}if(e===`--read-only`){let e=n$(t,n);return e.error?{error:e.error,consumed:0}:(r.visiblePaths=e.value,{consumed:e.consumed})}if(e===`--schema-b64`){let e=dre(t,n);return e.error?{error:e.error,consumed:0}:(r.schemaOut=e.value,{consumed:e.consumed})}return e.length>0&&e.startsWith(`-`)?{error:`agent: unknown flag '${e}'`,consumed:0}:(r.positionals.push(e),{consumed:1})}function i$(e){if(e.help)return{help:!0};if(e.positionals.length<3)return{error:`agent: missing required argument ${[`<cwd>`,`<allowed-commands>`,`<prompt>`][e.positionals.length]}`};if(e.positionals.length>3)return{error:`agent: too many arguments`};let[t,n,r]=e.positionals;return{cwd:t,allowedCommandsRaw:n,prompt:r}}function a$(e){let t={positionals:[],help:!1},n=0;for(;n<e.length;){let r=r$(e[n],e,n,t);if(r.error)return{help:!1,error:r.error};n+=r.consumed}let r=i$(t);if(`help`in r)return{help:!0};if(`error`in r)return{help:!1,error:r.error};let i=r;return{help:!1,cwd:i.cwd,allowedCommandsRaw:i.allowedCommandsRaw,prompt:i.prompt,modelId:t.modelId,visiblePaths:t.visiblePaths,thinkingLevel:t.thinkingLevel,structuredOutputSchema:t.schemaOut}}function o$(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function s$(e,t){return e.startsWith(`/`)?lt(e):lt(`${t.length>0?t:`/`}/${e}`)}function c$(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function l$(e){return e==null?`
|
|
5697
5697
|
`:e.replace(/\n+$/,``)+`
|
|
5698
|
-
`}function
|
|
5699
|
-
`}function
|
|
5698
|
+
`}function u$(e){return e==null||e===``?``:e.replace(/\n+$/,``)+`
|
|
5699
|
+
`}function d$(){let e=globalThis.__slicc_agent;if(!(!e||typeof e.spawn!=`function`))return e}function f$(e,t,n){return t?`agent: cwd not found: ${n}\n`:e&&!e.isDirectory?`agent: cwd not a directory: ${n}\n`:null}function p$(e,t,n){let r=e;return typeof r.canWrite==`function`&&!r.canWrite(t)?`agent: cwd not writable: ${n}\n`:null}function m$(e,t,n,r,i,a){let o={cwd:t,allowedCommands:n,prompt:r};e.modelId!==void 0&&(o.modelId=e.modelId),e.visiblePaths!==void 0&&(o.visiblePaths=e.visiblePaths),e.thinkingLevel!==void 0&&(o.thinkingLevel=e.thinkingLevel),e.structuredOutputSchema!==void 0&&(o.structuredOutputSchema=e.structuredOutputSchema),i.cwd&&i.cwd.length>0&&(o.invokingCwd=i.cwd);let s=a?.();return s!==void 0&&s.length>0&&(o.parentJid=s),o}function h$(e={}){let{getParentJid:t}=e;return B(`agent`,async(e,n)=>{let r=a$(e);if(r.help)return{stdout:`usage: agent <cwd> <allowed-commands> <prompt>
|
|
5700
5700
|
|
|
5701
5701
|
Spawns a sub-scoop, feeds it a task, blocks until the agent loop completes,
|
|
5702
5702
|
then prints the scoop's final message on stdout.
|
|
@@ -5742,13 +5742,13 @@ Examples:
|
|
|
5742
5742
|
agent --thinking high . "*" "design a careful plan first"
|
|
5743
5743
|
agent --read-only /workspace/,/shared/assets/ . "*" "review the docs"
|
|
5744
5744
|
`,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let i=r.cwd??``;if(i===``)return{stdout:``,stderr:`agent: <cwd> must not be empty
|
|
5745
|
-
`,exitCode:1};let a=
|
|
5746
|
-
`,exitCode:1}})}async function
|
|
5747
|
-
`,
|
|
5745
|
+
`,exitCode:1};let a=s$(i,n.cwd),o=c$(r.allowedCommandsRaw??``),s=r.prompt??``,c=null,l=!1;try{c=await n.fs.stat(a)}catch{l=!0}let u=f$(c,l,i);if(u)return{stdout:``,stderr:u,exitCode:1};let d=p$(n.fs,a,i);if(d)return{stdout:``,stderr:d,exitCode:1};let f=d$();return f?g$(f,m$(r,a,o,s,n,t)):{stdout:``,stderr:`agent: orchestrator bridge not available
|
|
5746
|
+
`,exitCode:1}})}async function g$(e,t){try{let n=await e.spawn(t),r=typeof n?.exitCode==`number`?n.exitCode:0,i=n?.finalText;return r===0?{stdout:l$(i),stderr:``,exitCode:0}:{stdout:``,stderr:u$(i),exitCode:r}}catch(e){let t=e instanceof Error?e.message:String(e);return $Q.error(`agent bridge threw`,e),{stdout:``,stderr:`${t}\n`,exitCode:1}}}const _$=new Set([`js`,`mjs`,`cjs`,`jsx`,`ts`,`mts`,`cts`,`tsx`,`json`,`jsonc`,`css`,`graphql`,`gql`,`html`,`svelte`,`vue`,`astro`,`jsh`,`bsh`]);function v$(e){let t=e.lastIndexOf(`.`);return t<0?!1:_$.has(e.slice(t+1).toLowerCase())}function y$(e){return e.endsWith(`.jsh`)||e.endsWith(`.bsh`)?`${e.slice(0,-4)}.js`:e}const b$=`async function __slicc() {
|
|
5747
|
+
`,x$=new TextEncoder().encode(b$).length;function S$(e){return e.endsWith(`.jsh`)||e.endsWith(`.bsh`)}function C$(e,t){let n=[e];for(;n.length>0;){let e=n.pop();if(!e||typeof e!=`object`)continue;if(Array.isArray(e)){for(let t of e)n.push(t);continue}let r=e,i=r.span;Array.isArray(i)&&i.length===2&&typeof i[0]==`number`&&typeof i[1]==`number`&&(r.span=[Math.max(0,i[0]-t),Math.max(0,i[1]-t)]),typeof r.sourceCode==`string`&&(r.sourceCode=null);for(let e of Object.keys(r))e===`span`||e===`sourceCode`||n.push(r[e])}}function w$(e){let t=(e.endsWith(`
|
|
5748
5748
|
`)?e.slice(0,-1):e).split(`
|
|
5749
5749
|
`);return t.shift(),t.pop(),t.map(e=>e.startsWith(` `)?e.slice(1):e).join(`
|
|
5750
5750
|
`)+`
|
|
5751
|
-
`}function
|
|
5751
|
+
`}function T$(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}const E$=new Set([`check`,`format`]),D$=`2.5.4`,O$=`6.0.0`,k$=Rq,A$=`@biomejs/wasm-web@${D$} @biomejs/js-api@${O$} esbuild-wasm@${k$}`,j$={"@biomejs/wasm-web":`@biomejs/wasm-web@${D$}`,"@biomejs/js-api":`@biomejs/js-api@${O$}`,"esbuild-wasm":`esbuild-wasm@${k$}`},M$=`run: ipk add ${A$} (no network fallback)`,N$=`biome - thin wrapper over the ipk-loaded @biomejs/wasm-web
|
|
5752
5752
|
|
|
5753
5753
|
Usage:
|
|
5754
5754
|
biome <subcommand> [options] [files...]
|
|
@@ -5766,19 +5766,19 @@ Flags:
|
|
|
5766
5766
|
|
|
5767
5767
|
Install:
|
|
5768
5768
|
Inert until the backing packages are installed in node_modules:
|
|
5769
|
-
ipk add ${
|
|
5769
|
+
ipk add ${A$}
|
|
5770
5770
|
All three packages must be present in the VFS \`node_modules\` for
|
|
5771
5771
|
lint/format to run (loading the wasm-web ESM glue also needs the
|
|
5772
5772
|
esbuild-wasm transpiler). There is no bundled binary, no CDN
|
|
5773
5773
|
fallback; a missing package exits non-zero with a clear \`ipk add\` hint.
|
|
5774
|
-
`;function
|
|
5774
|
+
`;function P$(e){let t={subcommand:null,paths:[],write:!1,stdinFilePath:null,showHelp:!1,showVersion:!1};if(e.length===0)return t.showHelp=!0,t;for(let n=0;n<e.length;n++){let r=e[n];if(r===`-h`||r===`--help`){t.showHelp=!0;continue}if(r===`-v`||r===`--version`){t.showVersion=!0;continue}if(t.subcommand===null&&E$.has(r)){t.subcommand=r;continue}if(r===`--write`){t.write=!0;continue}if(r===`--stdin-file-path`){let r=e[n+1];if(typeof r!=`string`||r.startsWith(`-`))throw Error(`biome: --stdin-file-path requires a value`);t.stdinFilePath=r,n+=1;continue}if(r.startsWith(`--stdin-file-path=`)){t.stdinFilePath=r.slice(18);continue}if(r.startsWith(`-`))throw Error(`biome: unknown option: ${r}`);t.paths.push(r)}return t}async function F$(e,t,n){let r=[],i=[];for(let a of n){let n=e.resolvePath(t,a);if(!await e.exists(n)){i.push(a);continue}(await e.stat?.(n))?.isDirectory?await I$(e,n,r):v$(n)&&r.push(n)}return{files:r,missing:i}}async function I$(e,t,n){let r=await e.readdir?.(t)??[];for(let i of r){if(i===`node_modules`||i.startsWith(`.git`))continue;let r=t===`/`?`/${i}`:`${t}/${i}`;(await e.stat?.(r))?.isDirectory?await I$(e,r,n):v$(r)&&n.push(r)}}async function L$(e){let t;try{t=await on(`@biomejs/wasm-web/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;try{let n=await e.reader.readFile(t.path),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}async function R$(e){let t;try{t=await on(`@biomejs/wasm-web/package.json`,e.fromDir,e.reader)}catch{return{ok:!1,missing:`@biomejs/wasm-web`}}if(t.type!==`file`)return{ok:!1,missing:`@biomejs/wasm-web`};try{if((await on(`@biomejs/js-api/web`,e.fromDir,e.reader)).type!==`file`)return{ok:!1,missing:`@biomejs/js-api`}}catch{return{ok:!1,missing:`@biomejs/js-api`}}try{if((await on(`esbuild-wasm/package.json`,e.fromDir,e.reader)).type!==`file`)return{ok:!1,missing:`esbuild-wasm`}}catch{return{ok:!1,missing:`esbuild-wasm`}}return{ok:!0,wasmPkgDir:ct(t.path).dir}}const z$=`
|
|
5775
5775
|
const fs = require('fs');
|
|
5776
|
-
const JSH_WRAP_PREFIX = ${JSON.stringify(
|
|
5776
|
+
const JSH_WRAP_PREFIX = ${JSON.stringify(b$)};
|
|
5777
5777
|
const JSH_WRAP_SUFFIX = ${JSON.stringify(`
|
|
5778
5778
|
}`)};
|
|
5779
|
-
const JSH_WRAP_PREFIX_BYTES = ${
|
|
5780
|
-
const shiftBiomeSpans = ${
|
|
5781
|
-
const unwrapFormattedJsh = ${
|
|
5779
|
+
const JSH_WRAP_PREFIX_BYTES = ${x$};
|
|
5780
|
+
const shiftBiomeSpans = ${C$.toString()};
|
|
5781
|
+
const unwrapFormattedJsh = ${w$.toString()};
|
|
5782
5782
|
async function compileBiomeWasm(wasmPath) {
|
|
5783
5783
|
// Prefer the host-side WASM compiler: biome's ~37 MB wasm hard-OOMs
|
|
5784
5784
|
// WebAssembly.compile inside this per-task realm worker, so the kernel
|
|
@@ -5883,9 +5883,9 @@ async function main() {
|
|
|
5883
5883
|
process.stdout.write(JSON.stringify(results));
|
|
5884
5884
|
}
|
|
5885
5885
|
main().catch((err) => { process.stderr.write(String(err && err.message || err) + '\\n'); process.exit(1); });
|
|
5886
|
-
`;function
|
|
5887
|
-
`,exitCode:2};let n=await
|
|
5888
|
-
`,exitCode:2};let i=await
|
|
5886
|
+
`;function B$(e){let t=e.match(/Cannot find module '(@biomejs\/[^']+)'/);if(!t)return null;let n=t[1].split(`/`).slice(0,2).join(`/`);return`biome: ${n} is not installed (run: ipk add ${n}); ${M$}\n`}async function V$(e,t,n,r,i){let a={op:t,write:n,files:r.map(e=>({path:e.path,biomePath:y$(e.path),source:e.source,wrap:S$(e.path)}))},o=[`node`,`[biome-helper]`,JSON.stringify(a),i],s=await oZ(z$,o,e,void 0,{filename:`[biome-helper]`});if(s.exitCode!==0)return{results:[],stderr:B$(s.stderr)??s.stderr,exitCode:s.exitCode};try{return{results:JSON.parse(s.stdout),stderr:``,exitCode:0}}catch(e){return{results:[],stderr:`biome: failed to parse helper output: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function H$(e,t){let n=await R$(t);if(!n.ok)return{stdout:``,stderr:`biome: ${n.missing} is not installed (run: ipk add ${j$[n.missing]??n.missing}); ${M$}\n`,exitCode:1};let r=`${n.wasmPkgDir}/biome_wasm_bg.wasm`;return await e.fs.exists(r)?{wasmPath:r}:{stdout:``,stderr:`biome: ${r} not found (reinstall: ipk add ${j$[`@biomejs/wasm-web`]})\n`,exitCode:1}}async function U$(e,t){if(t.paths.length===0&&e.stdin)return{inputs:[{path:t.stdinFilePath??`/stdin.ts`,source:rZ(e.stdin)}],missingErrText:``};if(t.paths.length===0)return{stdout:``,stderr:`biome: no files or directories specified
|
|
5887
|
+
`,exitCode:2};let n=await F$(e.fs,e.cwd,t.paths),r=n.missing.map(e=>`biome: ${e}: no such file or directory\n`).join(``),i=[];for(let t of n.files)i.push({path:t,source:await e.fs.readFile(t)});return i.length===0?{stdout:``,stderr:`${r}biome: no lintable files found\n`,exitCode:+(n.missing.length>0)}:{inputs:i,missingErrText:r}}async function W$(e,t,n,r,i){let a=[],o=[i],s=0,c=0;for(let i of r.results)i.diagnosticsText&&o.push(i.diagnosticsText),s+=i.errorCount,t.write&&i.formatted!==null&&!i.unchanged?(await e.fs.writeFile(i.path,i.formatted),c++):!t.write&&t.subcommand===`format`&&n.length===1&&n[0].path===i.path&&a.push(i.formatted??n[0].source);t.write&&c>0&&o.push(`biome: wrote ${c} file(s)\n`);let l=+(s>0||i.length>0);return{stdout:a.join(``),stderr:o.join(``),exitCode:l}}async function G$(e){let t=await L$(e);return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`biome: @biomejs/wasm-web is not installed (run: ipk add @biomejs/wasm-web@${D$}); ${M$}\n`,exitCode:1}}function K$(){return B(`biome`,async(e,t)=>{let n;try{n=P$(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}if(n.showHelp)return{stdout:N$,stderr:``,exitCode:0};let r=T$(t);if(n.showVersion)return G$(r);if(n.subcommand===null)return{stdout:``,stderr:`biome: missing subcommand (expected check or format)
|
|
5888
|
+
`,exitCode:2};let i=await H$(t,r);if(`exitCode`in i)return i;let a=await U$(t,n);if(`exitCode`in a)return a;let o=await V$(t,n.subcommand,n.write,a.inputs,i.wasmPath);return o.exitCode===0?W$(t,n,a.inputs,o,a.missingErrText):{stdout:``,stderr:a.missingErrText+o.stderr,exitCode:o.exitCode}})}r(`tray-sync`);const q$=r(`scoops.tray-leave`);function J$(){let e=globalThis.localStorage,t=e&&typeof e.setItem==`function`&&typeof e.removeItem==`function`?e:null;return typeof window<`u`&&typeof window.dispatchEvent==`function`?{wire:{kind:`standalone-page`,dispatchEvent:e=>window.dispatchEvent(e)},storage:t}:{wire:null,storage:t}}async function Y$(e={},t=J$()){let n=e.workerBaseUrl??null;if(t.storage)try{t.storage.removeItem(Ge),n===null?t.storage.removeItem(Ke):t.storage.setItem(Ke,n)}catch(t){q$.error(`tray-leave storage write failed`,{workerBaseUrl:n,requestId:e.requestId,error:t instanceof Error?t.message:String(t)})}if(!t.wire)throw Error(`leaveTray: no transport available — inject a panelRpcClient (worker) or run in a context with window`);switch(t.wire.kind){case`standalone-worker`:await t.wire.panelRpcClient.call(`tray-leave`,{workerBaseUrl:n,requestId:e.requestId});return;case`standalone-page`:t.wire.dispatchEvent(new CustomEvent(`slicc:tray-leave`,{detail:{workerBaseUrl:n,requestId:e.requestId}}));return}}const X$=r(`scoops.tray-join`);async function Z$(e,t={},n=J$()){if(n.storage){let r=We(e);try{n.storage.setItem(Ge,r?.joinUrl??e),r&&n.storage.setItem(Ke,r.workerBaseUrl)}catch(e){X$.error(`tray-join storage write failed`,{requestId:t.requestId,error:e instanceof Error?e.message:String(e)})}}if(!n.wire)throw Error(`joinTray: no transport available — inject a panelRpcClient (worker) or run in a context with window`);switch(n.wire.kind){case`standalone-page`:n.wire.dispatchEvent(new CustomEvent(`slicc:tray-join`,{detail:{joinUrl:e,requestId:t.requestId}}));return;case`standalone-worker`:throw Error(`joinTray: standalone-worker transport must be driven via panel-RPC tray-join`)}}function Q$(){return $$()}function $$(){try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayFollowers`);if(e)return JSON.parse(e)}catch{}return[]}function e1(){let e=i();if(e)return async()=>await e.call(`tray-reset`,void 0)}function t1(){return{stdout:`host - display or manage the current tray host status
|
|
5889
5889
|
|
|
5890
5890
|
Usage: host [join <join-url> | reset | leave [--leader <worker-url>]]
|
|
5891
5891
|
|
|
@@ -5896,40 +5896,40 @@ Subcommands:
|
|
|
5896
5896
|
reset Disconnect all followers and create a fresh tray session with a new join URL
|
|
5897
5897
|
leave Leave the current tray (drops follower or stops leader; clears stored URLs)
|
|
5898
5898
|
leave --leader <worker-url> Leave the current role and immediately become a leader on <worker-url>
|
|
5899
|
-
`,stderr:``,exitCode:0}}function
|
|
5900
|
-
`)}\n`}function
|
|
5901
|
-
`)}\n`}function
|
|
5902
|
-
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:
|
|
5899
|
+
`,stderr:``,exitCode:0}}function n1(e){if(e<60)return`${e}s ago`;let t=Math.floor(e/60);if(t<60)return`${t}m ago`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}h ago`:`${n}h ${r}m ago`}function r1(e,t){let n=[`status: ${e.state}`];if(e.session?n.push(`join_url: ${e.session.joinUrl}`):n.push(`join_url: unavailable`),e.error&&n.push(`error: ${e.error}`),e.session&&t.length>0){n.push(`followers:`);for(let e of t){let t=[e.runtimeId];if(e.runtime&&t.push(`(${e.runtime})`),e.connectedAt){let n=Math.round((Date.now()-new Date(e.connectedAt).getTime())/1e3);t.push(`connected ${n1(n)}`)}n.push(` - ${t.join(` `)}`)}}return`${n.join(`
|
|
5900
|
+
`)}\n`}function i1(e){let t=[`status: follower (${e.state})`];if(e.joinUrl&&t.push(`join_url: ${e.joinUrl}`),e.state===`connecting`){if(e.connectingSince!=null){let n=Math.round((Date.now()-e.connectingSince)/1e3);t.push(`connecting_for: ${n1(n).replace(` ago`,``)}`)}e.attachAttempts>0&&t.push(`attach_attempts: ${e.attachAttempts}`),e.lastAttachCode&&t.push(`last_code: ${e.lastAttachCode}`)}if(e.state===`connected`&&e.lastPingTime!=null){let n=Math.round((Date.now()-e.lastPingTime)/1e3);t.push(`last_ping: ${n}s ago`)}return e.state===`reconnecting`&&e.reconnectAttempts>0&&t.push(`reconnect_attempts: ${e.reconnectAttempts}`),e.lastError&&t.push(`last_error: ${e.lastError}`),e.error&&t.push(`error: ${e.error}`),`${t.join(`
|
|
5901
|
+
`)}\n`}function a1(e={}){let t=e.getStatus??Je,n=e.getFollowerStatus??$r,r=e.getFollowers??$$;return B(`host`,async i=>{if(i.includes(`--help`)||i.includes(`-h`))return t1();if(i[0]===`reset`){let r=e.resetTray??void 0??e1();return m1(n,t,r)}if(i[0]===`join`){let t=e.joinTray??l1();return u1(i.slice(1),t)}if(i[0]===`leave`){let r=e.leaveTray??o1();return d1(i.slice(1),t,n,r)}if(i.length>0)return{stdout:``,stderr:`host: unsupported arguments
|
|
5902
|
+
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:r1(t(),r()),stderr:``,exitCode:0}:{stdout:i1(a),stderr:``,exitCode:0}})}function o1(){return async({workerBaseUrl:e,requestId:t})=>{let n=i();if(n)return await n.call(`tray-leave`,{workerBaseUrl:e,requestId:t});let r=Qr(),a=Je(),o=r.state===`inactive`?a.state===`inactive`?`inactive`:`leader`:`follower`;return await Y$({workerBaseUrl:e,requestId:t}),e===null?o===`inactive`?{kind:`noop`}:{kind:`left`,previousMode:o}:{kind:`switched`,previousMode:o,workerBaseUrl:e}}}function s1(){return`host-leave-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function c1(){return`host-join-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function l1(){return async({joinUrl:e,requestId:t})=>{let n=i();if(n){await n.call(`tray-join`,{joinUrl:e,requestId:t});return}await Z$(e,{requestId:t})}}async function u1(e,t){let n;for(let t of e){if(t.startsWith(`-`)||n!==void 0)return{stdout:``,stderr:`host join: unexpected argument: ${t}\n`,exitCode:1};n=t}if(!n)return{stdout:``,stderr:`host join: missing join URL
|
|
5903
5903
|
Usage: host join <join-url>
|
|
5904
5904
|
`,exitCode:1};let r=We(n);if(!r)return{stdout:``,stderr:`host join: invalid join URL: ${n}\nExpected an https://…/join/<token> link from the leader’s "Copy tray join URL".
|
|
5905
|
-
`,exitCode:1};try{return await t({joinUrl:r.joinUrl,requestId:
|
|
5906
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function
|
|
5907
|
-
`,exitCode:0}}try{return{stdout:
|
|
5908
|
-
`,exitCode:1}}}function
|
|
5905
|
+
`,exitCode:1};try{return await t({joinUrl:r.joinUrl,requestId:c1()}),{stdout:`Joining tray as follower: ${r.joinUrl}\nRun \`host\` to check connection status.
|
|
5906
|
+
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function d1(e,t,n,r){let i=null;for(let t=0;t<e.length;t++){let n=e[t];if(n===`--leader`||n===`--as-leader`){let r=e[t+1];if(!r)return{stdout:``,stderr:`host leave: ${n} requires a worker base URL argument\n`,exitCode:1};let a=Ue(r);if(!a)return{stdout:``,stderr:`host leave: invalid worker base URL: ${r}\n`,exitCode:1};i=a,t+=1;continue}return{stdout:``,stderr:`host leave: unexpected argument: ${n}\n`,exitCode:1}}if(i===null){let e=t(),r=n();if(e.state===`inactive`&&r.state===`inactive`)return{stdout:``,stderr:`host leave: no active tray session
|
|
5907
|
+
`,exitCode:0}}try{return{stdout:f1(await r({workerBaseUrl:i,requestId:s1()})),stderr:``,exitCode:0}}catch(e){let t=e instanceof Error?e.message:String(e);return i===null?{stdout:``,stderr:`host leave: ${t}\n`,exitCode:1}:{stdout:``,stderr:`host leave: left the tray, but failed to become leader on ${i}: ${t}\nTray runtime is now dormant.
|
|
5908
|
+
`,exitCode:1}}}function f1(e){switch(e.kind){case`noop`:return`No active tray session.
|
|
5909
5909
|
`;case`left`:{let t=e.previousMode;switch(t){case`leader`:return`Stopped leader. Tray runtime is now dormant.
|
|
5910
5910
|
`;case`follower`:return`Disconnected from leader. Tray runtime is now dormant.
|
|
5911
|
-
`;default:return
|
|
5911
|
+
`;default:return p1(t)}}case`switched`:{let t=e.previousMode;switch(t){case`leader`:return`Stopped leader. Now leader on ${e.workerBaseUrl}\n`;case`follower`:return`Disconnected from leader. Now leader on ${e.workerBaseUrl}\n`;case`inactive`:return`Now leader on ${e.workerBaseUrl}\n`;default:return p1(t)}}default:return p1(e)}}function p1(e){throw Error(`formatLeaveResult: unhandled variant ${JSON.stringify(e)}`)}async function m1(e,t,n){if(e().state!==`inactive`)return{stdout:``,stderr:`host reset: only the leader can reset the tray session
|
|
5912
5912
|
`,exitCode:1};let r=t();if(r.state!==`leader`&&r.state!==`error`)return{stdout:``,stderr:`host reset: no active tray session to reset
|
|
5913
5913
|
`,exitCode:1};if(!n)return{stdout:``,stderr:`host reset: tray reset is not available in this environment
|
|
5914
5914
|
`,exitCode:1};try{return{stdout:`Tray session reset. All followers disconnected.
|
|
5915
|
-
`+
|
|
5915
|
+
`+r1(await n(),[]),stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host reset: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function h1(e={}){let t=e.getFollowers??Q$,n=e.getPanelRpc??i,r=e.getEmitter??(()=>null);return{listRuntimeIds(){return t().filter(e=>e.runtime===`slicc-cherry`).map(e=>e.runtimeId)},async emitSliccEvent(e,t,i){let a=r();if(a)try{return await a(e,t,i)?{delivered:!0}:{delivered:!1,reason:`the follower runtime is not connected to the leader`}}catch(e){return{delivered:!1,reason:`direct emit failed: ${e instanceof Error?e.message:String(e)}`}}let o=n();if(!o)return{delivered:!1,reason:`no page bridge to the leader tray (panel-RPC client)`};try{return(await o.call(`cherry-emit`,{runtimeId:e,name:t,detail:i}))?.delivered?{delivered:!0}:{delivered:!1,reason:`the follower runtime is not connected to the leader`}}catch(e){return{delivered:!1,reason:`panel-RPC delivery failed: ${e instanceof Error?e.message:String(e)}`}}}}}function g1(e){return{stdout:``,stderr:`cherry-emit: ${e}\n`,exitCode:1}}function _1(e){let t={positionals:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r!==`--detail`&&r!==`--runtime`){t.positionals.push(r);continue}let i=e[n+1];if(i===void 0||i.startsWith(`--`))return g1(`${r} requires a value`);r===`--detail`?t.detailJson=i:t.runtime=i,n++}return t}function v1(e,t){return e.length===0?g1(`no cherry follower runtime is connected`):t?e.includes(t)?t:g1(`runtime '${t}' not connected. Available: ${e.join(`, `)}`):e.length>1?g1(`multiple runtimes connected, pass --runtime <id>. Available: ${e.join(`, `)}`):e[0]}function y1(e){if(e===void 0)return{detail:void 0};try{return{detail:JSON.parse(e)}}catch{return g1(`--detail must be valid JSON`)}}function b1(e={}){let t=e.registry??h1();return B(`cherry-emit`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`cherry-emit - push a slicc.event to a cherry host page through a follower runtime
|
|
5916
5916
|
|
|
5917
5917
|
Usage: cherry-emit <name> [--detail <json>] [--runtime <id>]
|
|
5918
5918
|
|
|
5919
5919
|
--detail <json> JSON payload delivered as the event detail
|
|
5920
5920
|
--runtime <id> Target a specific follower runtime (canonical id, e.g. follower-abc).
|
|
5921
5921
|
Defaults to the sole connected runtime; required when more than one.
|
|
5922
|
-
`,stderr:``,exitCode:0};let n=
|
|
5922
|
+
`,stderr:``,exitCode:0};let n=_1(e);if(`exitCode`in n)return n;let r=n.positionals[0];if(!r)return g1(`event name is required`);let i=v1(t.listRuntimeIds(),n.runtime);if(typeof i!=`string`)return i;let a=y1(n.detailJson);if(`exitCode`in a)return a;let o=await t.emitSliccEvent(i,r,a.detail);return o.delivered?{stdout:`cherry-emit: sent '${r}' to ${i}\n`,stderr:``,exitCode:0}:g1(`failed to deliver '${r}' to ${i}: ${o.reason}`)})}function x1(e){return e instanceof Error?e.message:String(e)}function S1(){return{stdout:`usage: pbcopy
|
|
5923
5923
|
|
|
5924
5924
|
Copy stdin to the clipboard.
|
|
5925
5925
|
Example: echo hello | pbcopy
|
|
5926
|
-
`,stderr:``,exitCode:0}}function
|
|
5926
|
+
`,stderr:``,exitCode:0}}function C1(){return{stdout:`usage: pbpaste
|
|
5927
5927
|
|
|
5928
5928
|
Paste clipboard contents to stdout.
|
|
5929
|
-
`,stderr:``,exitCode:0}}function
|
|
5929
|
+
`,stderr:``,exitCode:0}}function w1(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
|
|
5930
5930
|
-o Force paste mode (write to stdout)
|
|
5931
5931
|
(default) Auto-detect: stdin present = copy, no stdin = paste
|
|
5932
|
-
Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function
|
|
5932
|
+
Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function T1(e,t){let n=!!globalThis.navigator?.clipboard,r=n?null:i();if(!n&&!r)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return n?await navigator.clipboard.writeText(e):await r.call(`clipboard-write-text`,{text:e}),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${x1(e)}\n`,exitCode:1}}}async function E1(e){let t=!!globalThis.navigator?.clipboard,n=t?null:i();if(!t&&!n)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:t?await navigator.clipboard.readText():(await n.call(`clipboard-read-text`,void 0)).text,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${x1(t)}\n`,exitCode:1}}}function D1(){return B(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?S1():T1(rZ(t.stdin),`pbcopy`))}function O1(){return B(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?C1():E1(`pbpaste`))}function k1(e){return B(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return w1(e);let r=t.includes(`-i`),i=t.includes(`-o`);if(r&&i)return{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1};if(i)return E1(e);let a=rZ(n.stdin);return r||a.length>0?T1(a,e):E1(e)})}function A1(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}function j1(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`JPEG`:t.endsWith(`.png`)?`PNG`:t.endsWith(`.gif`)?`GIF`:t.endsWith(`.webp`)?`WEBP`:t.endsWith(`.bmp`)?`BMP`:t.endsWith(`.tiff`)||t.endsWith(`.tif`)?`TIFF`:t.endsWith(`.avif`)?`AVIF`:`PNG`}function M1(){return{stdout:`usage: convert [input] [operations...] [output]
|
|
5933
5933
|
|
|
5934
5934
|
Operations:
|
|
5935
5935
|
-resize WxH resize to width x height
|
|
@@ -5944,7 +5944,7 @@ Examples:
|
|
|
5944
5944
|
convert photo.png -resize 50% smaller.png
|
|
5945
5945
|
convert image.jpg -rotate 90 -quality 85 rotated.jpg
|
|
5946
5946
|
convert input.png -crop 100x100+50+50 cropped.png
|
|
5947
|
-
`,stderr:``,exitCode:0}}const
|
|
5947
|
+
`,stderr:``,exitCode:0}}const N1=new Set([`-resize`,`-rotate`,`-crop`,`-quality`]);function P1(e){let t=[],n=[],r=0;for(;r<e.length;){let i=e[r];if(N1.has(i)){if(r+1>=e.length||e[r+1].startsWith(`-`))throw Error(`missing argument for ${i}`);let t=i.slice(1);n.push({type:t,value:e[r+1]}),r+=2;continue}if(i.startsWith(`-`))throw Error(`unsupported option ${i}`);t.push(i),r+=1}if(t.length!==2)throw Error(`expected exactly one input file and one output file`);return{operations:n,positional:t}}function F1(e,t,n){let r=n.match(/^(\d+)%$/);if(r){let e=parseInt(r[1],10),n=Math.round(t.width*e/100),i=Math.round(t.height*e/100);t.resize(n,i);return}let i=n.endsWith(`!`),a=(i?n.slice(0,-1):n).split(`x`);if(a.length!==2)throw Error(`Invalid resize format: ${n}`);let o=parseInt(a[0],10),s=parseInt(a[1],10);if(i){let n=new e.MagickGeometry(o,s);n.ignoreAspectRatio=!0,t.resize(n)}else t.resize(o,s)}function I1(e,t){let n=parseFloat(t);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t}`);e.rotate(n)}function L1(e,t,n){if(!n.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${n} (expected WxH+X+Y)`);let r=new e.MagickGeometry(n);t.crop(r)}function R1(e,t){let n=parseInt(t,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t} (must be 0-100)`);e.quality=n}function z1(e,t,n){switch(n.type){case`resize`:F1(e,t,n.value);return;case`rotate`:I1(t,n.value);return;case`crop`:L1(e,t,n.value);return;case`quality`:R1(t,n.value);return}}async function B1(e,t,n,r){for(let r of n)z1(e,t,r);let i=null,a=j1(r);return t.write(a,e=>{i=new Uint8Array(e)}),i}function V1(e=`convert`){return B(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return M1();let r;try{r=P1(t)}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}let[i,a]=r.positional;try{let e=n.fs.resolvePath(n.cwd,i),t=await n.fs.readFileBuffer(e),o=await Nn({ipk:A1(n)}),s=null;if(await o.ImageMagick.read(t,async e=>{s=await B1(o,e,r.operations,a)}),!s||s.byteLength===0)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,a);return await n.fs.writeFile(c,s),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function H1(){return{stdout:`usage: crontask <command> [options]
|
|
5948
5948
|
|
|
5949
5949
|
Commands:
|
|
5950
5950
|
create [options] Create a new cron task
|
|
@@ -5976,14 +5976,14 @@ Examples:
|
|
|
5976
5976
|
crontask create --name every-5min --scoop poller --cron "*/5 * * * *" --filter "() => ({ time: Date.now() })"
|
|
5977
5977
|
crontask list
|
|
5978
5978
|
crontask delete abc123
|
|
5979
|
-
`,stderr:``,exitCode:0}}function
|
|
5979
|
+
`,stderr:``,exitCode:0}}function U1(){return globalThis.__slicc_lickManager??null}let W1=null;async function G1(){if(W1)return W1;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return W1=e(),W1}async function K1(e,t,n){let r={method:e,headers:b({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(y(`/api/crontasks${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}async function q1(e){let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
|
|
5980
5980
|
`,exitCode:1};if(!n)return{stdout:``,stderr:`crontask: --cron is required
|
|
5981
5981
|
`,exitCode:1};if(!D()){if(r)return{stdout:``,stderr:`crontask: --filter is not supported in extension mode (CSP restriction)
|
|
5982
|
-
`,exitCode:1};let e=
|
|
5982
|
+
`,exitCode:1};let e=U1(),a=e?await e.createCronTask(t,n,i):await(await G1()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await K1(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}function J1(e){let t=`Active cron tasks:
|
|
5983
5983
|
`;for(let n of e)t+=` ${n.id} ${n.name.padEnd(20)} ${n.cron.padEnd(15)}`,n.scoop&&(t+=` -> ${n.scoop}`),n.filter&&(t+=` [filtered]`),t+=` (${n.status})`,n.nextRun&&(t+=` next: ${new Date(n.nextRun).toLocaleString()}`),t+=`
|
|
5984
|
-
`;return t}async function
|
|
5985
|
-
`,stderr:``,exitCode:0}:{stdout:
|
|
5986
|
-
`,stderr:``,exitCode:0}:{stdout:
|
|
5984
|
+
`;return t}async function Y1(){if(!D()){let e=U1(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return e()})();return t.length===0?{stdout:`No active cron tasks
|
|
5985
|
+
`,stderr:``,exitCode:0}:{stdout:J1(t),stderr:``,exitCode:0}}let{ok:e,data:t}=await K1(`GET`,``);if(!e)return{stdout:``,stderr:`crontask: failed to list: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;return n.length===0?{stdout:`No active cron tasks
|
|
5986
|
+
`,stderr:``,exitCode:0}:{stdout:J1(n),stderr:``,exitCode:0}}async function X1(e){let t=e[0],n=e[1];if(!n)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(!D()){let e=U1();return(e?await e.deleteCronTask(n):await(await G1()).deleteCronTask(n))?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}}let{ok:r,status:i,data:a}=await K1(`DELETE`,`/${n}`);return r?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:i===404?{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${a.error??`unknown error`}\n`,exitCode:1}}function Z1(){return B(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return H1();let t=e[0];try{switch(t){case`create`:return await q1(e);case`list`:return await Y1();case`delete`:case`kill`:return await X1(e);default:return{stdout:``,stderr:`crontask: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const Q1=`slicc-fs`;async function $1(){try{let e=globalThis.indexedDB;if(!e)return!1;let t=e.databases;return typeof t!=`function`||(await t.call(e)).some(e=>e.name===Q1)}catch{return!0}}async function e0(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(Q1)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function t0(){if(!await $1())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await e0();return e===`deleted`?{kind:`deleted`,message:`legacy slicc-fs IDB deleted`}:e===`blocked`?{kind:`blocked`,message:`legacy slicc-fs IDB delete blocked by another connection — close other tabs and retry`}:{kind:`error`,message:`legacy slicc-fs IDB delete failed`}}function n0(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
5987
5987
|
|
|
5988
5988
|
Usage:
|
|
5989
5989
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -5992,7 +5992,7 @@ Usage:
|
|
|
5992
5992
|
SLICC's filesystem lives in OPFS; the legacy slicc-fs IndexedDB from
|
|
5993
5993
|
the pre-OPFS era is never read anymore. This command deletes it on
|
|
5994
5994
|
explicit invocation to reclaim the space.
|
|
5995
|
-
`}const
|
|
5995
|
+
`}const r0={deleted:0,absent:0,blocked:1,error:1};function i0(e={}){let t=e.runCleanup??t0;return B(`slicc-fs-cleanup`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:n0(),stderr:``,exitCode:0};if(e.length>0)return{stdout:``,stderr:`slicc-fs-cleanup: unsupported argument: ${e[0]}\n`,exitCode:1};let n=await t(),r=r0[n.kind];return r===0?{stdout:`${n.message}\n`,stderr:``,exitCode:r}:{stdout:``,stderr:`slicc-fs-cleanup: ${n.message}\n`,exitCode:r}})}function a0(e){return`${e} — report VFS backend and storage usage/quota
|
|
5996
5996
|
|
|
5997
5997
|
Usage:
|
|
5998
5998
|
${e} Show diagnostics (raw bytes).
|
|
@@ -6000,16 +6000,16 @@ Usage:
|
|
|
6000
6000
|
${e} --help Show this help.
|
|
6001
6001
|
|
|
6002
6002
|
Read-only. Cleanup of the legacy IndexedDB lives in 'slicc-fs-cleanup'.
|
|
6003
|
-
`}function
|
|
6003
|
+
`}function o0(){return`diskutil — VFS diagnostics alias
|
|
6004
6004
|
|
|
6005
6005
|
Usage:
|
|
6006
6006
|
diskutil info Show VFS diagnostics (alias for 'df -h').
|
|
6007
6007
|
diskutil --help Show this help.
|
|
6008
6008
|
|
|
6009
6009
|
Read-only. See 'df --help' for the underlying command.
|
|
6010
|
-
`}function
|
|
6011
|
-
`)}\n`}function
|
|
6012
|
-
`,exitCode:1}})}const
|
|
6010
|
+
`}function s0(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`,`PB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=100?n.toFixed(0):n>=10?n.toFixed(1):n.toFixed(2)} ${t[r]}`}function c0(e,t){return e===null?`unavailable`:t?s0(e):`${e}`}async function l0(e){let t=e.fs?.backend??`unknown`,n=null,r=null,i=null,a=globalThis.navigator?.storage;if(a){try{let e=await a.estimate();n=typeof e.usage==`number`?e.usage:null,r=typeof e.quota==`number`?e.quota:null}catch{}if(typeof a.persisted==`function`)try{i=await a.persisted()}catch{i=null}}let o=null,s=e.legacyIdbExists??$1;try{o=await s()}catch{o=null}return{backend:t,usage:n,quota:r,persisted:i,legacyIdbPresent:o}}function u0(e,t){let n=e.usage!==null&&e.quota!==null&&e.quota>0?`${Math.round(e.usage/e.quota*100)}%`:`unavailable`,r=e.persisted===null?`unavailable`:e.persisted?`true`:`false`,i=e.legacyIdbPresent===null?`unavailable`:e.legacyIdbPresent?`present (slicc-fs)`:`absent`;return`${[`Backend: ${e.backend}`,`Usage: ${c0(e.usage,t)}`,`Quota: ${c0(e.quota,t)}`,`Used: ${n}`,`Persisted: ${r}`,`Legacy IDB: ${i}`].join(`
|
|
6011
|
+
`)}\n`}function d0(e={}){return B(`df`,async t=>{if(t.includes(`--help`))return{stdout:a0(`df`),stderr:``,exitCode:0};let n=new Set([`-h`,`--human-readable`]),r=t.find(e=>!n.has(e));if(r!==void 0)return{stdout:``,stderr:`df: unsupported argument: ${r}\n`,exitCode:1};let i=t.includes(`-h`)||t.includes(`--human-readable`);return{stdout:u0(await l0(e),i),stderr:``,exitCode:0}})}function f0(e={}){return B(`diskutil`,async t=>{if(t.includes(`--help`))return{stdout:o0(),stderr:``,exitCode:0};let n=t[0];return n===`info`?{stdout:u0(await l0(e),!0),stderr:``,exitCode:0}:{stdout:``,stderr:n?`diskutil: unsupported subcommand: ${n} (try 'diskutil info')\n`:`diskutil: missing subcommand (try 'diskutil info')
|
|
6012
|
+
`,exitCode:1}})}const p0=r(`di`),m0=new WeakMap;async function h0(e,t){let n=m0.get(e);if(n)return n;let r;if(await e.exists(`/workspace/node_modules/pyodide/pyodide-lock.json`))try{r=await e.readFile(`/workspace/node_modules/pyodide/pyodide-lock.json`)}catch(e){return p0.error(`failed to read pyodide-lock.json`,e),null}else{let e=`${Iz}pyodide-lock.json`,n;try{n=await t(e,{method:`GET`,headers:{Accept:`application/json`},timeoutMs:3e4})}catch(e){return p0.error(`failed to fetch pyodide-lock.json from CDN`,e),null}if(n.status<200||n.status>=300)return p0.error(`pyodide-lock.json CDN fetch returned HTTP ${n.status}`),null;r=de(n.body)}let i;try{i=JSON.parse(r)}catch(e){return p0.error(`pyodide-lock.json was not valid JSON`,e),null}let a=new Map;for(let[e,t]of Object.entries(i.packages??{}))!t||typeof t.file_name!=`string`||a.set(FR(t.name??e),t);return m0.set(e,a),a}async function g0(e,t,n,r){let i=await h0(e,t);if(!i)return null;let a=i.get(FR(n));if(!a?.file_name||!a.version||!a.sha256)return null;if(r&&r!==a.version)throw Error(`di: ${n}==${r} requested but the Pyodide lockfile pins ${a.name??n}==${a.version} (the Pyodide CDN serves only the locked version — omit the version, or use real uv locally)`);return{name:a.name??n,version:a.version,source:`pyodide-cdn`,fileName:a.file_name,sha256:a.sha256,url:`${Iz}${a.file_name}`}}function _0(e,t){let n=`https://pypi.org/pypi/${encodeURIComponent(e)}`;return t?`${n}/${encodeURIComponent(t)}/json`:`${n}/json`}function v0(e){if(!e.endsWith(`.whl`))return null;let t=e.slice(0,-4).split(`-`);return t.length<3?null:t[t.length-1]}async function y0(e,t,n){let r=`di: PyPI lookup for ${t}${n?`==${n}`:``}`,i=_0(t,n),a;try{a=await e(i,{method:`GET`,headers:{Accept:`application/json`},timeoutMs:3e4})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`${r}: network error (${t})`)}if(a.status===404)throw Error(`di: package '${t}'${n?` version '${n}'`:``} not found on PyPI`);if(a.status<200||a.status>=300){let e=a.statusText?` ${a.statusText}`:``;throw Error(`${r} returned HTTP ${a.status}${e}`)}let o;try{o=JSON.parse(de(a.body))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`${r}: response was not valid JSON (${t})`)}let s=o.info?.name??t,c=o.info?.version??n;if(!c)throw Error(`${r}: PyPI did not report a version for '${t}'`);let l=(o.urls??[]).filter(e=>e.packagetype===`bdist_wheel`&&typeof e.filename==`string`&&typeof e.url==`string`);if(l.length===0)throw Error(`di: ${s}==${c} has no wheel on PyPI (sdist/source-only packages are not supported in SLICC's di subset — use real uv locally)`);let u=l.find(e=>v0(e.filename)===`any`);if(!u){let e=l.map(e=>e.filename).join(`, `);throw Error(`di: ${s}==${c} only ships platform-specific wheels (${e}); SLICC's di subset installs pure-Python (none-any) wheels only — use real uv locally for compiled packages`)}let d=u.digests?.sha256;if(!d)throw Error(`di: PyPI did not provide a sha256 digest for ${u.filename}`);return{name:s,version:c,source:`pypi`,fileName:u.filename,sha256:d,url:u.url}}const b0=`/workspace/python_wheels`,x0=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function S0(e){let t=e.trim();if(!t)throw Error(`di: package spec is required`);let n=t,r,i=t.indexOf(`==`);if(i!==-1)n=t.slice(0,i),r=t.slice(i+2);else{let e=t.indexOf(`@`);e!==-1&&(n=t.slice(0,e),r=t.slice(e+1))}if(n=n.trim(),r=r?.trim(),!x0.test(n))throw Error(`di: invalid package name '${n}'`);if(r!==void 0&&r===``)throw Error(`di: empty version in spec '${e}'`);return{name:n,version:r}}function C0(e){return e instanceof Error?e:Error(String(e))}async function w0(e,t,n){return await g0(e,t,n.name,n.version)||y0(t,n.name,n.version)}async function T0(e,t,n){let r=await w0(e,t,n),i=await jR(t,{url:r.url,sha256:r.sha256,label:`di: download ${r.name}==${r.version}`});await e.mkdir(b0,{recursive:!0});let a=ut(b0,r.fileName),o=!0;if(await e.exists(a)){let t=await TR(await e.readFile(a,{encoding:`binary`}));if(t===r.sha256.toLowerCase())o=!1;else throw Error(`di: ${r.fileName} is already staged with different bytes (sha256 ${t} != ${r.sha256.toLowerCase()}); refusing to overwrite`)}else await e.writeFile(a,i);return{name:r.name,version:r.version,source:r.source,fileName:r.fileName,sha256:r.sha256,staged:o}}async function E0(e,t,n,r){let i=await zR(e,n),a=[],o=[];for(let n of r){let r;try{r=S0(n)}catch(e){o.push({spec:n,error:C0(e)});continue}try{a.push(await T0(e,t,r))}catch(e){o.push({spec:n,error:C0(e)})}}if(a.length>0){let t=await tz(e,i),n=t.dependencies,r=await rz(e,i);for(let e of a)n=$R(n,e.name,e.version),r=ez(r,{name:e.name,version:e.version,source:e.source,fileName:e.fileName,sha256:e.sha256});await nz(e,i,{...t,dependencies:n}),await iz(e,i,r)}return{results:a,errors:o,manifestDir:i}}async function D0(e,t){let n=await RR(e,t);if(!n)return null;let r=await tz(e,n),i=await rz(e,n),a=new Map(i.map(e=>[FR(e.name),e]));return r.dependencies.map(e=>{let{name:t,version:n}=LR(e),r=a.get(FR(t));return{name:t,version:n||r?.version||`?`,source:r?.source??`unknown`}})}function O0(e){return`${e} - minimal Python package manager (pure-Python + Pyodide wheels)
|
|
6013
6013
|
|
|
6014
6014
|
Usage:
|
|
6015
6015
|
${e} add <pkg>[@<version>] [<pkg> ...] resolve, stage, and record wheels
|
|
@@ -6022,27 +6022,27 @@ Resolution:
|
|
|
6022
6022
|
staged under /workspace/python_wheels/ and recorded in pyproject.toml + uv.lock.
|
|
6023
6023
|
|
|
6024
6024
|
Anything else is not implemented in SLICC's ${e} subset; use real uv locally.
|
|
6025
|
-
`}function
|
|
6026
|
-
`)}\n`}async function
|
|
6025
|
+
`}function k0(e,t){return{stdout:``,stderr:`${e}: '${t}' is not implemented in SLICC's di/uv subset; use real uv locally. Run '${e} --help' for supported verbs.\n`,exitCode:1}}function A0(e){return e instanceof Error?e.message:String(e)}function j0(e){let t=Math.max(4,...e.map(e=>e.name.length)),n=Math.max(7,...e.map(e=>e.version.length));return`${e.map(e=>`${e.name.padEnd(t)} ${e.version.padEnd(n)} (${e.source})`).join(`
|
|
6026
|
+
`)}\n`}async function M0(e,t,n,r){let i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return{stdout:``,stderr:`${e}: add requires at least one package\n`,exitCode:1};let a;try{a=await E0(r.fs,r.fetch,n.cwd,i)}catch(t){return{stdout:``,stderr:`${e}: ${A0(t)}\n`,exitCode:1}}let o=a.results.map(t=>t.staged?`${e}: added ${t.name}==${t.version} (${t.source}) -> ${t.fileName}`:`${e}: ${t.name}==${t.version} already staged (${t.source})`),s=a.errors.map(t=>`${e}: failed to add ${t.spec}: ${A0(t.error)}`);return{stdout:o.length>0?`${o.join(`
|
|
6027
6027
|
`)}\n`:``,stderr:s.length>0?`${s.join(`
|
|
6028
|
-
`)}\n`:``,exitCode:a.errors.length===0?0:1}}async function
|
|
6028
|
+
`)}\n`:``,exitCode:a.errors.length===0?0:1}}async function N0(e,t,n){let r=await D0(n.fs,t.cwd);return r===null?{stdout:``,stderr:`${e}: no pyproject.toml found (run '${e} add <pkg>' first)\n`,exitCode:0}:r.length===0?{stdout:`${e}: no dependencies recorded\n`,stderr:``,exitCode:0}:{stdout:j0(r),stderr:``,exitCode:0}}function P0(e,t){return B(e,async(n,r)=>{if(n.length===0)return{stdout:O0(e),stderr:`${e}: missing verb\n`,exitCode:1};if(n[0]===`--help`||n[0]===`-h`)return{stdout:O0(e),stderr:``,exitCode:0};let i=n[0],a=n.slice(1);return i===`add`?M0(e,a,r,t):i===`list`?N0(e,r,t):k0(e,i)})}const F0=[`A`,`AAAA`,`MX`,`TXT`,`CNAME`,`NS`,`SOA`,`SRV`,`PTR`,`CAA`],I0={1:`A`,2:`NS`,5:`CNAME`,6:`SOA`,12:`PTR`,15:`MX`,16:`TXT`,28:`AAAA`,33:`SRV`,257:`CAA`},L0={0:`NOERROR`,1:`FORMERR`,2:`SERVFAIL`,3:`NXDOMAIN`,4:`NOTIMP`,5:`REFUSED`};function R0(){return{stdout:`usage: dig <name> [type] [+short] [--json]
|
|
6029
6029
|
|
|
6030
6030
|
Resolve DNS records via Cloudflare DNS-over-HTTPS.
|
|
6031
6031
|
|
|
6032
|
-
Supported types: `+
|
|
6032
|
+
Supported types: `+F0.join(`, `)+` (default: A).
|
|
6033
6033
|
|
|
6034
6034
|
Flags:
|
|
6035
6035
|
+short one answer value per line, no headers
|
|
6036
6036
|
--json raw resolver JSON (pretty-printed)
|
|
6037
6037
|
-h, --help show this help
|
|
6038
|
-
`,stderr:``,exitCode:0}}function
|
|
6038
|
+
`,stderr:``,exitCode:0}}function z0(e){return I0[e]??`TYPE${e}`}function B0(){let e=g();return B(`dig`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return R0();let n=!1,r=!1,i=[];for(let e of t)if(e===`+short`)n=!0;else if(e===`--json`)r=!0;else if(e.startsWith(`--`))return{stdout:``,stderr:`dig: unknown option: ${e}\n`,exitCode:1};else if(e.startsWith(`+`))return{stdout:``,stderr:`dig: unknown option: ${e}\n`,exitCode:1};else i.push(e);if(n&&r)return{stdout:``,stderr:`dig: +short and --json are mutually exclusive
|
|
6039
6039
|
`,exitCode:1};let a=i[0]?.trim();if(!a)return{stdout:``,stderr:`dig: missing domain name
|
|
6040
6040
|
usage: dig <name> [type] [+short] [--json]
|
|
6041
|
-
`,exitCode:1};let o=i[1]?.trim().toUpperCase()??`A`;if(!
|
|
6042
|
-
`,exitCode:1}}if(typeof u.Status==`number`&&u.Status!==0)return{stdout:``,stderr:`dig: ${a}: ${
|
|
6041
|
+
`,exitCode:1};let o=i[1]?.trim().toUpperCase()??`A`;if(!F0.includes(o))return{stdout:``,stderr:`dig: unsupported record type: ${o}\n`,exitCode:1};let s=`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(a)}&type=${o}`,c;try{c=await e(s,{method:`GET`,headers:{Accept:`application/dns-json`}})}catch(e){return{stdout:``,stderr:`dig: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}if(c.status<200||c.status>=300)return{stdout:``,stderr:`dig: lookup failed: ${c.status} ${c.statusText}\n`,exitCode:1};let l=new TextDecoder(`utf-8`).decode(c.body),u;try{u=JSON.parse(l)}catch{return{stdout:``,stderr:`dig: invalid response from resolver
|
|
6042
|
+
`,exitCode:1}}if(typeof u.Status==`number`&&u.Status!==0)return{stdout:``,stderr:`dig: ${a}: ${L0[u.Status]??String(u.Status)}\n`,exitCode:1};if(r)return{stdout:`${JSON.stringify(u,null,2)}\n`,stderr:``,exitCode:0};let d=u.Answer??[];return d.length===0?n?{stdout:``,stderr:``,exitCode:0}:{stdout:`;; no records found
|
|
6043
6043
|
`,stderr:``,exitCode:0}:n?{stdout:`${d.map(e=>e.data).join(`
|
|
6044
|
-
`)}\n`,stderr:``,exitCode:0}:{stdout:`${d.map(e=>`${e.name}\t${e.TTL??0}\tIN\t${
|
|
6045
|
-
`)}\n`,stderr:``,exitCode:0}})}const
|
|
6044
|
+
`)}\n`,stderr:``,exitCode:0}:{stdout:`${d.map(e=>`${e.name}\t${e.TTL??0}\tIN\t${z0(e.type)}\t${e.data}`).join(`
|
|
6045
|
+
`)}\n`,stderr:``,exitCode:0}})}const V0=[`api-catalog`,`service-desc`,`service-meta`,`status`,`https://llmstxt.org/rel/llms-txt`];async function H0(e,t={}){let n=t.fetchImpl??fetch,r=t.timeoutMs??3e3,i={links:e,failures:[]},a=[],o=new Set;for(let s of e)for(let e of s.rel)V0.includes(e)&&(o.has(e)||(o.add(e),a.push(U0(n,s.href,r,t.signal).then(t=>W0(i,e,t)).catch(t=>{i.failures.push({rel:e,href:s.href,error:t instanceof Error?t.message:String(t)})}))));return await Promise.all(a),i}async function U0(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(Error(`timeout`)),n),o=()=>i.abort(Error(`aborted`));r&&r.addEventListener(`abort`,o,{once:!0});try{let n=await e(t,{signal:i.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);return{contentType:n.headers.get(`content-type`)??``,body:await n.text()}}finally{clearTimeout(a),r&&r.removeEventListener(`abort`,o)}}function W0(e,t,n){if(t===`https://llmstxt.org/rel/llms-txt`){e.llmsTxt=n.body;return}let r=n.contentType.includes(`json`)||n.contentType.includes(`linkset`),i=n.body;if(r)try{i=JSON.parse(n.body)}catch{i=n.body}switch(t){case`api-catalog`:e.catalog=i;break;case`service-desc`:e.serviceDesc=i;break;case`service-meta`:e.serviceMeta=i;break;case`status`:e.status=i;break}}function G0(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=u(n?.headers),a=await e(r,{method:n?.method??`GET`,...i?{headers:i}:{}});return new Response(a.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}function K0(){return`discover — fetch a URL and parse RFC 8288 Link headers
|
|
6046
6046
|
|
|
6047
6047
|
Usage:
|
|
6048
6048
|
discover <url> Print parsed links (and any SLICC handoff match)
|
|
@@ -6056,9 +6056,9 @@ Output is always JSON.
|
|
|
6056
6056
|
Examples:
|
|
6057
6057
|
discover ${S}/handoff?handoff=demo
|
|
6058
6058
|
discover --follow ${S}/llms.txt
|
|
6059
|
-
`}function
|
|
6060
|
-
`,exitCode:2};let r=n[0],i=g(),a;try{a=await i(r,{method:`GET`})}catch(e){return{stdout:``,stderr:`discover: fetch failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=[];for(let[e,t]of Object.entries(a.headers))e.toLowerCase()===`link`&&typeof t==`string`&&t.length>0&&o.push(t);let s=et(o,r),c=it(s),l={url:r,status:a.status,links:s,handoff:c};if(t&&s.length>0){let e=await
|
|
6061
|
-
`,stderr:``,exitCode:0}})}function
|
|
6059
|
+
`}function q0(){return B(`discover`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return{stdout:K0(),stderr:``,exitCode:0};let t=e.includes(`--follow`),n=e.filter(e=>!e.startsWith(`-`));if(n.length!==1)return{stdout:``,stderr:`discover: expected exactly one URL argument
|
|
6060
|
+
`,exitCode:2};let r=n[0],i=g(),a;try{a=await i(r,{method:`GET`})}catch(e){return{stdout:``,stderr:`discover: fetch failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=[];for(let[e,t]of Object.entries(a.headers))e.toLowerCase()===`link`&&typeof t==`string`&&t.length>0&&o.push(t);let s=et(o,r),c=it(s),l={url:r,status:a.status,links:s,handoff:c};if(t&&s.length>0){let e=await H0(s,{fetchImpl:G0(i)});l.discovery={catalog:e.catalog,serviceDesc:e.serviceDesc,serviceMeta:e.serviceMeta,status:e.status,llmsTxt:e.llmsTxt,failures:e.failures}}return{stdout:JSON.stringify(l,null,2)+`
|
|
6061
|
+
`,stderr:``,exitCode:0}})}function J0(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}const Y0=`esbuild - thin wrapper over the ipk-loaded esbuild-wasm
|
|
6062
6062
|
|
|
6063
6063
|
Usage:
|
|
6064
6064
|
esbuild [options] <entry> Bundle / transform
|
|
@@ -6098,10 +6098,10 @@ Install:
|
|
|
6098
6098
|
Inert until the backing package is installed:
|
|
6099
6099
|
ipk add esbuild-wasm
|
|
6100
6100
|
Then \`esbuild --version\` and the bundle/transform commands above.
|
|
6101
|
-
`,
|
|
6102
|
-
`,exitCode:2};let r;try{r=await
|
|
6103
|
-
`,exitCode:2};let r=e.entries.map(e=>t.fs.resolvePath(t.cwd,e));for(let e of r)if(!await t.fs.exists(e))return{stdout:``,stderr:`esbuild: ${e}: no such file\n`,exitCode:1};let i={entryPoints:r,bundle:!0,write:!1,plugins:[
|
|
6104
|
-
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=un(n);for(let e=1;e<o.length;e++){let n=o[e],i=gn(r,wn(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await
|
|
6101
|
+
`,X0=new Set([`iife`,`cjs`,`esm`]),Z0=new Set([`browser`,`node`,`neutral`]),Q0=new Set([`linked`,`inline`,`external`,`both`]),$0={"-h":`showHelp`,"--help":`showHelp`,"-v":`showVersion`,"--version":`showVersion`,"--bundle":`bundle`,"--transform":`transform`,"--minify":`minify`};function e2(e){if(e.startsWith(`--`)){let t=e.indexOf(`=`);if(t>0)return{key:e.slice(0,t),inlineValue:e.slice(t+1)}}return{key:e,inlineValue:null}}function t2(e,t,n){if(e.inlineValue!==null)return{value:e.inlineValue,advance:0};let r=t[n+1];if(typeof r!=`string`||r.startsWith(`-`))throw Error(`esbuild: ${e.key} requires a value`);return{value:r,advance:1}}function n2(e,t,n,r){if(t.inlineValue!==null){if(!Q0.has(t.inlineValue))throw Error(`esbuild: --sourcemap value must be one of linked|inline|external|both (got "${t.inlineValue}")`);return e.sourcemap=t.inlineValue,0}let i=n[r+1];return typeof i==`string`&&Q0.has(i)?(e.sourcemap=i,1):(e.sourcemap=!0,0)}function r2(e,t,n,r){if(t.key===`--outfile`){let{value:i,advance:a}=t2(t,n,r);return e.outfile=i,a}if(t.key===`--format`){let{value:i,advance:a}=t2(t,n,r);if(!X0.has(i))throw Error(`esbuild: --format must be one of iife|cjs|esm (got "${i}")`);return e.format=i,a}if(t.key===`--platform`){let{value:i,advance:a}=t2(t,n,r);if(!Z0.has(i))throw Error(`esbuild: --platform must be one of browser|node|neutral (got "${i}")`);return e.platform=i,a}if(t.key===`--target`){let{value:i,advance:a}=t2(t,n,r);return e.target=i.split(`,`).map(e=>e.trim()).filter(Boolean),a}if(t.key===`--loader`){let{value:i,advance:a}=t2(t,n,r);return e.loader=i,a}return-1}function i2(e,t,n){if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf(`=`);if(i<1)throw Error(`esbuild: ${t.slice(0,-1)} requires <key>=<value>`);return n[r.slice(0,i)]=r.slice(i+1),!0}function a2(e){let t={entries:[],bundle:!1,transform:!1,outfile:null,format:null,minify:!1,sourcemap:null,target:null,loader:null,external:[],platform:null,define:{},banner:{},footer:{},treeShaking:null,showHelp:!1,showVersion:!1};for(let n=0;n<e.length;n++){let r=e[n],i=$0[r];if(i){t[i]=!0;continue}if(r.startsWith(`--external:`)){t.external.push(r.slice(11));continue}if(i2(r,`--define:`,t.define)||i2(r,`--banner:`,t.banner)||i2(r,`--footer:`,t.footer))continue;let a=e2(r);if(a.key===`--tree-shaking`){if(a.inlineValue===null)t.treeShaking=!0;else if(a.inlineValue===`true`||a.inlineValue===`false`)t.treeShaking=a.inlineValue===`true`;else throw Error(`esbuild: --tree-shaking must be true or false (got "${a.inlineValue}")`);continue}if(a.key===`--sourcemap`){n+=n2(t,a,e,n);continue}let o=r2(t,a,e,n);if(o>=0){n+=o;continue}if(r.startsWith(`-`))throw Error(`esbuild: unknown option: ${r}`);t.entries.push(r)}return t}function o2(e,t,n,r,i){return{name:`slicc-vfs`,setup(a){a.onResolve({filter:/.*/},async a=>{if(a.kind!==`entry-point`&&s2(a.path,r)||/^[a-z]+:/.test(a.path)&&!a.path.startsWith(`file:`))return{path:a.path,external:!0};if(l2(a.path)){let n=a.importer?.startsWith(`/`)?un(a.importer):t;return{path:await f2(e,e.resolvePath(n,a.path))}}return u2(a.path,a.importer,n,c2(i,a.kind))}),a.onLoad({filter:/.*/},async t=>t.namespace&&t.namespace!==`file`?null:{contents:await e.readFile(t.path),loader:d2(t.path),resolveDir:un(t.path)})}}}function s2(e,t){return t.some(t=>{if(e===t)return!0;if(!t.includes(`*`))return!l2(t)&&e.startsWith(`${t}/`);let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(`*`,`.*`);return RegExp(`^${n}$`).test(e)})}function c2(e,t){let n=t===`require-call`||t===`require-resolve`?`require`:`import`;switch(e??`browser`){case`browser`:return[`browser`,n,`default`];case`node`:return[`node`,n,`default`];case`neutral`:return[n,`default`]}}function l2(e){return e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)}async function u2(e,t,n,r){let i=t?.startsWith(`/`)?un(t):n.fromDir;try{let t=await on(e,i,n.reader,{conditions:r});return t.type===`file`?{path:t.path}:{path:e,external:!0}}catch(e){return{errors:[{text:e instanceof Error?e.message:String(e)}]}}}function d2(e){let t=wn(e).toLowerCase(),n=t.lastIndexOf(`.`);if(n<0)return`js`;switch(t.slice(n+1)){case`ts`:return`ts`;case`tsx`:return`tsx`;case`jsx`:return`jsx`;case`mjs`:case`cjs`:case`js`:return`js`;case`json`:return`json`;case`css`:return`css`;case`txt`:return`text`;default:return`js`}}async function f2(e,t){if(await e.exists(t))try{if(!(await e.stat(t)).isDirectory)return t}catch{return t}let n=[`.ts`,`.tsx`,`.jsx`,`.mjs`,`.cjs`,`.js`,`.json`];for(let r of n){let n=`${t}${r}`;if(await e.exists(n))return n}for(let r of n){let n=gn(t,`index${r}`);if(await e.exists(n))return n}return t}async function p2(e,t,n){let r=[];if(n.length>0){let t=await e(n,{kind:`warning`,color:!1});r.push(t.join(``))}if(t.length>0){let n=await e(t,{kind:`error`,color:!1});r.push(n.join(``))}return r.join(``)}function m2(){return B(`esbuild`,async(e,t)=>{let n;try{n=a2(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}if(n.showHelp||e.length===0&&!t.stdin)return{stdout:Y0,stderr:``,exitCode:0};if(!n.transform&&!n.bundle&&n.entries.length>1)return{stdout:``,stderr:`esbuild: multiple entry points require --bundle (transform mode accepts at most one entry)
|
|
6102
|
+
`,exitCode:2};let r;try{r=await Bq({ipk:J0(t)})}catch(e){return{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return n.showVersion?{stdout:`${r.version}\n`,stderr:``,exitCode:0}:n.transform||!n.bundle&&n.entries.length<=1?h2(n,t,r):g2(n,t,r)})}async function h2(e,t,n){let r,i=`<stdin>`;if(e.entries.length===1){let n=t.fs.resolvePath(t.cwd,e.entries[0]);if(!await t.fs.exists(n))return{stdout:``,stderr:`esbuild: ${e.entries[0]}: no such file\n`,exitCode:1};r=await t.fs.readFile(n),i=n}else if(r=rZ(t.stdin),!r)return{stdout:Y0,stderr:``,exitCode:0};let a={loader:e.loader??d2(i),sourcefile:i,...e.format?{format:e.format}:{},...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{},...e.platform?{platform:e.platform}:{},...Object.keys(e.define).length>0?{define:e.define}:{},...e.treeShaking===null?{}:{treeShaking:e.treeShaking}};try{let i=await n.transform(r,a),o=await p2(n.formatMessages,[],i.warnings);if(e.outfile){let n=t.fs.resolvePath(t.cwd,e.outfile);return await t.fs.writeFile(n,i.code),i.map&&e.sourcemap&&e.sourcemap!==`inline`&&await t.fs.writeFile(`${n}.map`,i.map),{stdout:``,stderr:o,exitCode:0}}return{stdout:i.code,stderr:o,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await p2(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function g2(e,t,n){if(e.entries.length===0)return{stdout:``,stderr:`esbuild: --bundle requires at least one entry point
|
|
6103
|
+
`,exitCode:2};let r=e.entries.map(e=>t.fs.resolvePath(t.cwd,e));for(let e of r)if(!await t.fs.exists(e))return{stdout:``,stderr:`esbuild: ${e}: no such file\n`,exitCode:1};let i={entryPoints:r,bundle:!0,write:!1,plugins:[o2(t.fs,t.cwd,J0(t),e.external,e.platform)],format:e.format??`esm`,..._2(e)};try{let r=await n.build(i),a=await p2(n.formatMessages,r.errors,r.warnings),o=r.outputFiles??[];if(e.outfile){if(o.length===0)return{stdout:``,stderr:`esbuild: build produced no output
|
|
6104
|
+
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=un(n);for(let e=1;e<o.length;e++){let n=o[e],i=gn(r,wn(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await p2(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function _2(e){return{...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{},...e.external.length>0?{external:e.external}:{},...e.platform?{platform:e.platform}:{},...Object.keys(e.define).length>0?{define:e.define}:{},...Object.keys(e.banner).length>0?{banner:e.banner}:{},...Object.keys(e.footer).length>0?{footer:e.footer}:{},...e.treeShaking===null?{}:{treeShaking:e.treeShaking}}}function v2(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var y2=class{ops(){return import(`./esptool-operations-C0DUkD34.js`)}registry(){if(!eY())throw Error(`Web Serial is unavailable in this browser`);return rY()}async chipInfo(e,t,n){return(await this.ops()).esptoolChipInfo(this.registry(),e,t,n)}async readMac(e,t,n){return(await this.ops()).esptoolReadMac(this.registry(),e,t,n)}async eraseFlash(e,t,n){await(await this.ops()).esptoolEraseFlash(this.registry(),e,t,n)}async flash(e,t,n,r,i){await(await this.ops()).esptoolFlash(this.registry(),e,t,n,r,i)}async readFlash(e,t,n,r,i){return(await this.ops()).esptoolReadFlash(this.registry(),e,t,n,r,i)}async readReg(e,t,n,r){return(await this.ops()).esptoolReadReg(this.registry(),e,t,n,r)}async flashId(e,t,n){return(await this.ops()).esptoolFlashId(this.registry(),e,t,n)}async eraseRegion(e,t,n,r,i){await(await this.ops()).esptoolEraseRegion(this.registry(),e,t,n,r,i)}async run(e,t,n){await(await this.ops()).esptoolRun(this.registry(),e,t,n)}},b2=class e{rpc;constructor(e){this.rpc=e}static INFO_TIMEOUT_MS=12e4;static ERASE_TIMEOUT_MS=3e5;static FLASH_TIMEOUT_MS=6e5;async withProgress(e,t,n){let r=this.rpc.onEvent(`esptool-progress`,n=>{let r=n;!r||r.handle!==e||t(r.line)});try{return await n()}finally{r()}}async chipInfo(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-chip-info`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async readMac(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-read-mac`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseFlash(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-erase-flash`,{handle:t,baudRate:n},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async flash(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-flash`,{handle:t,baudRate:n,eraseAll:r,segments:i.map(e=>({address:e.address,bytes:v2(e.data)}))},{timeoutMs:e.FLASH_TIMEOUT_MS}))}async readFlash(t,n,r,i,a){let{bytes:o}=await this.withProgress(t,a,()=>this.rpc.call(`esptool-read-flash`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.FLASH_TIMEOUT_MS}));return new Uint8Array(o)}async readReg(t,n,r,i){return this.withProgress(t,i,()=>this.rpc.call(`esptool-read-reg`,{handle:t,baudRate:n,address:r},{timeoutMs:e.INFO_TIMEOUT_MS}))}async flashId(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-flash-id`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseRegion(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-erase-region`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async run(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-run`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}};function x2(e,t){return e&&eY()?new y2:t?new b2(t):null}const S2=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function C2(e){return zF(e,S2)}function w2(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function T2(e){let t=e.replace(/0x/gi,``).replace(/[\s:,]/g,``);if(t.length===0)return new Uint8Array;if(t.length%2!=0||/[^0-9a-f]/i.test(t))throw Error(`invalid hex string: '${e}'`);let n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function E2(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=w2(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=w2(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const D2=new Set([`none`,`even`,`odd`]),O2=new Set([`none`,`hardware`]);function k2(e){let t={baudRate:e.has(`--baud`)?w2(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=w2(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=w2(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!D2.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!O2.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=w2(e.get(`--buffer-size`),`buffer-size`)),t}function A2(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=w2(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=T2(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=w2(e.get(`--timeout-ms`),`timeout-ms`)),t}function j2(e,t){let n=e.toLowerCase();if(n===`on`||n===`true`||n===`1`)return!0;if(n===`off`||n===`false`||n===`0`)return!1;throw Error(`invalid ${t}: '${e}' (use on/off)`)}function M2(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=j2(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=j2(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=j2(e.get(`--break`),`break`)),t}function N2(e){let t=iZ(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function P2(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function F2(e){return`0x${e.toString(16).padStart(4,`0`)}`}function I2(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${F2(e.usbVendorId??0)}:${F2(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function L2(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function R2(e){return{stdout:e,stderr:``,exitCode:0}}function z2(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const B2=`serial - access serial ports via Web Serial
|
|
6105
6105
|
|
|
6106
6106
|
Usage: serial <subcommand> [options]
|
|
6107
6107
|
|
|
@@ -6120,7 +6120,7 @@ Open flags:
|
|
|
6120
6120
|
--parity none|even|odd --flow-control none|hardware --buffer-size N
|
|
6121
6121
|
|
|
6122
6122
|
Read flags:
|
|
6123
|
-
--bytes N Stop after N bytes (default: ${
|
|
6123
|
+
--bytes N Stop after N bytes (default: ${iY} cap)
|
|
6124
6124
|
--until <hex> Stop once this byte sequence is seen
|
|
6125
6125
|
--timeout-ms N Stop after N ms (default 1000)
|
|
6126
6126
|
--hex Hex-dump the bytes instead of emitting raw
|
|
@@ -6131,10 +6131,10 @@ Signal flags (set):
|
|
|
6131
6131
|
Options:
|
|
6132
6132
|
-h, --help
|
|
6133
6133
|
|
|
6134
|
-
Reads/writes are capped at ${
|
|
6135
|
-
`;function
|
|
6136
|
-
`):
|
|
6137
|
-
`)}\n`)}async function
|
|
6134
|
+
Reads/writes are capped at ${iY} bytes (4 MiB).
|
|
6135
|
+
`;function V2(e,t){if(t)return R2(e.length?`${P2(e)}\n`:``);let n=``;for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return R2(n)}async function H2(e){let t=await e.list();return t.length===0?R2(`no granted serial ports
|
|
6136
|
+
`):R2(`${t.map(I2).join(`
|
|
6137
|
+
`)}\n`)}async function U2(e,t){let n=e.get(`--__resolved`);if(n)return R2(`${I2(await t.info(n))}\n`);let r=E2(e),i=me();if(i){let e=await N(`serial-port`,r,i);if(e.handle)return R2(`${I2(await t.info(e.handle))}\n`);let n=e.info,a=eY();if(!a)return z2(`request: Web Serial unavailable for port re-acquire`);let o=(await a.getPorts()).find(e=>{let t=typeof e.getInfo==`function`?e.getInfo():{};return(n.usbVendorId===void 0||t.usbVendorId===n.usbVendorId)&&(n.usbProductId===void 0||t.usbProductId===n.usbProductId)});if(!o)return z2(`request: granted port could not be re-acquired`);let s=rY(),c=s.register(o),l=s.get(c);return l?R2(`${I2(aY(c,l))}\n`):z2(`request: failed to register granted port`)}return R2(`${I2(await t.request(r))}\n`)}async function W2(e,t,n){let r=e[1];return r?(await n.open(r,k2(t)),R2(``)):z2(`open: handle required`)}async function G2(e,t){let n=e[1];return n?(await t.close(n),R2(``)):z2(`close: handle required`)}async function K2(e,t,n,r){let i=e[1];if(!i)return z2(`read: handle required`);let a=A2(t);return a.maxBytes!==void 0&&a.maxBytes>4194304?z2(`read --bytes exceeds 4 MiB limit`):V2(await r.read(i,a),n.has(`--hex`))}async function q2(e,t,n){let r=e[1];if(!r)return z2(`write: handle required`);let i=N2(t);return i.length>4194304?z2(`write payload exceeds 4 MiB limit`):R2(`${await n.write(r,i)} bytes written\n`)}async function J2(e,t,n){let[,r,i]=e;return!r||!i?z2(`signals: handle and get|set required`):i===`get`?R2(L2(await n.getSignals(r))):i===`set`?(await n.setSignals(r,M2(t)),R2(``)):z2(`signals: unknown action '${i}' (use get|set)`)}async function Y2(e,t,n){let{positionals:r,flags:i,bools:a}=C2(e),o=r[0];switch(o){case`list`:return H2(n);case`request`:return U2(i,n);case`open`:return W2(r,i,n);case`close`:return G2(r,n);case`read`:return K2(r,i,a,n);case`write`:return q2(r,t,n);case`signals`:return J2(r,i,n);default:return z2(`unknown subcommand '${o??``}'. Try 'serial --help'.`)}}function X2(){return B(`serial`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return R2(B2);let n=EY(a(),i());if(!n)return z2(`Web Serial is unavailable in this environment`);try{return await Y2(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No port selected/i.test(t)?z2(`user cancelled or no port selected`):z2(t)}})}const Z2=new Set([`--port`,`--baud`,`--vid`,`--pid`]),Q2=115200;function $2(e){return zF(e,Z2)}function e4(e){let t=e.replace(/-/g,`_`);return t===`chip_info`||t===`id`?`chip_id`:t}function t4(e){return{stdout:e,stderr:``,exitCode:0}}function n4(e){return{stdout:``,stderr:`esptool: ${e}\n`,exitCode:1}}const r4=`esptool - flash ESP32 / ESP8266 chips via esptool-js
|
|
6138
6138
|
|
|
6139
6139
|
Usage: esptool [--port H] [--baud N] <subcommand> [args]
|
|
6140
6140
|
|
|
@@ -6151,27 +6151,27 @@ Subcommands:
|
|
|
6151
6151
|
|
|
6152
6152
|
Options:
|
|
6153
6153
|
--port H Use an existing serial handle from 'serial request'
|
|
6154
|
-
--baud N Flash baud rate (default ${
|
|
6154
|
+
--baud N Flash baud rate (default ${Q2})
|
|
6155
6155
|
--vid 0x.. Picker filter when --port is omitted
|
|
6156
6156
|
--pid 0x.. Picker filter when --port is omitted
|
|
6157
6157
|
--erase write_flash: erase the whole chip before writing
|
|
6158
6158
|
-h, --help
|
|
6159
6159
|
|
|
6160
6160
|
Without --port, the Web Serial picker opens (needs a user gesture).
|
|
6161
|
-
`;async function
|
|
6162
|
-
`)}\n`)}case`read_mac`:{let e=await
|
|
6163
|
-
`)}\n`)}case`erase_flash`:{let e=await
|
|
6161
|
+
`;async function i4(e,t){return e.get(`--port`)||(await t.request(E2(e))).handle}async function a4(e,t){let n=e.slice(1);if(n.length===0||n.length%2!=0)throw Error(`write_flash expects <addr> <file> pairs`);let r=[];for(let e=0;e<n.length;e+=2){let i=w2(n[e],`address`),a=t.fs.resolvePath(t.cwd,n[e+1]),o=await t.fs.readFileBuffer(a);r.push({address:i,data:o})}return r}async function o4(e,t,n,r){let{positionals:i,flags:a,bools:o}=$2(e),s=e4(i[0]??``),c=a.has(`--baud`)?w2(a.get(`--baud`),`baud`):Q2,l=[],u=e=>l.push(e);switch(s){case`chip_id`:{let e=await i4(a,r),t=await n.chipInfo(e,c,u);return l.push(`Chip type: ${t.chip}`),l.push(`Chip description: ${t.description}`),l.push(`Features: ${t.features.join(`, `)}`),l.push(`Crystal: ${t.crystalMHz}MHz`),l.push(`MAC: ${t.mac}`),t4(`${l.join(`
|
|
6162
|
+
`)}\n`)}case`read_mac`:{let e=await i4(a,r),{mac:t}=await n.readMac(e,c,u);return l.push(`MAC: ${t}`),t4(`${l.join(`
|
|
6163
|
+
`)}\n`)}case`erase_flash`:{let e=await i4(a,r);return await n.eraseFlash(e,c,u),t4(l.length?`${l.join(`
|
|
6164
6164
|
`)}\n`:`flash erased
|
|
6165
|
-
`)}case`write_flash`:{let e=await
|
|
6165
|
+
`)}case`write_flash`:{let e=await a4(i,t),s=await i4(a,r);return await n.flash(s,c,o.has(`--erase`),e,u),t4(l.length?`${l.join(`
|
|
6166
6166
|
`)}\n`:`flash written
|
|
6167
|
-
`)}case`read_flash`:{if(i.length<4)return
|
|
6168
|
-
`)}\n`)}case`read_reg`:{if(i.length<2)return
|
|
6169
|
-
`)}\n`)}case`flash_id`:{let e=await
|
|
6170
|
-
`)}\n`)}case`erase_region`:{if(i.length<3)return
|
|
6167
|
+
`)}case`read_flash`:{if(i.length<4)return n4(`read_flash expects <addr> <size> <outfile>`);let e=w2(i[1],`address`),o=w2(i[2],`size`),s=t.fs.resolvePath(t.cwd,i[3]),d=await i4(a,r),f=await n.readFlash(d,c,e,o,u);return await t.fs.writeFile(s,f),l.push(`Wrote ${f.byteLength} bytes to ${s}`),t4(`${l.join(`
|
|
6168
|
+
`)}\n`)}case`read_reg`:{if(i.length<2)return n4(`read_reg expects <addr>`);let e=w2(i[1],`address`),t=await i4(a,r),{value:o}=await n.readReg(t,c,e,u);return l.push(`0x${e.toString(16)} = 0x${(o>>>0).toString(16).padStart(8,`0`)}`),t4(`${l.join(`
|
|
6169
|
+
`)}\n`)}case`flash_id`:{let e=await i4(a,r),t=await n.flashId(e,c,u);return l.push(`Manufacturer: 0x${t.manufacturer.toString(16).padStart(2,`0`)}`),l.push(`Device: 0x${t.device.toString(16).padStart(4,`0`)}`),l.push(`Detected flash size: ${t.flashSize??`unknown`}`),t4(`${l.join(`
|
|
6170
|
+
`)}\n`)}case`erase_region`:{if(i.length<3)return n4(`erase_region expects <addr> <size>`);let e=w2(i[1],`address`),t=w2(i[2],`size`),o=await i4(a,r);return await n.eraseRegion(o,c,e,t,u),t4(l.length?`${l.join(`
|
|
6171
6171
|
`)}\n`:`region erased
|
|
6172
|
-
`)}case`run`:{let e=await
|
|
6172
|
+
`)}case`run`:{let e=await i4(a,r);return await n.run(e,c,u),t4(l.length?`${l.join(`
|
|
6173
6173
|
`)}\n`:`running app
|
|
6174
|
-
`)}default:return
|
|
6174
|
+
`)}default:return n4(`unknown subcommand '${i[0]??``}'. Try 'esptool --help'.`)}}function s4(){return B(`esptool`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return t4(r4);let n=a(),r=i(),o=x2(n,r),s=EY(n,r);if(!o||!s)return n4(`Web Serial is unavailable in this environment`);try{return await o4(e,t,o,s)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No port selected/i.test(t)?n4(`user cancelled or no port selected`):n4(t)}})}function c4(){return ce()}function l4(e){return{bytes:p4(e.bytesBase64),mimeType:e.mimeType??`application/octet-stream`,width:e.width??0,height:e.height??0,...typeof e.durationMs==`number`?{durationMs:e.durationMs}:{}}}async function u4(e,t={}){if(!ce())throw Error(`media capture popup requires the extension runtime`);let n=t.timeoutMs??5*6e4,r=d4(),i=f4(JSON.stringify({...e,requestId:r})),a=chrome.runtime.getURL(`capture-popup.html?req=${i}`);return await new Promise((e,t)=>{let i=!1,o=()=>{if(!i){i=!0,clearTimeout(c);try{chrome.runtime.onMessage.removeListener(s)}catch{}}},s=n=>{let i=n;if(!(i?.source!==`capture-popup`||i.requestId!==r))if(o(),i.ok&&i.bytesBase64!==void 0)try{e(l4(i))}catch(e){t(e instanceof Error?e:Error(String(e)))}else t(Error(i.error||`media capture failed`))},c=setTimeout(()=>{try{chrome.runtime.sendMessage({target:`capture-popup`,type:`capture-abort`,requestId:r})}catch{}o(),t(Error(`media capture timed out waiting for the capture window`))},n);chrome.runtime.onMessage.addListener(s);try{chrome.runtime.sendMessage({type:`capture-open-window`,url:a,requestId:r})}catch(e){o(),t(e instanceof Error?e:Error(String(e)))}})}function d4(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cap-${crypto.randomUUID()}`:`cap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function f4(e){let t=new TextEncoder().encode(e),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function p4(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 m4;(function(e){e.LOAD=`LOAD`,e.EXEC=`EXEC`,e.FFPROBE=`FFPROBE`,e.WRITE_FILE=`WRITE_FILE`,e.READ_FILE=`READ_FILE`,e.DELETE_FILE=`DELETE_FILE`,e.RENAME=`RENAME`,e.CREATE_DIR=`CREATE_DIR`,e.LIST_DIR=`LIST_DIR`,e.DELETE_DIR=`DELETE_DIR`,e.ERROR=`ERROR`,e.DOWNLOAD=`DOWNLOAD`,e.PROGRESS=`PROGRESS`,e.LOG=`LOG`,e.MOUNT=`MOUNT`,e.UNMOUNT=`UNMOUNT`})(m4||={});const h4=(()=>{let e=0;return()=>e++})(),g4=Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),_4=Error(`called FFmpeg.terminate()`);var v4=class{#e=null;#t={};#n={};#r=[];#i=[];loaded=!1;#a=()=>{this.#e&&(this.#e.onmessage=({data:{id:e,type:t,data:n}})=>{switch(t){case m4.LOAD:this.loaded=!0,this.#t[e](n);break;case m4.MOUNT:case m4.UNMOUNT:case m4.EXEC:case m4.FFPROBE:case m4.WRITE_FILE:case m4.READ_FILE:case m4.DELETE_FILE:case m4.RENAME:case m4.CREATE_DIR:case m4.LIST_DIR:case m4.DELETE_DIR:this.#t[e](n);break;case m4.LOG:this.#r.forEach(e=>e(n));break;case m4.PROGRESS:this.#i.forEach(e=>e(n));break;case m4.ERROR:this.#n[e](n);break}delete this.#t[e],delete this.#n[e]})};#o=({type:e,data:t},n=[],r)=>this.#e?new Promise((i,a)=>{let o=h4();this.#e&&this.#e.postMessage({id:o,type:e,data:t},n),this.#t[o]=i,this.#n[o]=a,r?.addEventListener(`abort`,()=>{a(new DOMException(`Message # ${o} was aborted`,`AbortError`))},{once:!0})}):Promise.reject(g4);on(e,t){e===`log`?this.#r.push(t):e===`progress`&&this.#i.push(t)}off(e,t){e===`log`?this.#r=this.#r.filter(e=>e!==t):e===`progress`&&(this.#i=this.#i.filter(e=>e!==t))}load=({classWorkerURL:e,...t}={},{signal:n}={})=>(this.#e||(this.#e=e?new Worker(new URL(e,import.meta.url),{type:`module`}):new Worker(new URL(`/assets/worker-D1KsWRGg.js`,``+import.meta.url),{type:`module`}),this.#a()),this.#o({type:m4.LOAD,data:t},void 0,n));exec=(e,t=-1,{signal:n}={})=>this.#o({type:m4.EXEC,data:{args:e,timeout:t}},void 0,n);ffprobe=(e,t=-1,{signal:n}={})=>this.#o({type:m4.FFPROBE,data:{args:e,timeout:t}},void 0,n);terminate=()=>{let e=Object.keys(this.#n);for(let t of e)this.#n[t](_4),delete this.#n[t],delete this.#t[t];this.#e&&(this.#e.terminate(),this.#e=null,this.loaded=!1)};writeFile=(e,t,{signal:n}={})=>{let r=[];return t instanceof Uint8Array&&r.push(t.buffer),this.#o({type:m4.WRITE_FILE,data:{path:e,data:t}},r,n)};mount=(e,t,n)=>this.#o({type:m4.MOUNT,data:{fsType:e,options:t,mountPoint:n}},[]);unmount=e=>this.#o({type:m4.UNMOUNT,data:{mountPoint:e}},[]);readFile=(e,t=`binary`,{signal:n}={})=>this.#o({type:m4.READ_FILE,data:{path:e,encoding:t}},void 0,n);deleteFile=(e,{signal:t}={})=>this.#o({type:m4.DELETE_FILE,data:{path:e}},void 0,t);rename=(e,t,{signal:n}={})=>this.#o({type:m4.RENAME,data:{oldPath:e,newPath:t}},void 0,n);createDir=(e,{signal:t}={})=>this.#o({type:m4.CREATE_DIR,data:{path:e}},void 0,t);listDir=(e,{signal:t}={})=>this.#o({type:m4.LIST_DIR,data:{path:e}},void 0,t);deleteDir=(e,{signal:t}={})=>this.#o({type:m4.DELETE_DIR,data:{path:e}},void 0,t)},y4;(function(e){e.MEMFS=`MEMFS`,e.NODEFS=`NODEFS`,e.NODERAWFS=`NODERAWFS`,e.IDBFS=`IDBFS`,e.WORKERFS=`WORKERFS`,e.PROXYFS=`PROXYFS`})(y4||={});const b4="@ffmpeg/core is not installed in node_modules: run `ipk add @ffmpeg/core@0.12.10` (no network fallback)";let x4=null;async function S4(e={}){return x4||=C4(e.onProgress,e.ipk).catch(e=>{throw x4=null,e}),x4}async function C4(e,t){let n=e??(()=>{}),r=new v4,i=await T4(t,n);return n(`initializing ffmpeg-core...`),await r.load({coreURL:i.coreURL,wasmURL:i.wasmURL,...i.classWorkerURL?{classWorkerURL:i.classWorkerURL}:{}}),n(`ffmpeg ready`),r}async function w4(e){let t;try{t=await on(`@ffmpeg/core/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=ct(t.path).dir,r=`${n}/dist/esm/ffmpeg-core.js`,i=`${n}/dist/esm/ffmpeg-core.wasm`;if(!await e.reader.exists(r)||!await e.reader.exists(i))return null;try{return{coreSource:await e.reader.readFile(r),wasmBytes:await e.readBytes(i)}}catch{return null}}async function T4(e,t){if(Cn())throw Error(`ffmpeg-wasm is not available in Node runtime`);if(!e)throw Error(b4);let n=await w4(e);if(!n)throw Error(b4);t(`ffmpeg-core loaded from ipk node_modules (js: ${n.coreSource.length} chars, wasm: ${n.wasmBytes.byteLength} bytes)`);let r=E4(n.wasmBytes,`application/wasm`);return{coreURL:D4(n.coreSource,`text/javascript`),wasmURL:r}}function E4(e,t){let n=new ArrayBuffer(e.byteLength);return new Uint8Array(n).set(e),URL.createObjectURL(new Blob([n],{type:t}))}function D4(e,t){return URL.createObjectURL(new Blob([e],{type:t}))}function O4(){return{stdout:`ffmpeg - WASM build, downloaded on demand
|
|
6175
6175
|
|
|
6176
6176
|
Usage:
|
|
6177
6177
|
ffmpeg [global-opts] -i input [input-opts] ... output [output-opts]
|
|
@@ -6208,14 +6208,14 @@ Notes:
|
|
|
6208
6208
|
- The browser will prompt for camera/mic permission on first capture.
|
|
6209
6209
|
- Numeric -i values index into the per-kind enumerateDevices() list,
|
|
6210
6210
|
matching ffmpeg's native avfoundation device numbering on macOS.
|
|
6211
|
-
`,stderr:``,exitCode:0}}async function
|
|
6212
|
-
`,stderr:``,exitCode:0}:{stdout:``,stderr:`ffmpeg: ${
|
|
6213
|
-
`,exitCode:1}:
|
|
6214
|
-
`,exitCode:1}})}async function
|
|
6215
|
-
`)}\n`,exitCode:0}}async function
|
|
6216
|
-
`,exitCode:1}}}catch(e){return{error:{stdout:``,stderr:
|
|
6211
|
+
`,stderr:``,exitCode:0}}async function k4(e){return await w4(U4(e))?{stdout:`ffmpeg (wasm via @ffmpeg/ffmpeg)
|
|
6212
|
+
`,stderr:``,exitCode:0}:{stdout:``,stderr:`ffmpeg: ${b4}\n`,exitCode:1}}function A4(e){if(!e.includes(`:`))return{video:e};let t=e.indexOf(`:`),n=e.slice(0,t),r=e.slice(t+1);return{...n?{video:n}:{},...r?{audio:r}:{}}}const j4=new Set(`-f.-i.-c.-c:v.-c:a.-vf.-af.-filter:v.-filter:a.-filter_complex.-r.-b:v.-b:a.-s.-t.-ss.-to.-pix_fmt.-vcodec.-acodec.-ar.-ac.-frames:v.-frames:a.-q:v.-q:a.-crf.-preset.-tune.-movflags.-map.-metadata.-loglevel.-threads.-video_size.-framerate.-pixel_format.-update.-list_devices.-warmup`.split(`.`));function M4(){return{inputs:[],outputOpts:[],outputPath:null,listDevices:!1,exactSize:!1,pendingOpts:[]}}function N4(e,t,n){let r=e[t+1];if(typeof r!=`string`)throw Error(`ffmpeg: ${n} requires a value`);return r}function P4(e,t,n){let r=N4(t,n,`-i`);return e.inputs.push({path:r,format:e.pendingFormat,videoSize:e.pendingVideoSize,frameRate:e.pendingFrameRate,raw:[...e.pendingOpts,`-i`,r]}),e.pendingFormat=void 0,e.pendingVideoSize=void 0,e.pendingFrameRate=void 0,e.pendingOpts=[],n+2}function F4(e,t,n){let r=N4(t,n,`-video_size`),i=/^(\d+)x(\d+)$/.exec(r);return i&&(e.pendingVideoSize={width:parseInt(i[1],10),height:parseInt(i[2],10)}),e.pendingOpts.push(`-video_size`,r),n+2}function I4(e,t,n){let r=N4(t,n,`-framerate`),i=parseFloat(r);return Number.isNaN(i)||(e.pendingFrameRate=i),e.pendingOpts.push(`-framerate`,r),n+2}function L4(e,t,n){let r=N4(t,n,`-list_devices`);return/^(true|1|yes)$/i.test(r)&&(e.listDevices=!0),e.pendingOpts.push(`-list_devices`,r),n+2}function R4(e,t,n){let r=N4(t,n,`-warmup`),i=parseInt(r,10);return!Number.isNaN(i)&&i>=0&&(e.warmupMs=i),n+2}function z4(e,t,n,r){if(j4.has(r)){let i=N4(t,n,r);return e.pendingOpts.push(r,i),n+2}return e.pendingOpts.push(r),n+1}function B4(e,t,n){return e.outputPath=t,e.outputOpts=e.pendingOpts,e.pendingOpts=[],n+1}function V4(e){let t=M4(),n=0;for(;n<e.length;){let r=e[n];if(r===`-i`){n=P4(t,e,n);continue}if(r===`-f`){let r=N4(e,n,`-f`);t.pendingFormat=r,t.pendingOpts.push(`-f`,r),n+=2;continue}if(r===`-video_size`){n=F4(t,e,n);continue}if(r===`-framerate`){n=I4(t,e,n);continue}if(r===`-list_devices`){n=L4(t,e,n);continue}if(r===`-warmup`){n=R4(t,e,n);continue}if(r===`-exact_size`){t.exactSize=!0,n+=1;continue}if(r.startsWith(`-`)){n=z4(t,e,n,r);continue}n=B4(t,r,n)}return{inputs:t.inputs,outputOpts:t.outputOpts,outputPath:t.outputPath,listDevices:t.listDevices,...t.warmupMs===void 0?{}:{warmupMs:t.warmupMs},exactSize:t.exactSize}}function H4(e){return e.inputs.some(e=>e.format===`avfoundation`)}function U4(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}function W4(e){let t=[];return(e.mode===`photo`||e.captureVideo!==!1)&&t.push(`camera`),e.mode===`video`&&e.captureAudio&&t.push(`microphone`),t}function G4(e){return e.length===0?`media devices`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`}function K4(e){for(let t of e){let e=t.stream;if(e)for(let t of e.getTracks())t.stop()}}async function q4(e,t){if(typeof window>`u`)return null;try{let{getLeaderPermissionsSurface:n}=await import(`./wc-permissions-registry-C7PhTX3c.js`).then(e=>e.n),r=n();if(!r)return null;let i=await r.prompt({kinds:e,description:t});if(K4(i.grants),i.status===`granted`)return{ok:!0};let a=i.message?`: ${i.message}`:``;return{ok:!1,message:`${i.reason??i.status}${a}`}}catch{return null}}async function J4(e){if(e.length===0)return{ok:!0};let t=`ffmpeg is requesting access to your ${G4(e)}.`,n=await q4(e,t);if(n)return n;let r=i();if(r)try{return await r.call(`permission-request`,{kinds:e,description:t},{timeoutMs:5*6e4}),{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return/permission surface unavailable/i.test(t)?{ok:!0}:{ok:!1,message:t}}return{ok:!0}}function Y4(e){let t=e.inputs.find(e=>e.format===`avfoundation`);if(!t)throw Error(`ffmpeg: no avfoundation input found`);if(!e.outputPath)throw Error(`ffmpeg: output path is required`);let n=e.outputOpts.indexOf(`-frames:v`),r=n>=0&&e.outputOpts[n+1]===`1`,i=e.outputOpts.indexOf(`-update`),a=i>=0&&e.outputOpts[i+1]===`1`,o=e.outputOpts.indexOf(`-t`),s=o>=0?parseFloat(e.outputOpts[o+1]):NaN,c=A4(t.path),l=Z4(e.outputPath),u=/^image\//.test(l),d=!c.video&&!!c.audio;if(!d&&(r||a||u)){let n=u&&/^image\/(jpeg|png|webp)$/.test(l)?l:`image/jpeg`;return{outputPath:e.outputPath,captureMime:n,needsTranscode:X4(e.outputOpts,`photo`)||n!==l,request:{mode:`photo`,deviceId:c.video,width:t.videoSize?.width,height:t.videoSize?.height,frameRate:t.frameRate,exactSize:e.exactSize,mimeType:n,quality:.92,...e.warmupMs===void 0?{}:{warmupMs:e.warmupMs}}}}let f=d||!!c.audio,p=`video/webm`;return{outputPath:e.outputPath,captureMime:p,needsTranscode:X4(e.outputOpts,`video`)||p!==l,request:{mode:`video`,deviceId:c.video,captureVideo:!d,...f?{captureAudio:!0}:{},...c.audio?{audioDeviceId:c.audio}:{},width:t.videoSize?.width,height:t.videoSize?.height,frameRate:t.frameRate,exactSize:e.exactSize,mimeType:p,durationMs:Number.isFinite(s)?s*1e3:void 0}}}function X4(e,t){let n=t===`photo`?new Set([`-vf`,`-filter:v`,`-filter_complex`,`-pix_fmt`,`-q:v`,`-vcodec`,`-c:v`]):new Set([`-c`,`-c:v`,`-c:a`,`-vcodec`,`-acodec`,`-vf`,`-af`,`-filter:v`,`-filter:a`,`-filter_complex`,`-pix_fmt`,`-pixel_format`,`-crf`,`-preset`,`-tune`,`-b:v`,`-b:a`,`-ar`,`-ac`,`-q:v`,`-q:a`,`-movflags`,`-r`]);return e.some(e=>n.has(e))}function Z4(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.webp`)?`image/webp`:t.endsWith(`.gif`)?`image/gif`:t.endsWith(`.webm`)?`video/webm`:t.endsWith(`.mp4`)?`video/mp4`:t.endsWith(`.mov`)?`video/quicktime`:t.endsWith(`.mkv`)?`video/x-matroska`:t.endsWith(`.m4a`)?`audio/mp4`:t.endsWith(`.mp3`)?`audio/mpeg`:t.endsWith(`.wav`)?`audio/wav`:t.endsWith(`.ogg`)?`audio/ogg`:`application/octet-stream`}function Q4(e){return e===`image/jpeg`?`jpg`:e===`image/png`?`png`:e===`image/webp`?`webp`:e===`video/webm`?`webm`:e===`video/mp4`?`mp4`:e===`audio/webm`?`webm`:`bin`}function $4(e,t){let n=e.path.lastIndexOf(`/`),r=n>=0?e.path.slice(n+1):e.path;return r?`__in${t}_${r}`:`__in${t}.bin`}function e3(){return B(`ffmpeg`,async(e,t)=>{if(e.length===0||e.includes(`--help`))return O4();if(e.includes(`-version`)||e.includes(`--version`))return k4(t);let n;try{n=V4(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return n.listDevices&&H4(n)?t3():n.outputPath?n.inputs.length===0?{stdout:``,stderr:`ffmpeg: at least one input file must be specified
|
|
6213
|
+
`,exitCode:1}:H4(n)?s3(n,t):p3(n,t):{stdout:``,stderr:`ffmpeg: at least one output file must be specified
|
|
6214
|
+
`,exitCode:1}})}async function t3(){let e;try{e=await n3()}catch(e){return{stdout:``,stderr:`ffmpeg: failed to enumerate devices: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let t=[];return t.push(`[AVFoundation indev @ 0x0] AVFoundation video devices:`),e.videoinputs.length===0?t.push(`[AVFoundation indev @ 0x0] (none)`):e.videoinputs.forEach((e,n)=>{t.push(`[AVFoundation indev @ 0x0] [${n}] ${e.label||`Camera ${n}`}`)}),t.push(`[AVFoundation indev @ 0x0] AVFoundation audio devices:`),e.audioinputs.length===0?t.push(`[AVFoundation indev @ 0x0] (none)`):e.audioinputs.forEach((e,n)=>{t.push(`[AVFoundation indev @ 0x0] [${n}] ${e.label||`Microphone ${n}`}`)}),{stdout:``,stderr:`${t.join(`
|
|
6215
|
+
`)}\n`,exitCode:0}}async function n3(){if(a()&&typeof navigator<`u`&&navigator.mediaDevices?.enumerateDevices){let e=await navigator.mediaDevices.enumerateDevices(),t=e=>({deviceId:e.deviceId,label:e.label||``,...e.groupId?{groupId:e.groupId}:{}});return{videoinputs:e.filter(e=>e.kind===`videoinput`).map(t),audioinputs:e.filter(e=>e.kind===`audioinput`).map(t)}}let e=i();if(!e)throw Error(`device enumeration requires a browser context`);return e.call(`enumerate-media-devices`,void 0,{timeoutMs:1e4})}async function r3(e){let t=await u4({kind:`camera`,...e.request}),n=new ArrayBuffer(t.bytes.byteLength);return new Uint8Array(n).set(t.bytes),{bytes:n,mimeType:t.mimeType,width:t.width,height:t.height,...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}async function i3(e){let t=i();if(!t)return null;let n=await t.call(`capture-camera`,e.request,{timeoutMs:5*6e4});return{bytes:n.bytes,mimeType:n.mimeType,width:n.width,height:n.height,durationMs:n.durationMs}}async function a3(e){try{if(c4())return{result:await r3(e)};let t=await i3(e);return t?{result:t}:{error:{stdout:``,stderr:`ffmpeg: camera capture requires a browser context — not available in this runtime
|
|
6216
|
+
`,exitCode:1}}}catch(e){return{error:{stdout:``,stderr:o3(e),exitCode:1}}}}function o3(e){let t=e instanceof Error?e.message:String(e);return/NotAllowedError|Permission denied/i.test(t)?`ffmpeg: camera permission denied
|
|
6217
6217
|
`:/NotFoundError/i.test(t)?`ffmpeg: no camera device found
|
|
6218
|
-
`:`ffmpeg: ${t}\n`}async function
|
|
6218
|
+
`:`ffmpeg: ${t}\n`}async function s3(e,t){let n;try{n=Y4(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let r=await J4(W4(n.request));if(!r.ok)return{stdout:``,stderr:`ffmpeg: camera permission denied (${r.message})\n`,exitCode:1};let i=await a3(n);if(`error`in i)return i.error;let a=i.result,o=Math.round(a.bytes.byteLength/1024),s=`${a.width}x${a.height}`,c=n.request.mode===`video`&&a.durationMs?`${s}, ${Math.round(a.durationMs)}ms`:s,l=new Uint8Array(a.bytes),u=``;if(n.needsTranscode)try{let r=await c3({bytes:l,captureMime:n.captureMime,outputName:n.outputPath,outputOpts:e.outputOpts,ipk:U4(t),onLog:e=>{u+=`${e}\n`}});l=new Uint8Array(r.byteLength),l.set(r)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${u}ffmpeg: captured ${c} (${o} KB) but transcode failed: ${t}\n`,exitCode:1}}let d=t.fs.resolvePath(t.cwd,n.outputPath);try{await t.fs.writeFile(d,l)}catch(e){return{stdout:``,stderr:`ffmpeg: failed to write ${n.outputPath}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let f=Math.round(l.byteLength/1024),p=n.needsTranscode?`${o} KB → ${f} KB`:`${o} KB`;return{stdout:``,stderr:`${u}ffmpeg: captured ${c} (${p}) to ${n.outputPath}\n`,exitCode:0}}async function c3(e){let t=`__capture.${Q4(e.captureMime)}`,n=`__out_${e.outputName.split(`/`).pop()||`out.bin`}`;e.onLog(`transcoding captured stream...`);let r=await S4({onProgress:e.onLog,ipk:e.ipk}),i=t=>{e.onLog(t.message)};r.on(`log`,i);try{await r.writeFile(t,e.bytes);let i=[`-i`,t,...e.outputOpts,n],a=await r.exec(i);if(a!==0)throw Error(`ffmpeg-core exited with code ${a}`);let o=await r.readFile(n);if(o instanceof Uint8Array)return o;if(typeof o==`string`)return new TextEncoder().encode(o);throw Error(`ffmpeg-core returned an unknown payload type`)}finally{try{r.off(`log`,i)}catch{}try{await r.deleteFile(t)}catch{}try{await r.deleteFile(n)}catch{}}}function l3(e){return e.format===`lavfi`}async function u3(e,t){let n=[];for(let[r,i]of e.inputs.entries()){if(l3(i)){n.push({ffmpegName:i.path,bytes:null,virtual:!0});continue}let e=t.fs.resolvePath(t.cwd,i.path);if(!await t.fs.exists(e))return{error:{stdout:``,stderr:`ffmpeg: input file not found: ${i.path}\n`,exitCode:1}};let a=await t.fs.readFileBuffer(e);n.push({ffmpegName:$4(i,r),bytes:a,virtual:!1})}return{inputs:n}}function d3(e,t,n){let r=[];for(let[n,i]of e.inputs.entries()){let e=t[n],a=i.raw;for(let t=0;t<a.length;t++){if(a[t]===`-i`){r.push(`-i`,e.virtual?a[t+1]:e.ffmpegName),t+=1;continue}r.push(a[t])}}return r.push(...e.outputOpts),r.push(n),r}async function f3(e,t,n){for(let n of t)if(n.bytes!==null)try{await e.deleteFile(n.ffmpegName)}catch{}try{await e.deleteFile(n)}catch{}}async function p3(e,t){let n=await u3(e,t);if(`error`in n)return n.error;let r=n.inputs,i=e.outputPath,a=`__out_${i.split(`/`).pop()||`out.bin`}`,o=``,s;try{s=await S4({onProgress:e=>{o+=`${e}\n`},ipk:U4(t)})}catch(e){return{stdout:``,stderr:`${o}ffmpeg: failed to load wasm: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let c=e=>{o+=`${e.message}\n`};s.on(`log`,c);try{for(let e of r)e.bytes!==null&&await s.writeFile(e.ffmpegName,e.bytes);let n=d3(e,r,a),c=await s.exec(n);if(c!==0)return{stdout:``,stderr:o||`ffmpeg: exited with code ${c}\n`,exitCode:c||1};let l;try{l=await s.readFile(a)}catch{return{stdout:``,stderr:o||`ffmpeg: produced no output file for ${i}\n`,exitCode:1}}let u=l instanceof Uint8Array?l:new TextEncoder().encode(typeof l==`string`?l:``);if(u.byteLength===0)return{stdout:``,stderr:o||`ffmpeg: produced an empty output file for ${i}\n`,exitCode:1};let d=t.fs.resolvePath(t.cwd,i);return await t.fs.writeFile(d,u),{stdout:``,stderr:o,exitCode:0}}catch(e){return{stdout:``,stderr:`${o}ffmpeg: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}finally{try{s.off(`log`,c)}catch{}await f3(s,r,a)}}const m3=new Map;let h3=0;function g3(){return B(`fswatch`,async e=>{let t=e[0];if(!t||t===`--help`)return{stdout:`usage: fswatch <command> [options]
|
|
6219
6219
|
|
|
6220
6220
|
Commands:
|
|
6221
6221
|
create --path <path> --pattern <glob> [--scoop <name>] [--name <name>] Watch for file changes
|
|
@@ -6227,11 +6227,11 @@ Options:
|
|
|
6227
6227
|
--pattern <glob> File pattern to match, e.g. "*.md", "*.bsh" (required)
|
|
6228
6228
|
--scoop <name> Route change events to this scoop as lick events
|
|
6229
6229
|
--name <name> Human-readable name for the watcher
|
|
6230
|
-
`,stderr:``,exitCode:0};if(t===`list`){if(
|
|
6231
|
-
`,stderr:``,exitCode:0};let e=``;for(let[,t]of
|
|
6232
|
-
`,exitCode:1};let n=
|
|
6230
|
+
`,stderr:``,exitCode:0};if(t===`list`){if(m3.size===0)return{stdout:`No active file watchers.
|
|
6231
|
+
`,stderr:``,exitCode:0};let e=``;for(let[,t]of m3)e+=`ID: ${t.id}\n`,e+=` Name: ${t.name}\n`,e+=` Path: ${t.basePath}\n`,e+=` Pattern: ${t.pattern}\n`,t.scoop&&(e+=` Scoop: ${t.scoop}\n`),e+=` Created: ${t.createdAt}\n\n`;return{stdout:e,stderr:``,exitCode:0}}if(t===`delete`){let t=e[1];if(!t)return{stdout:``,stderr:`fswatch: delete requires an ID
|
|
6232
|
+
`,exitCode:1};let n=m3.get(t);return n?(n.unsubscribe(),m3.delete(t),{stdout:`Deleted watcher "${n.name}" (${t})\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fswatch: watcher not found: ${t}\n`,exitCode:1}}if(t===`create`){let t=``,n=``,r=``,i=``;for(let a=1;a<e.length;a++)e[a]===`--path`&&e[a+1]?t=e[++a]:e[a]===`--pattern`&&e[a+1]?n=e[++a]:e[a]===`--scoop`&&e[a+1]?r=e[++a]:e[a]===`--name`&&e[a+1]&&(i=e[++a]);if(!t||!n)return{stdout:``,stderr:`fswatch: --path and --pattern are required
|
|
6233
6233
|
`,exitCode:1};let a=RegExp(`^`+n.replace(/\./g,`\\.`).replace(/\*/g,`.*`)+`$`),o=e=>{let t=e.split(`/`).pop()??``;return a.test(t)},s=globalThis.__slicc_fs_watcher;if(!s)return{stdout:``,stderr:`fswatch: file system watcher not available
|
|
6234
|
-
`,exitCode:1};let c=`fsw-${++
|
|
6234
|
+
`,exitCode:1};let c=`fsw-${++h3}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});m3.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}function _3(){return{stdout:`usage: hear [-i file] [-l lang] [-T seconds] [-d deviceId] [--engine name]
|
|
6235
6235
|
hear --devices | --status | --warmup
|
|
6236
6236
|
|
|
6237
6237
|
Speech recognition: listens on the microphone until you pause, then
|
|
@@ -6249,15 +6249,15 @@ Options:
|
|
|
6249
6249
|
--devices List audio input devices
|
|
6250
6250
|
--status Show the enhanced model state (downloading/ready + ETA)
|
|
6251
6251
|
--warmup Start the enhanced model download in the background
|
|
6252
|
-
`,stderr:``,exitCode:0}}const
|
|
6252
|
+
`,stderr:``,exitCode:0}}const v3={"--devices":`devices`,"--status":`status`,"--warmup":`warmup`},y3={"-i":`a file path`,"-l":`a language tag`,"-T":`a timeout in seconds`,"-d":`a device id`,"--engine":`an engine name`};function b3(e,t,n){switch(t){case`-i`:return e.inputFile=n,null;case`-l`:return e.lang=n,null;case`-d`:return e.deviceId=n,null;case`-T`:{let t=Number.parseFloat(n);return Number.isNaN(t)||t<=0||t>600?`-T requires a timeout between 0 and 600 seconds`:(e.timeoutSeconds=t,null)}case`--engine`:return n!==`builtin`&&n!==`enhanced`?`--engine must be builtin or enhanced`:(e.engine=n,null);default:return`unknown option: ${t}`}}function x3(e){let t={inputFile:null,lang:void 0,timeoutSeconds:30,deviceId:void 0,engine:`auto`,devices:!1,status:!1,warmup:!1};for(let n=0;n<e.length;n++){let r=e[n],i=v3[r];if(i){t[i]=!0;continue}if(!(r in y3))return C3(`unknown option: ${r}`);let a=n+1<e.length?e[++n]:null;if(a==null)return C3(`${r} requires ${y3[r]}`);let o=b3(t,r,a);if(o)return C3(o)}return t}function S3(e){switch(e.state){case`ready`:return`enhanced engine: ready
|
|
6253
6253
|
`;case`failed`:return`enhanced engine: failed (re-run hear --warmup to retry)
|
|
6254
6254
|
`;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
|
|
6255
|
-
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`enhanced engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function
|
|
6255
|
+
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`enhanced engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function C3(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function w3(e){return e instanceof Error?e.message:String(e)}function T3(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
|
|
6256
6256
|
`)+(t.length?`
|
|
6257
|
-
`:``)}async function
|
|
6258
|
-
`,stderr:``,exitCode:0}}catch(e){return
|
|
6257
|
+
`:``)}async function E3(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:T3((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:C3(`device enumeration unavailable`):{stdout:T3((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return C3(w3(e))}}async function D3(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-DI5vlKdf.js`);return{stdout:S3(t?n():e()),stderr:``,exitCode:0}}return{stdout:S3(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return C3(w3(e))}}async function O3(e,t,n){let r=t.inputFile,i=n.fs.resolvePath(n.cwd,r),a;try{a=new Uint8Array(await n.fs.readFileBuffer(i))}catch{return C3(`cannot open ${r}: No such file`)}let o=_n(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return C3(`${r} is not an audio file`);let s=new ArrayBuffer(a.byteLength);new Uint8Array(s).set(a);try{return{stdout:(e.local?await(await import(`./hear-DI5vlKdf.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
|
|
6258
|
+
`,stderr:``,exitCode:0}}catch(e){return C3(`transcription failed: ${w3(e)}`)}}async function k3(e,t){let n=Math.round(t.timeoutSeconds*1e3);try{let r={lang:t.lang,timeoutMs:n,deviceId:t.deviceId,engine:t.engine},i=e.local?await(await import(`./hear-DI5vlKdf.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
|
|
6259
6259
|
`,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
|
|
6260
|
-
`,exitCode:1}}catch(e){return
|
|
6260
|
+
`,exitCode:1}}catch(e){return C3(w3(e))}}function A3(){return B(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return _3();let n=x3(e);if(`exitCode`in n)return n;let r={local:a(),panelRpc:i()};return!r.local&&!r.panelRpc?C3(`speech recognition unavailable in this environment`):n.devices?E3(r):n.status||n.warmup?D3(r,n.warmup):n.inputFile?O3(r,n,t):k3(r,n)})}const j3=[`playwright-cli`,`playwright`,`puppeteer`],M3=new WeakMap;function N3(e,t){let n=M3.get(e);n||(n=new WeakMap,M3.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map,consoleMessages:new Map,consoleCleanup:new Map,networkRequests:new Map,networkRequestIndex:new Map,networkCleanup:new Map,routes:new Map,routeCleanup:new Map,lastMousePosition:new Map},n.set(t,r)),r}function P3(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const F3=h,I3=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`,`drop`]);function L3(e){return e.toISOString().replace(/:/g,`-`)}function R3(e){return e instanceof P||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const z3=`function(text) {
|
|
6261
6261
|
const el = this;
|
|
6262
6262
|
const tag = el.tagName;
|
|
6263
6263
|
const proto = tag === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
|
|
@@ -6269,11 +6269,11 @@ Options:
|
|
|
6269
6269
|
}
|
|
6270
6270
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6271
6271
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6272
|
-
}`,
|
|
6272
|
+
}`,B3=`function() {
|
|
6273
6273
|
const el = this;
|
|
6274
6274
|
if (el.isContentEditable) return el.textContent || '';
|
|
6275
6275
|
return el.value ?? '';
|
|
6276
|
-
}`,
|
|
6276
|
+
}`,V3=`function() {
|
|
6277
6277
|
const el = this;
|
|
6278
6278
|
if (!(el instanceof HTMLElement)) return false;
|
|
6279
6279
|
el.focus();
|
|
@@ -6297,19 +6297,19 @@ Options:
|
|
|
6297
6297
|
return true;
|
|
6298
6298
|
}
|
|
6299
6299
|
return false;
|
|
6300
|
-
}`;async function
|
|
6301
|
-
`}}const
|
|
6300
|
+
}`;async function H3(e){let t=await e.evaluate(`JSON.stringify({ href: location.href, hostname: location.hostname, pathname: location.pathname })`);return JSON.parse(t)}const U3={string:[`tab`,`filename`,`max-width`,`runtime`,`timeout`,`filter`,`output`,`start`,`return`,`teleport-start`,`teleport-return`,`teleport-runtime`,`domain`,`path`,`expires`,`method`,`depth`,`modifiers`,`sameSite`,`data`,`status`,`body`,`content-type`,`header`,`style`],boolean:[`boxes`,`clear`,`discover`,`foreground`,`fg`,`full-page`,`fullPage`,`hide`,`httpOnly`,`list`,`off`,`secure`,`static`,`submit`],alias:{foreground:`fg`,"full-page":`fullPage`}};function W3(e){let t=GF(e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e),U3),n={};for(let[e,r]of Object.entries(t.flags)){let t=e===`_noiframes`?`no-iframes`:e;if(r===!0)n[t]=`true`;else if(r===!1)continue;else r!==void 0&&(n[t]=String(r))}return{positional:t.positionals,flags:n}}function Q(e){let t=e.tab;return t?{targetId:t}:{error:`Error: --tab <targetId> is required. Run 'playwright-cli tab-list' to get tab IDs.
|
|
6301
|
+
`}}const G3=[`debug`,`log`,`info`,`warning`,`error`],K3=1e3,q3={assert:`error`,trace:`debug`,dir:`log`,dirxml:`log`,table:`log`,count:`info`,timeEnd:`info`,clear:`log`,startGroup:`log`,startGroupCollapsed:`log`,endGroup:`log`,profile:`debug`,profileEnd:`debug`};function J3(e,t,n,r){if(e.consoleCleanup.has(n))return;e.consoleMessages.set(n,[]);let i=t=>{if(t.sessionId!==r)return;let i=t.type??`log`,a=q3[i]??i,o=(t.args??[]).map(e=>String(e.value??e.description??``)).join(` `),s=e.consoleMessages.get(n);s&&(s.push({level:a,text:o,timestamp:Date.now()}),s.length>K3&&s.splice(0,s.length-K3))};t.on(`Runtime.consoleAPICalled`,i),e.consoleCleanup.set(n,()=>{t.off(`Runtime.consoleAPICalled`,i)})}const Y3=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0]??`log`,o=r.clear===`true`,s=G3.indexOf(a);if(s===-1)return{stdout:``,stderr:`Invalid level "${a}". Valid: ${G3.join(`, `)}\n`,exitCode:1};t.consoleCleanup.has(i.targetId)||await e.withTab(i.targetId,async n=>{let r=e.getTransport();await r.send(`Runtime.enable`,{},n),J3(t,r,i.targetId,n)});let c=(t.consoleMessages.get(i.targetId)??[]).filter(e=>G3.indexOf(e.level)>=s);return o&&t.consoleMessages.set(i.targetId,[]),c.length===0?{stdout:`No console messages
|
|
6302
6302
|
`,stderr:``,exitCode:0}:{stdout:c.map(e=>`[${e.level}] ${e.text}`).join(`
|
|
6303
6303
|
`)+`
|
|
6304
|
-
`,stderr:``,exitCode:0}},
|
|
6304
|
+
`,stderr:``,exitCode:0}},X3=async({browser:e,flags:t})=>{let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};let r=t.domain,i=t.path;return{stdout:await e.withTab(n.targetId,async()=>{let t=(await e.sendCDP(`Network.getCookies`)).cookies??[],n=r||i?t.filter(e=>(!r||String(e.domain??``).includes(r))&&(!i||String(e.path??``).startsWith(i))):t;return n.length===0?`No cookies`:n.map(e=>`${e.name}=${e.value}\tDomain=${e.domain}\tPath=${e.path}\tSecure=${e.secure}\tHttpOnly=${e.httpOnly}\tExpires=${e.expires}`).join(`
|
|
6305
6305
|
`)})+`
|
|
6306
|
-
`,stderr:``,exitCode:0}},
|
|
6306
|
+
`,stderr:``,exitCode:0}},Z3=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`cookie-get requires a cookie name
|
|
6307
6307
|
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return{stdout:await e.withTab(r.targetId,async()=>{let t=((await e.sendCDP(`Network.getCookies`)).cookies??[]).filter(e=>e.name===i);if(t.length===0)throw Error(`Cookie "${i}" not found`);return t.map(e=>`${e.name}=${e.value}\tDomain=${e.domain}\tPath=${e.path}\tSecure=${e.secure}\tHttpOnly=${e.httpOnly}\tExpires=${e.expires}`).join(`
|
|
6308
6308
|
`)})+`
|
|
6309
|
-
`,stderr:``,exitCode:0}},
|
|
6310
|
-
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r=await
|
|
6311
|
-
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r={name:t[0]};n.domain&&(r.domain=n.domain),n.path&&(r.path=n.path),!r.domain&&!r.path&&(r.url=(await
|
|
6312
|
-
`,stderr:``,exitCode:0})},
|
|
6309
|
+
`,stderr:``,exitCode:0}},Q3=async({browser:e,positional:t,flags:n})=>{if(t.length<2)return{stdout:``,stderr:`cookie-set requires <name> <value>
|
|
6310
|
+
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r=await H3(e),i={name:t[0],value:t[1]};n.domain&&(i.domain=n.domain),n.path&&(i.path=n.path),n.secure===`true`&&(i.secure=!0),n.httpOnly===`true`&&(i.httpOnly=!0),n.expires&&(i.expires=parseFloat(n.expires)),n.sameSite&&(i.sameSite=n.sameSite),!i.domain&&!i.path&&(i.url=r.href),await e.sendCDP(`Network.setCookie`,i)}),{stdout:`Cookie "${t[0]}" set\n`,stderr:``,exitCode:0})},$3=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`cookie-delete requires a cookie name
|
|
6311
|
+
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r={name:t[0]};n.domain&&(r.domain=n.domain),n.path&&(r.path=n.path),!r.domain&&!r.path&&(r.url=(await H3(e)).href),await e.sendCDP(`Network.deleteCookies`,r)}),{stdout:`Cookie "${t[0]}" deleted\n`,stderr:``,exitCode:0})},e6=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{await e.sendCDP(`Network.clearBrowserCookies`)}),{stdout:`All cookies cleared
|
|
6312
|
+
`,stderr:``,exitCode:0})},t6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`generate-locator requires a ref (e.g. e5)
|
|
6313
6313
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=t.snapshots.get(i.targetId);if(!o)return{stdout:``,stderr:`No snapshot available. Run "snapshot" first.
|
|
6314
6314
|
`,exitCode:1};let s=o.refToBackendNodeId.get(a);if(!s){let e=o.refToSelector.get(a);return e?{stdout:`page.locator(${JSON.stringify(e.split(`,`)[0].trim())})\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Unknown ref "${a}"\n`,exitCode:1}}let c=``;return await e.withTab(i.targetId,async t=>{let n=e.getTransport();await n.send(`DOM.enable`,{},t);let r=(await n.send(`DOM.resolveNode`,{backendNodeId:s},t)).object;if(!r?.objectId){let e=o.refToSelector.get(a)?.split(`,`)[0].trim()??``;c=`page.locator(${JSON.stringify(e)})`;return}let i=await n.send(`Runtime.callFunctionOn`,{objectId:r.objectId,functionDeclaration:`function() {
|
|
6315
6315
|
const el = this;
|
|
@@ -6321,7 +6321,7 @@ Options:
|
|
|
6321
6321
|
const id = el.id;
|
|
6322
6322
|
return JSON.stringify({ testId, label, placeholder, id });
|
|
6323
6323
|
}`,returnByValue:!0},t),l=JSON.parse(i.result?.value??`{}`);if(l.testId)c=`page.getByTestId(${JSON.stringify(l.testId)})`;else if(l.label)c=`page.getByLabel(${JSON.stringify(l.label)})`;else if(l.placeholder)c=`page.getByPlaceholder(${JSON.stringify(l.placeholder)})`;else if(l.id)c=`page.locator(${JSON.stringify(`#${l.id}`)})`;else{let e=o.refToSelector.get(a)?.split(`,`)[0].trim()??``;c=`page.locator(${JSON.stringify(e)})`}}),{stdout:c+`
|
|
6324
|
-
`,stderr:``,exitCode:0}},
|
|
6324
|
+
`,stderr:``,exitCode:0}},n6=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=r.hide===`true`,o=r.style??`outline: 3px solid #ff4444; background: rgba(255, 68, 68, 0.1);`;if(a&&!n[0])return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Runtime.evaluate`,{expression:`document.querySelectorAll('[data-slicc-highlight]').forEach(el => {
|
|
6325
6325
|
el.style.outline = '';
|
|
6326
6326
|
el.style.background = '';
|
|
6327
6327
|
el.removeAttribute('data-slicc-highlight');
|
|
@@ -6349,35 +6349,35 @@ Options:
|
|
|
6349
6349
|
el.style.cssText += '; ' + styleVal;
|
|
6350
6350
|
el.setAttribute('data-slicc-highlight','1');
|
|
6351
6351
|
}
|
|
6352
|
-
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}}),{stdout:a?`Highlight removed from ${s}\n`:`Highlighted ${s}\n`,stderr:``,exitCode:0}},
|
|
6353
|
-
`,stderr:``,exitCode:0})};function
|
|
6354
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n.join(` `),o=await e.withTab(i.targetId,async()=>{let t=await
|
|
6355
|
-
`,stderr:``,exitCode:0}},
|
|
6356
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=r.output,s;try{s=await t.readTextFile(a)}catch(e){return{stdout:``,stderr:`eval-file: cannot read ${a}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let c=await e.withTab(i.targetId,async()=>{let t=await
|
|
6357
|
-
`,stderr:``,exitCode:0}};function
|
|
6358
|
-
`,exitCode:1};let r=t[0],{browseShWarning:i,...a}=await
|
|
6359
|
-
`,stderr:i?`${i}\n`:``,exitCode:+!!a.error}};function
|
|
6352
|
+
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}}),{stdout:a?`Highlight removed from ${s}\n`:`Highlighted ${s}\n`,stderr:``,exitCode:0}},r6=async({browser:e,positional:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.length>0?t.join(` `):void 0;return await e.withTab(r.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Page.enable`,{},n),await t.send(`Page.handleJavaScriptDialog`,{accept:!0,...i===void 0?{}:{promptText:i}},n)}),{stdout:`Accepted dialog${i?` with "${i}"`:``}\n`,stderr:``,exitCode:0}},i6=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Page.enable`,{},n),await t.send(`Page.handleJavaScriptDialog`,{accept:!1},n)}),{stdout:`Dismissed dialog
|
|
6353
|
+
`,stderr:``,exitCode:0})};function a6(e){let t=e instanceof Error?e.message:String(e);return/SyntaxError/.test(t)}function o6(e){return/\bawait\b/.test(e)||/\breturn\b/.test(e)}async function s6(e,t){try{return await e.evaluate(t)}catch(n){if(!a6(n)||!o6(t))throw n;try{return await e.evaluate(`(async () => (\n${t}\n))()`)}catch(r){if(!a6(r))throw r;try{return await e.evaluate(`(async () => {\n${t}\n})()`)}catch(e){throw a6(e)?n:e}}}}const c6=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`eval requires an expression
|
|
6354
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n.join(` `),o=await e.withTab(i.targetId,async()=>{let t=await s6(e,a);return typeof t==`string`?t:JSON.stringify(t,null,2)});return r.filename?(await t.writeFile(r.filename,o??`null`),{stdout:`Result saved to ${r.filename}\n`,stderr:``,exitCode:0}):{stdout:(o??`undefined`)+`
|
|
6355
|
+
`,stderr:``,exitCode:0}},l6=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`eval-file requires a file path
|
|
6356
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=r.output,s;try{s=await t.readTextFile(a)}catch(e){return{stdout:``,stderr:`eval-file: cannot read ${a}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let c=await e.withTab(i.targetId,async()=>{let t=await s6(e,s);return typeof t==`string`?t:JSON.stringify(t,null,2)});if(o){let e=c??`null`;return await t.writeFile(o,e),{stdout:`Result saved to ${o} (${Math.round(new TextEncoder().encode(e).length/1024)} KB)\n`,stderr:``,exitCode:0}}return{stdout:(c??`undefined`)+`
|
|
6357
|
+
`,stderr:``,exitCode:0}};function u6(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=u(n?.headers),a=await e(r,{method:n?.method??`GET`,...i?{headers:i}:{}});return new Response(a.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}async function d6(e){let t=new Set;try{let n=await e.readDir(`/workspace/skills`);for(let e of n)e.type===`directory`&&e.name.startsWith(`browse-`)&&t.add(e.name)}catch{}return t}async function f6(e,t,n){let r=``;try{r=new URL(e).hostname}catch{return{}}let i=r?oQ(r):``;if(!i)return{};let a;try{a=await lQ(n)}catch(e){return{warning:`playwright-cli: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}`}}let o=await d6(t),s=[];for(let e of a){if(!e.hostname||oQ(e.hostname)!==i)continue;let t=e.name||e.task.replace(/-[A-Za-z0-9]{4,8}$/,``)||e.task,n=`browse-${e.hostname}-${t}`;s.push({slug:e.slug,name:e.name,title:e.title||e.name||e.task,recommendedMethod:e.recommendedMethod,installed:o.has(n),installHint:`upskill browse:${e.hostname}/${e.task}`})}return{skills:s}}async function p6(e,t={}){let n=t.fetchImpl??g(),r;try{r=await n(e,{method:t.method??`GET`})}catch(t){return{url:e,links:[],handoff:null,error:t instanceof Error?t.message:String(t)}}let i=[];for(let[e,t]of Object.entries(r.headers))e.toLowerCase()===`link`&&typeof t==`string`&&t.length>0&&i.push(t);let a=et(i,e),o=it(a),s={url:e,status:r.status,links:a,handoff:o};if(t.discover&&a.length>0){let e=await H0(a,{fetchImpl:u6(n)});s.discovery={catalog:e.catalog,serviceDesc:e.serviceDesc,serviceMeta:e.serviceMeta,status:e.status,llmsTxt:e.llmsTxt,failures:e.failures}}else t.discover&&(s.discovery={failures:[]});if(t.discover&&t.fs){let r=await f6(e,t.fs,n);r.warning?s.browseShWarning=r.warning:r.skills&&r.skills.length>0&&(s.discovery={...s.discovery??{failures:[]},browseShSkills:r.skills})}return s}const m6=async({fs:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`fetch requires a URL
|
|
6358
|
+
`,exitCode:1};let r=t[0],{browseShWarning:i,...a}=await p6(r,{discover:n.discover===`true`,method:n.method??`GET`,fs:e});return{stdout:JSON.stringify(a,null,2)+`
|
|
6359
|
+
`,stderr:i?`${i}\n`:``,exitCode:+!!a.error}};function h6(e){if(!e)return 0;let t={Alt:1,Control:2,Meta:4,Shift:8};return e.split(`,`).map(e=>t[e.trim()]??0).reduce((e,t)=>e|t,0)}async function g6(e,t){let n=e.getTransport();await n.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:`Enter`},t),await n.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:`Enter`},t)}async function _6(e,t,n){let r=e.getTransport(),i=e.getSessionId();((await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:B3,returnByValue:!0},i)).result?.value??``)!==n&&await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:z3,arguments:[{value:n}],returnByValue:!0},i)}async function v6(e,t,n){await e.clickByBackendNodeId(t);let r=e.getTransport(),i=e.getSessionId();await r.send(`DOM.enable`,{},i),await r.send(`Runtime.enable`,{},i);let a=(await r.send(`DOM.resolveNode`,{backendNodeId:t},i)).object;a?.objectId&&await r.send(`Runtime.callFunctionOn`,{objectId:a.objectId,functionDeclaration:V3,returnByValue:!0},i),await e.insertText(n),a?.objectId&&await _6(e,a.objectId,n)}async function y6(e,t,n){await e.click(t),await e.evaluate(`(function() {
|
|
6360
6360
|
const el = document.querySelector(${JSON.stringify(t)});
|
|
6361
|
-
if (el) { return (${
|
|
6361
|
+
if (el) { return (${V3}).call(el); }
|
|
6362
6362
|
return false;
|
|
6363
6363
|
})()`),await e.insertText(n);let r=t.split(`,`)[0].trim();await e.evaluate(`(function() {
|
|
6364
6364
|
const el = document.querySelector(${JSON.stringify(r)});
|
|
6365
6365
|
if (!el) return '';
|
|
6366
|
-
return (${
|
|
6366
|
+
return (${B3}).call(el);
|
|
6367
6367
|
})()`)!==n&&await e.evaluate(`(function() {
|
|
6368
6368
|
const el = document.querySelector(${JSON.stringify(r)});
|
|
6369
6369
|
if (!el) return;
|
|
6370
|
-
(${
|
|
6371
|
-
})()`)}const
|
|
6372
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=
|
|
6370
|
+
(${z3}).call(el, ${JSON.stringify(n)});
|
|
6371
|
+
})()`)}const b6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`click requires a ref (e.g. e5)
|
|
6372
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=h6(r.modifiers);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),s=n.refToFrameId?.get(a);if(r&&s){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let o=r.split(`,`)[0].trim();return await e.evaluateInFrame(s,`(function() {
|
|
6373
6373
|
var el = document.querySelector(${JSON.stringify(o)});
|
|
6374
6374
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6375
6375
|
el.scrollIntoView({ block: 'center' });
|
|
6376
6376
|
el.click();
|
|
6377
6377
|
})()`),t.snapshots.delete(i.targetId),`Clicked ${a} (in iframe)`}let c=n.refToBackendNodeId.get(a);if(c)return await e.clickByBackendNodeId(c,o),t.snapshots.delete(i.targetId),`Clicked ${a}`;let l=n.refToSelector.get(a);if(!l)throw Error(`Unknown ref "${a}". Available: ${[...n.refToSelector.keys()].slice(0,10).join(`, `)}...`);return await e.click(l,o),t.snapshots.delete(i.targetId),`Clicked ${a}`})+`
|
|
6378
|
-
`,stderr:``,exitCode:0}},
|
|
6379
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.join(` `);return await e.withTab(r.targetId,async t=>{await e.type(i),n.submit===`true`&&await
|
|
6380
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async n=>{let s=t.snapshots.get(i.targetId);if(!s)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:c}=
|
|
6378
|
+
`,stderr:``,exitCode:0}},x6=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`type requires text
|
|
6379
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.join(` `);return await e.withTab(r.targetId,async t=>{await e.type(i),n.submit===`true`&&await g6(e,t)}),{stdout:`Typed: ${i}\n`,stderr:``,exitCode:0}},S6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`fill requires <ref> <text>
|
|
6380
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async n=>{let s=t.snapshots.get(i.targetId);if(!s)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:c}=P3(a),l=s.refToFrameId?.get(a);if(c&&l){let c=s.refToSelector.get(a);if(!c)throw Error(`Unknown ref "${a}" in iframe`);let u=c.split(`,`)[0].trim();return await e.evaluateInFrame(l,`(function() {
|
|
6381
6381
|
var el = document.querySelector(${JSON.stringify(u)});
|
|
6382
6382
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6383
6383
|
el.scrollIntoView({ block: 'center' });
|
|
@@ -6386,33 +6386,33 @@ Options:
|
|
|
6386
6386
|
el.value = ${JSON.stringify(o)};
|
|
6387
6387
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6388
6388
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6389
|
-
})()`),t.snapshots.delete(i.targetId),r.submit===`true`&&await
|
|
6390
|
-
`,stderr:``,exitCode:0}},
|
|
6391
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t),await n.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Pressed ${i}\n`,stderr:``,exitCode:0}},
|
|
6392
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t)}),{stdout:`Key ${i} down\n`,stderr:``,exitCode:0}},
|
|
6393
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Key ${i} up\n`,stderr:``,exitCode:0}},
|
|
6394
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1]||`left`,s=
|
|
6389
|
+
})()`),t.snapshots.delete(i.targetId),r.submit===`true`&&await g6(e,n),`Filled ${a} with: ${o} (in iframe)`}let u=s.refToBackendNodeId.get(a);if(u)return await v6(e,u,o),t.snapshots.delete(i.targetId),r.submit===`true`&&await g6(e,n),`Filled ${a} with: ${o}`;let d=s.refToSelector.get(a);if(!d)throw Error(`Unknown ref "${a}"`);return await y6(e,d,o),t.snapshots.delete(i.targetId),r.submit===`true`&&await g6(e,n),`Filled ${a} with: ${o}`})+`
|
|
6390
|
+
`,stderr:``,exitCode:0}},C6=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`press requires a key name
|
|
6391
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t),await n.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Pressed ${i}\n`,stderr:``,exitCode:0}},w6=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`keydown requires a key name
|
|
6392
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t)}),{stdout:`Key ${i} down\n`,stderr:``,exitCode:0}},T6=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`keyup requires a key name
|
|
6393
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Key ${i} up\n`,stderr:``,exitCode:0}},E6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`dblclick requires a ref (e.g. e5)
|
|
6394
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1]||`left`,s=h6(r.modifiers);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),c=n.refToFrameId?.get(a);if(r&&c){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let o=r.split(`,`)[0].trim();return await e.evaluateInFrame(c,`(function() {
|
|
6395
6395
|
var el = document.querySelector(${JSON.stringify(o)});
|
|
6396
6396
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6397
6397
|
el.scrollIntoView({ block: 'center' });
|
|
6398
6398
|
el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
|
|
6399
6399
|
})()`),t.snapshots.delete(i.targetId),`Double-clicked ${a} (in iframe)`}let l=n.refToBackendNodeId.get(a);if(!l)throw Error(`Unknown ref "${a}"`);return await e.dblclickByBackendNodeId(l,o,s),t.snapshots.delete(i.targetId),`Double-clicked ${a}`})+`
|
|
6400
|
-
`,stderr:``,exitCode:0}},
|
|
6401
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6400
|
+
`,stderr:``,exitCode:0}},D6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`hover requires a ref (e.g. e5)
|
|
6401
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),o=n.refToFrameId?.get(a);if(r&&o){let t=n.refToSelector.get(a);if(!t)throw Error(`Unknown ref "${a}" in iframe`);let r=t.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6402
6402
|
var el = document.querySelector(${JSON.stringify(r)});
|
|
6403
6403
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6404
6404
|
el.scrollIntoView({ block: 'center' });
|
|
6405
6405
|
el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
|
|
6406
6406
|
})()`),`Hovered ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);return await e.hoverByBackendNodeId(s),`Hovered ${a}`})+`
|
|
6407
|
-
`,stderr:``,exitCode:0}},
|
|
6408
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6407
|
+
`,stderr:``,exitCode:0}},O6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`select requires <ref> <value>
|
|
6408
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),s=n.refToFrameId?.get(a);if(r&&s){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let c=r.split(`,`)[0].trim();return await e.evaluateInFrame(s,`(function() {
|
|
6409
6409
|
var el = document.querySelector(${JSON.stringify(c)});
|
|
6410
6410
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6411
6411
|
el.value = ${JSON.stringify(o)};
|
|
6412
6412
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6413
6413
|
})()`),t.snapshots.delete(i.targetId),`Selected "${o}" on ${a} (in iframe)`}let c=n.refToBackendNodeId.get(a);if(!c)throw Error(`Unknown ref "${a}"`);return await e.selectByBackendNodeId(c,o),t.snapshots.delete(i.targetId),`Selected "${o}" on ${a}`})+`
|
|
6414
|
-
`,stderr:``,exitCode:0}},
|
|
6415
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6414
|
+
`,stderr:``,exitCode:0}},k6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`check requires a ref (e.g. e5)
|
|
6415
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),o=n.refToFrameId?.get(a);if(r&&o){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let s=r.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6416
6416
|
var el = document.querySelector(${JSON.stringify(s)});
|
|
6417
6417
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6418
6418
|
if (!el.checked) {
|
|
@@ -6421,8 +6421,8 @@ Options:
|
|
|
6421
6421
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
6422
6422
|
}
|
|
6423
6423
|
})()`),t.snapshots.delete(i.targetId),`Checked ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);let c=await e.setCheckedByBackendNodeId(s,!0);return c===`toggled`&&t.snapshots.delete(i.targetId),c===`already`?`${a} already checked`:`Checked ${a}`})+`
|
|
6424
|
-
`,stderr:``,exitCode:0}},
|
|
6425
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6424
|
+
`,stderr:``,exitCode:0}},A6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`uncheck requires a ref (e.g. e5)
|
|
6425
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=P3(a),o=n.refToFrameId?.get(a);if(r&&o){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let s=r.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6426
6426
|
var el = document.querySelector(${JSON.stringify(s)});
|
|
6427
6427
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6428
6428
|
if (el.checked) {
|
|
@@ -6431,14 +6431,14 @@ Options:
|
|
|
6431
6431
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
6432
6432
|
}
|
|
6433
6433
|
})()`),t.snapshots.delete(i.targetId),`Unchecked ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);let c=await e.setCheckedByBackendNodeId(s,!1);return c===`toggled`&&t.snapshots.delete(i.targetId),c===`already`?`${a} already unchecked`:`Unchecked ${a}`})+`
|
|
6434
|
-
`,stderr:``,exitCode:0}},
|
|
6434
|
+
`,stderr:``,exitCode:0}},j6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`drag requires <startRef> <endRef>
|
|
6435
6435
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let r=n.refToBackendNodeId.get(a),s=n.refToBackendNodeId.get(o);if(!r)throw Error(`Unknown ref "${a}"`);if(!s)throw Error(`Unknown ref "${o}"`);return await e.dragByBackendNodeIds(r,s),t.snapshots.delete(i.targetId),`Dragged ${a} to ${o}`})+`
|
|
6436
|
-
`,stderr:``,exitCode:0}};function
|
|
6436
|
+
`,stderr:``,exitCode:0}};function M6(e){return e===void 0?`left`:e===`left`||e===`right`||e===`middle`?e:{error:`Invalid button "${e}". Must be left, right, or middle.\n`}}function N6(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const P6={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,pdf:`application/pdf`,txt:`text/plain`,json:`application/json`,csv:`text/csv`,html:`text/html`,htm:`text/html`,xml:`application/xml`,zip:`application/zip`,mp4:`video/mp4`,mp3:`audio/mpeg`};function F6(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return P6[t]??`application/octet-stream`}const I6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`mousemove requires <x> <y>
|
|
6437
6437
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseFloat(n[0]),o=parseFloat(n[1]);return isNaN(a)||isNaN(o)?{stdout:``,stderr:`x and y must be numbers
|
|
6438
|
-
`,exitCode:1}:(await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:a,y:o,button:`none`,modifiers:0},t)}),t.lastMousePosition.set(i.targetId,{x:a,y:o}),{stdout:`Mouse moved to (${a}, ${o})\n`,stderr:``,exitCode:0})},
|
|
6438
|
+
`,exitCode:1}:(await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:a,y:o,button:`none`,modifiers:0},t)}),t.lastMousePosition.set(i.targetId,{x:a,y:o}),{stdout:`Mouse moved to (${a}, ${o})\n`,stderr:``,exitCode:0})},L6=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=M6(n[0]);if(typeof a==`object`)return{stdout:``,stderr:a.error,exitCode:1};let o=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mousePressed`,button:a,clickCount:1,x:o.x,y:o.y,modifiers:0},t)}),{stdout:`Mouse button ${a} pressed\n`,stderr:``,exitCode:0}},R6=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=M6(n[0]);if(typeof a==`object`)return{stdout:``,stderr:a.error,exitCode:1};let o=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,button:a,clickCount:1,x:o.x,y:o.y,modifiers:0},t)}),{stdout:`Mouse button ${a} released\n`,stderr:``,exitCode:0}},z6=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`mousewheel requires <dx> <dy>
|
|
6439
6439
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseFloat(n[0]),o=parseFloat(n[1]);if(isNaN(a)||isNaN(o))return{stdout:``,stderr:`dx and dy must be numbers
|
|
6440
|
-
`,exitCode:1};let s=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseWheel`,deltaX:a,deltaY:o,x:s.x,y:s.y,modifiers:0},t)}),{stdout:`Mouse wheel scrolled (dx=${a}, dy=${o})\n`,stderr:``,exitCode:0}},
|
|
6441
|
-
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=r[0],s=i.path,c=i.data,l=[];if(s){let e=await t.readFile(s),n=s.split(`/`).pop()??s,r=
|
|
6440
|
+
`,exitCode:1};let s=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseWheel`,deltaX:a,deltaY:o,x:s.x,y:s.y,modifiers:0},t)}),{stdout:`Mouse wheel scrolled (dx=${a}, dy=${o})\n`,stderr:``,exitCode:0}},B6=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`drop requires a ref (e.g. e5)
|
|
6441
|
+
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=r[0],s=i.path,c=i.data,l=[];if(s){let e=await t.readFile(s),n=s.split(`/`).pop()??s,r=F6(n),i=typeof e==`string`?new TextEncoder().encode(e):e;l.push({name:n,type:r,base64:N6(i)})}let u=[];if(c){let e=c.indexOf(`=`);if(e===-1)return{stdout:``,stderr:`--data format must be "mime/type=value"
|
|
6442
6442
|
`,exitCode:1};u.push({mimeType:c.slice(0,e),value:c.slice(e+1)})}return{stdout:await e.withTab(a.targetId,async t=>{let r=n.snapshots.get(a.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let i=e.getTransport(),s=r.refToBackendNodeId.get(o);if(s){await i.send(`DOM.enable`,{},t);let e=await i.send(`DOM.resolveNode`,{backendNodeId:s},t),r=await i.send(`Runtime.callFunctionOn`,{objectId:e.object.objectId,functionDeclaration:`function(filesData, dataItems) {
|
|
6443
6443
|
var dt = new DataTransfer();
|
|
6444
6444
|
for (var i = 0; i < filesData.length; i++) {
|
|
@@ -6453,7 +6453,7 @@ Options:
|
|
|
6453
6453
|
this.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6454
6454
|
this.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6455
6455
|
return this.tagName;
|
|
6456
|
-
}`,arguments:[{value:l},{value:u}],returnByValue:!0},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`}let{isIframe:c}=
|
|
6456
|
+
}`,arguments:[{value:l},{value:u}],returnByValue:!0},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`}let{isIframe:c}=P3(o),d=r.refToFrameId?.get(o),f;if(c&&d){let e=r.refToSelector.get(o);if(!e)throw Error(`Unknown ref "${o}" in iframe`);f=e.split(`,`)[0].trim()}else{let e=r.refToSelector.get(o);if(!e)throw Error(`Unknown ref "${o}". Available: ${[...r.refToSelector.keys()].slice(0,10).join(`, `)}...`);f=e.split(`,`)[0].trim()}let p=JSON.stringify(l),m=JSON.stringify(u),h=`(function() {
|
|
6457
6457
|
var el = document.querySelector(${JSON.stringify(f)});
|
|
6458
6458
|
if (!el) throw new Error('Element not found for ref ${o}: ' + ${JSON.stringify(f)});
|
|
6459
6459
|
var dt = new DataTransfer();
|
|
@@ -6473,7 +6473,7 @@ Options:
|
|
|
6473
6473
|
el.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6474
6474
|
return true;
|
|
6475
6475
|
})()`,g=await i.send(`Runtime.evaluate`,{expression:h,returnByValue:!0,awaitPromise:!1},t);if(g.exceptionDetails){let e=g.exceptionDetails.exception?.description??g.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`})+`
|
|
6476
|
-
`,stderr:``,exitCode:0}},
|
|
6476
|
+
`,stderr:``,exitCode:0}},V6=r(`playwright-teleport`),H6={origin:``,localStorage:{},sessionStorage:{}};function U6(e){let t=new Map;for(let n of e){let e=n.domain??`unknown`;t.set(e,(t.get(e)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]).map(([e,t])=>`${t} ${e}`).join(`, `)}function W6(e){return Object.keys(e.localStorage).length+Object.keys(e.sessionStorage).length}function G6(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function K6(e){try{return new URL(`/favicon.ico`,e).toString()}catch{return e}}function q6(e,t,n){let r=G6(t);if(t&&r===e)return t;let i=G6(n);return n&&i===e?n:e||(t??n)}async function J6(e,t){let n=await e.evaluate(`(() => {
|
|
6477
6477
|
const collect = (storage) => {
|
|
6478
6478
|
const items = {};
|
|
6479
6479
|
for (let i = 0; i < storage.length; i++) {
|
|
@@ -6487,7 +6487,7 @@ Options:
|
|
|
6487
6487
|
localStorage: collect(window.localStorage),
|
|
6488
6488
|
sessionStorage: collect(window.sessionStorage),
|
|
6489
6489
|
});
|
|
6490
|
-
})()`);if(typeof n!=`string`||n.length===0)return
|
|
6490
|
+
})()`);if(typeof n!=`string`||n.length===0)return V6.warn(`Teleport storage capture returned non-string result`,{label:t,type:typeof n}),H6;try{let e=JSON.parse(n);return{origin:typeof e.origin==`string`?e.origin:``,localStorage:e.localStorage??{},sessionStorage:e.sessionStorage??{}}}catch(e){return V6.warn(`Could not parse teleport storage snapshot`,{label:t,error:String(e)}),H6}}function Y6(e){return`(() => {
|
|
6491
6491
|
const snapshot = ${JSON.stringify(e)};
|
|
6492
6492
|
if (!snapshot.origin || window.location.origin !== snapshot.origin) return;
|
|
6493
6493
|
const markerKey = '__slicc_teleport_storage_applied__:' + snapshot.origin;
|
|
@@ -6503,7 +6503,7 @@ Options:
|
|
|
6503
6503
|
apply(window.localStorage, snapshot.localStorage || {});
|
|
6504
6504
|
apply(window.sessionStorage, snapshot.sessionStorage || {});
|
|
6505
6505
|
try { window.sessionStorage.setItem(markerKey, '1'); } catch {}
|
|
6506
|
-
})();`}function
|
|
6506
|
+
})();`}function X6(e){return`(() => {
|
|
6507
6507
|
const snapshot = ${JSON.stringify(e)};
|
|
6508
6508
|
if (!snapshot.origin || globalThis.location.origin !== snapshot.origin) {
|
|
6509
6509
|
throw new Error('Teleport storage origin mismatch');
|
|
@@ -6521,61 +6521,61 @@ Options:
|
|
|
6521
6521
|
localStorageCount: Object.keys(snapshot.localStorage || {}).length,
|
|
6522
6522
|
sessionStorageCount: Object.keys(snapshot.sessionStorage || {}).length,
|
|
6523
6523
|
});
|
|
6524
|
-
})();`}async function
|
|
6524
|
+
})();`}async function Z6(e,t,n){let r=W6(t);if(r===0)return;let i=await e.evaluate(X6(t));V6.info(`Applied teleport storage snapshot on current page`,{target:n,totalEntries:r,resultType:typeof i}),V6.debug(`Applied teleport storage snapshot details`,{target:n,origin:t.origin||`(unknown)`,totalEntries:r,resultType:typeof i})}async function Q6(e,t,n,r){let i=W6(t);if(i===0)return null;let a=await e.sendCDP(`Page.addScriptToEvaluateOnNewDocument`,{source:Y6(t)}),o=typeof a.identifier==`string`?a.identifier:null;return V6.info(`Installed teleport storage init script`,{target:r,totalEntries:i,hasIdentifier:!!o}),V6.debug(`Installed teleport storage init script details`,{target:r,origin:t.origin||`(unknown)`,localStorageCount:Object.keys(t.localStorage).length,sessionStorageCount:Object.keys(t.sessionStorage).length,hasIdentifier:!!o}),o?async()=>{try{await e.attachToPage(n),await e.sendCDP(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:o})}catch(e){V6.warn(`Failed to remove teleport storage init script`,{target:r,error:String(e)})}}:null}async function $6(e){let t=await e.evaluate(`(() => JSON.stringify({
|
|
6525
6525
|
url: window.location.href,
|
|
6526
6526
|
title: document.title || '',
|
|
6527
6527
|
bodySnippet: document.body?.innerText?.replace(/\\s+/g, ' ').trim().slice(0, 500) || '(empty)',
|
|
6528
|
-
}))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function $6(e){return/callback|authorize\/resume|error/i.test(e)}async function e8(e,t,n){try{let r=await Q6(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,B6.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){B6.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function t8(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),B6.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){B6.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}const $=r(`playwright-teleport`);function n8(){return null}async function r8(e,t){if($.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),$.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await e8(e,t,`timeout`)}catch(e){$.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await t8(t,`timeout`)}if(i8(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){$.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function i8(e){$.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function a8(e,t,n,r,i,a,o,s){if(a===`preview`)throw Error(`cannot teleport to a preview target (no Network.*)`);$.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),$.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);$.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&($.info(`Teleport start pattern matched on leader`),$.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),o8(e,t,c,a))}catch(e){$.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function o8(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,$.info(`Teleport triggered`),$.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=V6;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],$.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){$.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await q6(e,`leader`),$.info(`Captured leader storage for follower`,{totalEntries:U6(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o)throw Error(`No follower selection available — not connected to a tray`);$.info(`Selected follower for teleport`),$.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,$.info(`Opened follower tab for teleport`),$.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),$.info(`Attached to follower tab for teleport`),$.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),$.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){$.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await Z6(e,a,c,`follower`),$.info(`Navigating follower to intercepted auth URL`),$.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),$.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&r8(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,$.info(`Teleport waiting for follower auth redirect`),$.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,$.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,$.info(`Follower reached auth provider; waiting for return pattern`),$.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):$.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}$.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),$6(i)&&await e8(e,n,`waiting-for-return`),n.returnPattern.test(i)&&($.info(`Follower return pattern matched after auth`),$.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),d8(e,t,n,o))}catch(e){$.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){$.error(`Teleport trigger failed`,{error:String(e)}),await t8(n,`trigger-error`),n.phase=`done`,i8(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function s8(e,t){$.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(t.followerTargetId);let n;try{let t=await e.evaluate(`window.location.href`);n=typeof t==`string`?t:String(t),$.debug(`Captured final URL from follower`,{finalUrl:n})}catch(e){$.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);$.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){$.warn(`Could not read follower page content`,{error:String(e)})}let r=(await e.sendCDP(`Network.getCookies`)).cookies??[],i=r.length>0?H6(r):`none`;$.info(`Captured cookies from follower`,{count:r.length}),$.debug(`Captured cookies from follower details`,{count:r.length,domains:i});let a=V6;try{a=await q6(e,`follower`),$.info(`Captured follower storage for leader`,{totalEntries:U6(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured follower storage for leader details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture follower storage`,{error:String(e)})}await e8(e,t,`capture`),await t8(t,`capture`);try{await e.closePage(t.followerTargetId),$.info(`Closed follower tab after teleport`),$.debug(`Closed follower tab after teleport details`,{followerTargetId:t.followerTargetId})}catch(e){$.warn(`Failed to close follower tab`,{error:String(e)})}return{cookies:r,followerStorage:a,finalUrl:n}}async function c8(e,t,n,r,i){try{await e.navigate(r),await X6(e,n,`leader`),i&&i!==r&&await e.navigate(i)}catch(a){$.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(a)}),$.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:r,landingUrl:i,error:String(a)});let o=await Z6(e,n,t,`leader`);try{i&&await e.navigate(i)}finally{await o?.()}}}async function l8(e,t,n,r,i){let a=t.leaderTargetId,o=await Z6(e,n,a,`leader`);try{r&&($.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:U6(n)}),$.debug(`Navigating leader after auth-state injection details`,{landingUrl:r,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:n.origin||`(unknown)`,storageEntries:U6(n)}),await e.navigate(r))}finally{await o?.()}}async function u8(e,t,n,r,i){let a=t.leaderTargetId,o=r.origin||``,s=K6(o,t.originalLeaderUrl,i),c=W6(t.originalLeaderUrl),l=!!o&&c!==o,u=l?G6(o):null;return a?(await e.attachToPage(a),n.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:n}),$.info(`Injected cookies into leader tab`,{count:n.length}),$.debug(`Injected cookies into leader tab details`,{count:n.length,leaderTargetId:a})),l&&u?($.info(`Hydrating leader storage origin before landing`,{storageEntries:U6(r)}),$.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:u,landingUrl:s,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:o,storageEntries:U6(r)}),await c8(e,a,r,u,s)):await l8(e,t,r,s,i),s):($.warn(`No leader tab available for auth-state injection`),s)}async function d8(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,$.info(`Capturing auth state from follower`),$.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{let{cookies:t,followerStorage:i,finalUrl:a}=await s8(e,n),o=U6(i),s=await u8(e,n,t,i,a);n.phase=`done`,i8(n);let c=t.length>0?` (${H6(t)})`:``,l=o>0?` + ${o} storage entr${o===1?`y`:`ies`}`:``,u=s?` (navigated to ${s})`:``,d=`Teleported ${t.length} cookie(s)${c}${l} from ${r}${u}`;$.info(`Teleport completed successfully`,{cookieCount:t.length,storageEntries:o,landed:!!s}),$.debug(`Teleport completed successfully details`,{result:d}),n.resolveBlock?.(d)}catch(e){$.error(`Teleport auth-state capture failed`,{error:String(e)}),await t8(n,`capture-error`),n.phase=`done`,i8(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}const f8=r(`playwright`),p8=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`goto requires a URL
|
|
6529
|
-
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};await e.withTab(a.targetId,async()=>(await e.navigate(r[0]),!0)),n.snapshots.delete(a.targetId);let o=i[`teleport-start`],s=i[`teleport-return`];if(o&&s){
|
|
6530
|
-
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Navigated to ${r[0]}\n`,stderr:``,exitCode:0}},
|
|
6531
|
-
`,stderr:``,exitCode:0})},
|
|
6532
|
-
`,stderr:``,exitCode:0})},
|
|
6533
|
-
`,stderr:``,exitCode:0})},
|
|
6534
|
-
`,exitCode:1}:(await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Network.enable`,{},t),await n.send(`Network.emulateNetworkConditions`,{offline:i===`offline`,latency:0,downloadThroughput:-1,uploadThroughput:-1},t)}),{stdout:`Network set to ${i}\n`,stderr:``,exitCode:0})},
|
|
6528
|
+
}))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function e8(e){return/callback|authorize\/resume|error/i.test(e)}async function t8(e,t,n){try{let r=await $6(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,V6.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){V6.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function n8(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),V6.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){V6.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}const $=r(`playwright-teleport`);function r8(){return null}async function i8(e,t){if($.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),$.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await t8(e,t,`timeout`)}catch(e){$.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await n8(t,`timeout`)}if(a8(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){$.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function a8(e){$.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function o8(e,t,n,r,i,a,o,s){if(a===`preview`)throw Error(`cannot teleport to a preview target (no Network.*)`);$.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),$.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);$.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&($.info(`Teleport start pattern matched on leader`),$.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),s8(e,t,c,a))}catch(e){$.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function s8(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,$.info(`Teleport triggered`),$.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=H6;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],$.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){$.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await J6(e,`leader`),$.info(`Captured leader storage for follower`,{totalEntries:W6(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o)throw Error(`No follower selection available — not connected to a tray`);$.info(`Selected follower for teleport`),$.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,$.info(`Opened follower tab for teleport`),$.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),$.info(`Attached to follower tab for teleport`),$.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),$.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){$.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await Q6(e,a,c,`follower`),$.info(`Navigating follower to intercepted auth URL`),$.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),$.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&i8(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,$.info(`Teleport waiting for follower auth redirect`),$.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,$.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,$.info(`Follower reached auth provider; waiting for return pattern`),$.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):$.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}$.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),e8(i)&&await t8(e,n,`waiting-for-return`),n.returnPattern.test(i)&&($.info(`Follower return pattern matched after auth`),$.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),f8(e,t,n,o))}catch(e){$.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){$.error(`Teleport trigger failed`,{error:String(e)}),await n8(n,`trigger-error`),n.phase=`done`,a8(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function c8(e,t){$.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(t.followerTargetId);let n;try{let t=await e.evaluate(`window.location.href`);n=typeof t==`string`?t:String(t),$.debug(`Captured final URL from follower`,{finalUrl:n})}catch(e){$.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);$.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){$.warn(`Could not read follower page content`,{error:String(e)})}let r=(await e.sendCDP(`Network.getCookies`)).cookies??[],i=r.length>0?U6(r):`none`;$.info(`Captured cookies from follower`,{count:r.length}),$.debug(`Captured cookies from follower details`,{count:r.length,domains:i});let a=H6;try{a=await J6(e,`follower`),$.info(`Captured follower storage for leader`,{totalEntries:W6(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured follower storage for leader details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture follower storage`,{error:String(e)})}await t8(e,t,`capture`),await n8(t,`capture`);try{await e.closePage(t.followerTargetId),$.info(`Closed follower tab after teleport`),$.debug(`Closed follower tab after teleport details`,{followerTargetId:t.followerTargetId})}catch(e){$.warn(`Failed to close follower tab`,{error:String(e)})}return{cookies:r,followerStorage:a,finalUrl:n}}async function l8(e,t,n,r,i){try{await e.navigate(r),await Z6(e,n,`leader`),i&&i!==r&&await e.navigate(i)}catch(a){$.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(a)}),$.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:r,landingUrl:i,error:String(a)});let o=await Q6(e,n,t,`leader`);try{i&&await e.navigate(i)}finally{await o?.()}}}async function u8(e,t,n,r,i){let a=t.leaderTargetId,o=await Q6(e,n,a,`leader`);try{r&&($.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:W6(n)}),$.debug(`Navigating leader after auth-state injection details`,{landingUrl:r,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:n.origin||`(unknown)`,storageEntries:W6(n)}),await e.navigate(r))}finally{await o?.()}}async function d8(e,t,n,r,i){let a=t.leaderTargetId,o=r.origin||``,s=q6(o,t.originalLeaderUrl,i),c=G6(t.originalLeaderUrl),l=!!o&&c!==o,u=l?K6(o):null;return a?(await e.attachToPage(a),n.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:n}),$.info(`Injected cookies into leader tab`,{count:n.length}),$.debug(`Injected cookies into leader tab details`,{count:n.length,leaderTargetId:a})),l&&u?($.info(`Hydrating leader storage origin before landing`,{storageEntries:W6(r)}),$.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:u,landingUrl:s,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:o,storageEntries:W6(r)}),await l8(e,a,r,u,s)):await u8(e,t,r,s,i),s):($.warn(`No leader tab available for auth-state injection`),s)}async function f8(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,$.info(`Capturing auth state from follower`),$.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{let{cookies:t,followerStorage:i,finalUrl:a}=await c8(e,n),o=W6(i),s=await d8(e,n,t,i,a);n.phase=`done`,a8(n);let c=t.length>0?` (${U6(t)})`:``,l=o>0?` + ${o} storage entr${o===1?`y`:`ies`}`:``,u=s?` (navigated to ${s})`:``,d=`Teleported ${t.length} cookie(s)${c}${l} from ${r}${u}`;$.info(`Teleport completed successfully`,{cookieCount:t.length,storageEntries:o,landed:!!s}),$.debug(`Teleport completed successfully details`,{result:d}),n.resolveBlock?.(d)}catch(e){$.error(`Teleport auth-state capture failed`,{error:String(e)}),await n8(n,`capture-error`),n.phase=`done`,a8(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}const p8=r(`playwright`),m8=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`goto requires a URL
|
|
6529
|
+
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};await e.withTab(a.targetId,async()=>(await e.navigate(r[0]),!0)),n.snapshots.delete(a.targetId);let o=i[`teleport-start`],s=i[`teleport-return`];if(o&&s){p8.info(`Arming teleport via goto/navigate flags`),p8.debug(`Arming teleport via goto/navigate flags details`,{targetId:a.targetId,startPattern:o,returnPattern:s});let t,c;try{t=new RegExp(o)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-start: ${o}\n`,exitCode:1}}try{c=new RegExp(s)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-return: ${s}\n`,exitCode:1}}let l=i.timeout?parseInt(i.timeout,10):300,u=n.teleportWatchers.get(a.targetId);u&&(a8(u),n.teleportWatchers.delete(a.targetId)),o8(e,n,t,c,l*1e3,i[`teleport-runtime`],r[0],a.targetId)}if(i.discover===`true`){let{browseShWarning:e,...n}=await p6(r[0],{discover:!0,fs:t}),i={action:`navigate`,targetId:a.targetId,source:`auxiliary-fetch`,...n};return{stdout:JSON.stringify(i,null,2)+`
|
|
6530
|
+
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Navigated to ${r[0]}\n`,stderr:``,exitCode:0}},h8=async({browser:e,state:t,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`history.back()`)}),t.snapshots.delete(r.targetId),{stdout:`Navigated back
|
|
6531
|
+
`,stderr:``,exitCode:0})},g8=async({browser:e,state:t,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`history.forward()`)}),t.snapshots.delete(r.targetId),{stdout:`Navigated forward
|
|
6532
|
+
`,stderr:``,exitCode:0})},_8=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{await e.sendCDP(`Page.reload`)}),{stdout:`Reloaded
|
|
6533
|
+
`,stderr:``,exitCode:0})},v8=async({browser:e,flags:t,positional:n})=>{let r=Q(t);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n[0];return i!==`online`&&i!==`offline`?{stdout:``,stderr:`network-state-set requires "online" or "offline"
|
|
6534
|
+
`,exitCode:1}:(await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Network.enable`,{},t),await n.send(`Network.emulateNetworkConditions`,{offline:i===`offline`,latency:0,downloadThroughput:-1,uploadThroughput:-1},t)}),{stdout:`Network set to ${i}\n`,stderr:``,exitCode:0})},y8=[`image/`,`font/`,`text/css`,`application/javascript`,`text/javascript`];function b8(e,t){if(e&&y8.some(t=>e.startsWith(t)))return!0;try{let e=new URL(t).pathname;return/\.(png|jpe?g|gif|webp|svg|ico|woff2?|ttf|eot|otf|css|js|mjs)$/i.test(e)}catch{return!1}}function x8(e,t,n,r){if(e.networkCleanup.has(n))return;e.networkRequests.set(n,[]),e.networkRequestIndex.set(n,new Map);let i=1,a=t=>{if(t.sessionId!==r)return;let a=t.requestId,o=t.request;if(!o)return;let s=e.networkRequests.get(n),c=e.networkRequestIndex.get(n);if(!s||!c)return;let l=o.url??``,u={index:i++,requestId:a,method:o.method??`GET`,url:l,requestHeaders:o.headers??{},requestBody:o.postData==null?null:String(o.postData),status:null,responseHeaders:null,responseBody:null,mimeType:null,isStatic:b8(null,l),timestamp:Date.now()};if(s.push(u),c.set(a,u),s.length>500){let e=s.splice(0,s.length-500);for(let t of e)c.delete(t.requestId)}},o=t=>{if(t.sessionId!==r)return;let i=t.requestId,a=t.response;if(!a)return;let o=e.networkRequestIndex.get(n)?.get(i);o&&(o.status=a.status??null,o.responseHeaders=a.headers??null,o.mimeType=a.mimeType??null,o.isStatic=b8(o.mimeType,o.url))},s=i=>{if(i.sessionId!==r)return;let a=i.requestId,o=e.networkRequestIndex.get(n)?.get(a);!o||o.isStatic||o.responseBody!==null||t.send(`Network.getResponseBody`,{requestId:a},r).then(e=>{let t=e;t&&(o.responseBody=t.body??null)}).catch(()=>{})};t.on(`Network.requestWillBeSent`,a),t.on(`Network.responseReceived`,o),t.on(`Network.loadingFinished`,s),e.networkCleanup.set(n,()=>{t.off(`Network.requestWillBeSent`,a),t.off(`Network.responseReceived`,o),t.off(`Network.loadingFinished`,s)})}function S8(e,t,n){let r=parseInt(n,10);return!Number.isFinite(r)||r<1?null:(e.networkRequests.get(t)??[]).find(e=>e.index===r)??null}const C8=async({browser:e,state:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};t.networkCleanup.has(r.targetId)||await e.withTab(r.targetId,async n=>{let i=e.getTransport();await i.send(`Network.enable`,{},n),x8(t,i,r.targetId,n)});let i=n.static===`true`,a=n.filter,o=n.clear===`true`,s=t.networkRequests.get(r.targetId)??[];if(i||(s=s.filter(e=>!e.isStatic)),a){let e;try{e=new RegExp(a)}catch{return{stdout:``,stderr:`Invalid filter regex: ${a}\n`,exitCode:1}}s=s.filter(t=>e.test(t.url))}return o&&(t.networkRequests.set(r.targetId,[]),t.networkRequestIndex.set(r.targetId,new Map)),s.length===0?{stdout:`No requests
|
|
6535
6535
|
`,stderr:``,exitCode:0}:{stdout:s.map(e=>`${e.index} ${e.method} ${e.url} → ${e.status??`pending`}`).join(`
|
|
6536
6536
|
`)+`
|
|
6537
|
-
`,stderr:``,exitCode:0}},
|
|
6537
|
+
`,stderr:``,exitCode:0}},w8=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),x8(t,r,a.targetId,n)});let o=n[0]??``,s=S8(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};let c=[`Method: ${s.method}`,`URL: ${s.url}`,`Status: ${s.status??`pending`}`,``,`Request Headers:`,...Object.entries(s.requestHeaders).map(([e,t])=>` ${e}: ${t}`)];if(s.requestBody!==null&&c.push(``,`Request Body: ${s.requestBody}`),s.responseHeaders!==null&&(c.push(``,`Response Headers:`),c.push(...Object.entries(s.responseHeaders).map(([e,t])=>` ${e}: ${t}`))),s.responseBody!==null){let e=s.responseBody,t=e.length>4096?e.slice(0,4096)+`
|
|
6538
6538
|
... (truncated)`:e;c.push(``,`Response Body:\n${t}`)}let l=c.join(`
|
|
6539
6539
|
`)+`
|
|
6540
|
-
`,u=r.filename;return u?(await i.writeFile(u,l),{stdout:`Saved to ${u}\n`,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}},
|
|
6540
|
+
`,u=r.filename;return u?(await i.writeFile(u,l),{stdout:`Saved to ${u}\n`,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}},T8=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),x8(t,r,a.targetId,n)});let o=n[0]??``,s=S8(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};let c=Object.entries(s.requestHeaders).map(([e,t])=>`${e}: ${t}`).join(`
|
|
6541
6541
|
`)+`
|
|
6542
|
-
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},
|
|
6542
|
+
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},E8=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),x8(t,r,a.targetId,n)});let o=n[0]??``,s=S8(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.requestBody===null)return{stdout:`(no request body)
|
|
6543
6543
|
`,stderr:``,exitCode:0};let c=r.filename;return c?(await i.writeFile(c,s.requestBody),{stdout:`Saved to ${c}\n`,stderr:``,exitCode:0}):{stdout:s.requestBody+`
|
|
6544
|
-
`,stderr:``,exitCode:0}},
|
|
6544
|
+
`,stderr:``,exitCode:0}},D8=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),x8(t,r,a.targetId,n)});let o=n[0]??``,s=S8(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.responseHeaders===null)return{stdout:`(response not yet received)
|
|
6545
6545
|
`,stderr:``,exitCode:0};let c=Object.entries(s.responseHeaders).map(([e,t])=>`${e}: ${t}`).join(`
|
|
6546
6546
|
`)+`
|
|
6547
|
-
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},
|
|
6547
|
+
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},O8=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),x8(t,r,a.targetId,n)});let o=n[0]??``,s=S8(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.responseBody===null)return{stdout:`(response body not yet available)
|
|
6548
6548
|
`,stderr:``,exitCode:0};let c=r.filename,l=s.mimeType!==null&&!s.mimeType.startsWith(`text/`)&&!s.mimeType.includes(`json`)&&!s.mimeType.includes(`javascript`)&&!s.mimeType.includes(`xml`);if(c){if(l)try{let e=atob(s.responseBody),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);await i.writeFile(c,t)}catch{await i.writeFile(c,s.responseBody)}else await i.writeFile(c,s.responseBody);return{stdout:`Saved to ${c}\n`,stderr:``,exitCode:0}}if(l)try{return{stdout:`[binary body, ${atob(s.responseBody).length} bytes]\n`,stderr:``,exitCode:0}}catch{}let u=s.responseBody;return{stdout:(u.length>4096?u.slice(0,4096)+`
|
|
6549
6549
|
... (truncated)`:u)+`
|
|
6550
|
-
`,stderr:``,exitCode:0}},
|
|
6551
|
-
`)){c.push(u);let t=u.match(/^(\s*)- iframe\s/);if(!t)continue;let d=u.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=
|
|
6552
|
-
`)}catch{return t}}async function G8(e,t){let n=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:r,title:i}=JSON.parse(n),a=await e.getAccessibilityTree(),o=new Map,s=new Map,c=new Map,l=
|
|
6553
|
-
`);return t?.noIframes||(l=await
|
|
6554
|
-
`)}}const
|
|
6555
|
-
`,exitCode:1};let n=t[0];return e.harRecorder?{stdout:`Recording stopped. HAR files saved to ${await e.harRecorder.stopRecording(n)}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Recording not found: ${n}\n`,exitCode:1}},K8=r(`playwright-route`);function
|
|
6556
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o={pattern:a,regex:
|
|
6550
|
+
`,stderr:``,exitCode:0}},k8=r(`har-recorder`);var A8=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}`),k8.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=>{k8.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 j8(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return k8.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 k8.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)),k8.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 k8.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 j8(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){k8.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return k8.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const M8=r(`playwright`);function N8(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function P8(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}const F8=[`none`,`presentation`,`generic`,`rootwebarea`],I8=[`textbox`,`button`,`link`,`checkbox`,`radio`];function L8(e,t){return F8.includes(e)?!1:!!t||I8.includes(e)}function R8(e,t){let n=P8(t);return e===`button`&&t?[`button[aria-label="${n}"]`,`button[title="${n}"]`,`[role="button"][aria-label="${n}"]`,`[role="button"][title="${n}"]`,`input[type="button"][value="${n}"]`,`input[type="submit"][value="${n}"]`,`input[type="reset"][value="${n}"]`].join(`, `):e===`link`&&t?`a[aria-label="${n}"], a[title="${n}"], [role="link"][aria-label="${n}"], [role="link"][title="${n}"]`:e===`textbox`?t?`input[aria-label="${n}"], textarea[aria-label="${n}"], [contenteditable][aria-label="${n}"], input[placeholder="${n}"], textarea[placeholder="${n}"], [contenteditable][placeholder="${n}"], input[title="${n}"], textarea[title="${n}"], [contenteditable][title="${n}"]`:`input, textarea, [contenteditable]`:e===`checkbox`?`input[type="checkbox"]`:e===`radio`?`input[type="radio"]`:t?`[aria-label="${n}"], [title="${n}"]`:`[role="${e}"]`}function z8(e,t,n,r,i=``,a=``){let o=[],s=Un(e.role,`unknown`).toLowerCase(),c=Un(e.name),l=Un(e.value),u=``;L8(s,c)&&(u=a+`e${++r.value}`,e.backendNodeId&&n.set(u,e.backendNodeId),t.set(u,R8(s,c)));let d=`${i}- ${s}`;if(c&&(d+=` "${N8(c)}"`),u&&(d+=` [ref=${u}]`),l&&(d+=`: "${N8(l)}"`),o.push(d),e.children)for(let s of e.children)o.push(...z8(s,t,n,r,i+` `,a));return o}async function B8(e,t){if(t.appTabId)return;let n=await e.listPages(),r=await V8(),i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}async function V8(){if(typeof window<`u`)return window.location.origin;let e=i();if(e)try{let t=await e.call(`page-info`,void 0,{timeoutMs:2e3});if(t.origin)return t.origin}catch{}return`http://localhost:5710`}function H8(e,t){return t===e.appTabId}function fre(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function pre(e,t){return!H8(e,t.targetId)&&!fre(t)}function mre(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function U8(e,t){await B8(e,t);let n;if(typeof e.listAllTargets==`function`){n=await e.listAllTargets();let t=mre()?i():null;if(t)try{let{targets:e}=await t.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(n.map(e=>e.targetId));for(let t of e)r.has(t.targetId)||(r.add(t.targetId),n.push({targetId:t.targetId,title:t.title,url:t.url}))}catch(e){M8.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}}else n=await e.listPages();return n.filter(e=>pre(t,e))}function W8(e,t){try{let n=new URL(e,t);return n.origin+n.pathname.replace(/\/$/,``)+n.search}catch{return null}}function hre(e,t,n,r){let i=W8(t,n);return e.find(e=>{if(r.has(e.frameId))return!1;let n=W8(e.url);return n!==null&&i!==null?n===i:e.url===t})}async function gre(e,t,n,r,i,a,o){try{let s=await e.getAccessibilityTreeForFrame(t),c=new Map,l=new Map,u=z8(s,c,l,{value:0},n,r);for(let[e,n]of c)i.set(e,n),o.set(e,t);for(let[e,n]of l)a.set(e,n),o.set(e,t);return u}catch{return[]}}async function _re(e,t,n,r,i,a){if(typeof e.getFrameTree!=`function`)return t;try{let o=(await e.getFrameTree()).filter(e=>e.parentFrameId);if(o.length===0)return t;let s=0,c=[],l=new Set;for(let u of t.split(`
|
|
6551
|
+
`)){c.push(u);let t=u.match(/^(\s*)- iframe\s/);if(!t)continue;let d=u.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=hre(o,d[1],n,l);f&&(l.add(f.frameId),s++,c.push(...await gre(e,f.frameId,t[1]+` `,`f${s}`,r,i,a)))}return c.join(`
|
|
6552
|
+
`)}catch{return t}}async function G8(e,t){let n=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:r,title:i}=JSON.parse(n),a=await e.getAccessibilityTree(),o=new Map,s=new Map,c=new Map,l=z8(a,o,s,{value:0}).join(`
|
|
6553
|
+
`);return t?.noIframes||(l=await _re(e,l,r,o,s,c)),{url:r,title:i,text:l,refToSelector:o,refToBackendNodeId:s,refToFrameId:c}}async function vre(e,t,n,r){await e.attachToPage(n);let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:l}=await G8(e,r),u={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:l,content:o,timestamp:Date.now()};return t.snapshots.set(n,u),{snapshot:u,output:[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
6554
|
+
`)}}const yre=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=r[0]||`about:blank`,o=i.filter;await B8(e,n);let s=await e.createPage(a),c=e.getTransport(),l=(await c.send(`Target.attachToTarget`,{targetId:s,flatten:!0})).sessionId;n.harRecorder||=new A8(c,t);let u=await n.harRecorder.startRecording(s,l,o);return{stdout:`Recording started (targetId: ${s}, recordingId: ${u}) at ${a}\nHAR saved to /recordings/${u}/\n`,stderr:``,exitCode:0}},bre=async({state:e,positional:t})=>{if(t.length===0)return{stdout:``,stderr:`stop-recording requires a recordingId
|
|
6555
|
+
`,exitCode:1};let n=t[0];return e.harRecorder?{stdout:`Recording stopped. HAR files saved to ${await e.harRecorder.stopRecording(n)}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Recording not found: ${n}\n`,exitCode:1}},K8=r(`playwright-route`);function xre(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 Sre(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`@@`).replace(/\*/g,`[^/]*`).replace(/@@/g,`.*`);return RegExp(`^${t}$`)}async function Cre(e,t,n){await e.withTab(n,async r=>{let i=e.getTransport();await i.send(`Fetch.enable`,{patterns:[{urlPattern:`*`,requestStage:`Request`}]},r);let a=async e=>{if(e.sessionId!==r)return;let{requestId:a,request:o}=e,s=(t.routes.get(n)??[]).find(e=>e.regex.test(o.url));if(!s){await i.send(`Fetch.continueRequest`,{requestId:a},r).catch(e=>{K8.warn(`Fetch.continueRequest failed — intercepted request may hang`,{requestId:a,err:e})});return}let c=[{name:`Content-Type`,value:s.contentType},...Object.entries(s.headers).map(([e,t])=>({name:e,value:t}))];await i.send(`Fetch.fulfillRequest`,{requestId:a,responseCode:s.status,responseHeaders:c,body:s.body?xre(s.body):void 0},r).catch(e=>{K8.warn(`Fetch.fulfillRequest failed`,{requestId:a,url:o.url,err:e})})};t.routeCleanup.set(n,()=>{i.off(`Fetch.requestPaused`,a),i.send(`Fetch.disable`,{},r).catch(()=>void 0)}),i.on(`Fetch.requestPaused`,a)})}const wre=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`route requires a URL pattern
|
|
6556
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o={pattern:a,regex:Sre(a),status:r.status?parseInt(r.status,10):200,body:r.body??``,contentType:r[`content-type`]??`text/plain`,headers:{}};if(r.header){r.header.includes(`,`)&&K8.warn(`--header value contains comma — only last segment used. Use separate route calls for multiple headers.`);for(let e of r.header.split(`,`)){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();o.headers[n]=r}}}t.routeCleanup.has(i.targetId)||(t.routes.has(i.targetId)||t.routes.set(i.targetId,[]),await Cre(e,t,i.targetId));let s=t.routes.get(i.targetId)??[];return s.unshift(o),t.routes.set(i.targetId,s),{stdout:`Route added: ${a}\n`,stderr:``,exitCode:0}},Tre=async({state:e,flags:t})=>{let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};let r=e.routes.get(n.targetId)??[];return r.length===0?{stdout:`No active routes
|
|
6557
6557
|
`,stderr:``,exitCode:0}:{stdout:r.map((e,t)=>`${t+1}. ${e.pattern} → ${e.status} ${e.contentType}`).join(`
|
|
6558
6558
|
`)+`
|
|
6559
|
-
`,stderr:``,exitCode:0}},
|
|
6560
|
-
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function q8(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!
|
|
6561
|
-
`),f=`/.playwright/snapshots/page-${
|
|
6559
|
+
`,stderr:``,exitCode:0}},Ere=async({state:e,positional:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];if(!i){e.routes.set(r.targetId,[]);let t=e.routeCleanup.get(r.targetId);return t&&(t(),e.routeCleanup.delete(r.targetId)),{stdout:`All routes removed
|
|
6560
|
+
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function q8(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!R3(e))throw e}t.sessionDirsCreated=!0}}async function Dre(e,t,n,r){try{return await e.withTab(n,async()=>{let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:l}=await G8(e),u={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:l,content:o,timestamp:Date.now()};r.snapshots.set(n,u);let d=[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
6561
|
+
`),f=`/.playwright/snapshots/page-${L3(new Date)}.yml`;return await t.writeFile(f,d),f})}catch{return null}}async function Ore(e,t,n){await q8(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
|
|
6562
6562
|
`)+`
|
|
6563
|
-
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}async function
|
|
6563
|
+
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}async function kre(e,t){let n=e.getTransport(),r=e.getSessionId();await n.send(`DOM.enable`,{},r),await n.send(`Runtime.enable`,{},r);let i=(await n.send(`DOM.resolveNode`,{backendNodeId:t},r)).object;if(i?.objectId)return(await n.send(`Runtime.callFunctionOn`,{objectId:i.objectId,functionDeclaration:`function() {
|
|
6564
6564
|
this.scrollIntoView({ block: 'center' });
|
|
6565
6565
|
const r = this.getBoundingClientRect();
|
|
6566
6566
|
return { x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height };
|
|
6567
|
-
}`,returnByValue:!0},r)).result?.value}async function
|
|
6567
|
+
}`,returnByValue:!0},r)).result?.value}async function Are(e,t){let n=await e.evaluate(`(function() {
|
|
6568
6568
|
const el = document.querySelector(${JSON.stringify(t.split(`,`)[0].trim())});
|
|
6569
6569
|
if (!el) return null;
|
|
6570
6570
|
el.scrollIntoView({ block: 'center' });
|
|
6571
6571
|
const r = el.getBoundingClientRect();
|
|
6572
6572
|
return JSON.stringify({ x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height });
|
|
6573
|
-
})()`);return n?JSON.parse(n):void 0}async function
|
|
6574
|
-
`,stderr:``,exitCode:0}},
|
|
6573
|
+
})()`);return n?JSON.parse(n):void 0}async function jre(e,t,n){let r=t.refToBackendNodeId.get(n);if(r)return kre(e,r);let i=t.refToSelector.get(n);if(!i)throw Error(`Unknown ref "${n}"`);return Are(e,i)}const Mre=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};r[0];let o=i[`no-iframes`]===`true`;i.depth&&parseInt(i.depth,10),i.boxes;let{output:s}=await e.withTab(a.targetId,async()=>await vre(e,n,a.targetId,{noIframes:o}));return i.filename?(await t.writeFile(i.filename,s),{stdout:`Snapshot saved to ${i.filename}\n`,stderr:``,exitCode:0}):{stdout:s+`
|
|
6574
|
+
`,stderr:``,exitCode:0}},Nre=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:{stdout:await e.withTab(n.targetId,async()=>`Frames in current tab:\n${(await e.getFrameTree()).map(e=>{let t=e.parentFrameId?`child`:`main`,n=e.parentFrameId?` (parent: ${e.parentFrameId})`:``;return` [${t}] ${e.frameId}${n} - ${e.url}`}).join(`
|
|
6575
6575
|
`)}`)+`
|
|
6576
|
-
`,stderr:``,exitCode:0}},
|
|
6577
|
-
`,exitCode:1}:{stdout:``,stderr:`pdf: ${t}\n`,exitCode:1}}return{stdout:`Saved PDF to ${i}\n`,stderr:``,exitCode:0}},
|
|
6578
|
-
`,stderr:o,exitCode:0}},
|
|
6576
|
+
`,stderr:``,exitCode:0}},Pre=async({browser:e,fs:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n.filename||`/tmp/page-${L3(new Date)}.pdf`;try{await e.withTab(r.targetId,async n=>{let r=(await e.getTransport().send(`Page.printToPDF`,{},n)).data,a=F3(r);await t.writeFile(i,a)})}catch(e){let t=e instanceof Error?e.message:String(e);return ce()?{stdout:``,stderr:`pdf: not available in extension mode — use screenshot --full-page
|
|
6577
|
+
`,exitCode:1}:{stdout:``,stderr:`pdf: ${t}\n`,exitCode:1}}return{stdout:`Saved PDF to ${i}\n`,stderr:``,exitCode:0}},Fre=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=``;return{stdout:await e.withTab(a.targetId,async()=>{let s;if(r[0]?.startsWith(`e`)){let t=n.snapshots.get(a.targetId);if(!t)throw Error(`No snapshot available. Run "snapshot" first.`);s=await jre(e,t,r[0]),s||(o+=`Warning: could not clip to element ${r[0]}, capturing full viewport\n`)}let c=i[`max-width`]?parseInt(i[`max-width`],10):void 0,l=await e.screenshot({fullPage:i.fullPage===`true`||i[`full-page`]===`true`,...s?{clip:s}:{},...c?{maxWidth:c}:{}}),u=i.filename||`/tmp/screenshot-${Date.now()}.png`,d=F3(l);await t.writeFile(u,d);try{await q8(t,n);let e=`/.playwright/screenshots/screenshot-${L3(new Date)}.png`;await t.writeFile(e,d)}catch{}return`Screenshot saved to ${u} (${Math.round(d.length/1024)} KB)`})+`
|
|
6578
|
+
`,stderr:o,exitCode:0}},Ire=async({browser:e,fs:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=r.filename??n[0]??`/.playwright/storage-state.json`,o=[],s=[],c=``;o=(await e.sendCDP(`Network.getCookies`)).cookies??[],await e.withTab(i.targetId,async t=>{let n=e.getTransport();c=(await n.send(`Runtime.evaluate`,{expression:`location.origin`,returnByValue:!0},t)).result.value??``;let r=(await n.send(`Runtime.evaluate`,{expression:`JSON.stringify(Object.entries(localStorage).map(([name,value])=>({name,value})))`,returnByValue:!0},t)).result.value??`[]`;s=JSON.parse(r)});let l=JSON.stringify({cookies:o,origins:c?[{origin:c,localStorage:s}]:[]},null,2);return await t.writeFile(a,l),{stdout:`Saved storage state to ${a}\n`,stderr:``,exitCode:0}},Lre=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`state-load requires a filename
|
|
6579
6579
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o;try{let e=await t.readTextFile(a);o=JSON.parse(e)}catch{return{stdout:``,stderr:`Failed to read storage state from ${a}\n`,exitCode:1}}o.cookies?.length&&await e.sendCDP(`Network.setCookies`,{cookies:o.cookies});let s=[];o.origins?.length&&await e.withTab(i.targetId,async t=>{let n=e.getTransport(),r=(await n.send(`Runtime.evaluate`,{expression:`location.origin`,returnByValue:!0},t)).result.value??``,i=o.origins.filter(e=>e.origin===r);s=o.origins.filter(e=>e.origin!==r);for(let{localStorage:e}of i){let r=`(function() {
|
|
6580
6580
|
var items = ${JSON.stringify(e)};
|
|
6581
6581
|
for (var i = 0; i < items.length; i++) {
|
|
@@ -6584,25 +6584,25 @@ Options:
|
|
|
6584
6584
|
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}});let c=``;return s.length>0&&(c=`Skipped localStorage for non-matching origins: ${s.map(e=>e.origin).join(`, `)}\n`),{stdout:`Loaded storage state from ${a}\n`,stderr:c,exitCode:0}};function J8(e,t){return{list:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:{stdout:await e.withTab(r.targetId,async()=>{let n=await e.evaluate(`JSON.stringify(Object.entries(${t}))`),r=JSON.parse(n);return r.length===0?`No ${t} entries`:r.map(([e,t])=>`${e}=${t}`).join(`
|
|
6585
6585
|
`)})+`
|
|
6586
6586
|
`,stderr:``,exitCode:0}},get:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-get requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:{stdout:await n.withTab(a.targetId,async()=>{let e=await n.evaluate(`${t}.getItem(${JSON.stringify(r[0])})`);if(e===null)throw Error(`Key "${r[0]}" not found in ${t}`);return e})+`
|
|
6587
|
-
`,stderr:``,exitCode:0}},set:async({browser:n,positional:r,flags:i})=>{if(r.length<2)return{stdout:``,stderr:`${e}-set requires <key> <value>\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.setItem(${JSON.stringify(r[0])}, ${JSON.stringify(r.slice(1).join(` `))})`)}),{stdout:`${t} "${r[0]}" set\n`,stderr:``,exitCode:0})},del:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-delete requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.removeItem(${JSON.stringify(r[0])})`)}),{stdout:`${t} "${r[0]}" deleted\n`,stderr:``,exitCode:0})},clear:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`${t}.clear()`)}),{stdout:`${t} cleared\n`,stderr:``,exitCode:0})}}}const Y8=J8(`localstorage`,`localStorage`),X8=J8(`sessionstorage`,`sessionStorage`),Z8=r(`playwright`),Q8=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=r[0]||`about:blank`,o=i.runtime;await
|
|
6588
|
-
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Opened ${a} in new tab [targetId: ${s}]\n`,stderr:``,exitCode:0}},
|
|
6587
|
+
`,stderr:``,exitCode:0}},set:async({browser:n,positional:r,flags:i})=>{if(r.length<2)return{stdout:``,stderr:`${e}-set requires <key> <value>\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.setItem(${JSON.stringify(r[0])}, ${JSON.stringify(r.slice(1).join(` `))})`)}),{stdout:`${t} "${r[0]}" set\n`,stderr:``,exitCode:0})},del:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-delete requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.removeItem(${JSON.stringify(r[0])})`)}),{stdout:`${t} "${r[0]}" deleted\n`,stderr:``,exitCode:0})},clear:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`${t}.clear()`)}),{stdout:`${t} cleared\n`,stderr:``,exitCode:0})}}}const Y8=J8(`localstorage`,`localStorage`),X8=J8(`sessionstorage`,`sessionStorage`),Z8=r(`playwright`),Q8=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=r[0]||`about:blank`,o=i.runtime;await B8(e,n);let s;if(s=o?await e.createRemotePage(o,a):await e.createPage(a),i.foreground===`true`||i.fg===`true`)try{await e.withTab(s,async t=>{await e.getTransport().send(`Page.bringToFront`,{},t)})}catch(e){Z8.debug(`open/tab-new --foreground bringToFront failed`,{targetId:s,error:e instanceof Error?e.message:String(e)})}let c=i[`teleport-start`],l=i[`teleport-return`];if(c&&l){Z8.info(`Arming teleport via open/tab-new flags`),Z8.debug(`Arming teleport via open/tab-new flags details`,{targetId:s,startPattern:c,returnPattern:l});let t,r;try{t=new RegExp(c)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-start: ${c}\n`,exitCode:1}}try{r=new RegExp(l)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-return: ${l}\n`,exitCode:1}}let o=i.timeout?parseInt(i.timeout,10):300,u=n.teleportWatchers.get(s);u&&(a8(u),n.teleportWatchers.delete(s)),o8(e,n,t,r,o*1e3,i[`teleport-runtime`],a,s)}if(i.discover===`true`){let{browseShWarning:e,...n}=await p6(a,{discover:!0,fs:t}),r={action:`open`,targetId:s,source:`auxiliary-fetch`,...n};return{stdout:JSON.stringify(r,null,2)+`
|
|
6588
|
+
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Opened ${a} in new tab [targetId: ${s}]\n`,stderr:``,exitCode:0}},Rre=async({browser:e,state:t})=>{let n=await U8(e,t);return n.length===0?{stdout:`No tabs open
|
|
6589
6589
|
`,stderr:``,exitCode:0}:{stdout:n.map(e=>{let t=!!e.active,n=e.targetId.includes(`:`),r=t?` (active)`:``,i=n?` [remote:${e.targetId.substring(0,e.targetId.indexOf(`:`))}]`:``;return`[${e.targetId}] ${e.url} "${e.title}"${r}${i}`}).join(`
|
|
6590
6590
|
`)+`
|
|
6591
|
-
`,stderr:``,exitCode:0}},$8=async({browser:e,state:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};await e.closePage(r.targetId),t.snapshots.delete(r.targetId),t.teleportWatchers.delete(r.targetId),t.consoleMessages.delete(r.targetId);let i=t.consoleCleanup.get(r.targetId);i&&(i(),t.consoleCleanup.delete(r.targetId)),t.networkRequests.delete(r.targetId);let a=t.networkCleanup.get(r.targetId);a&&(a(),t.networkCleanup.delete(r.targetId));let o=t.routeCleanup.get(r.targetId);return o&&(o(),t.routeCleanup.delete(r.targetId)),t.routes.delete(r.targetId),t.lastMousePosition.delete(r.targetId),{stdout:`Closed tab ${r.targetId}\n`,stderr:``,exitCode:0}},
|
|
6591
|
+
`,stderr:``,exitCode:0}},$8=async({browser:e,state:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};await e.closePage(r.targetId),t.snapshots.delete(r.targetId),t.teleportWatchers.delete(r.targetId),t.consoleMessages.delete(r.targetId);let i=t.consoleCleanup.get(r.targetId);i&&(i(),t.consoleCleanup.delete(r.targetId)),t.networkRequests.delete(r.targetId);let a=t.networkCleanup.get(r.targetId);a&&(a(),t.networkCleanup.delete(r.targetId));let o=t.routeCleanup.get(r.targetId);return o&&(o(),t.routeCleanup.delete(r.targetId)),t.routes.delete(r.targetId),t.lastMousePosition.delete(r.targetId),{stdout:`Closed tab ${r.targetId}\n`,stderr:``,exitCode:0}},zre=async({browser:e,state:t,positional:n})=>{if(n.length===0)return{stdout:``,stderr:`tab-select requires a tab index
|
|
6592
6592
|
`,exitCode:1};let r=n[0];if(!/^[0-9]+$/.test(r))return{stdout:``,stderr:`tab-select index must be a positive integer
|
|
6593
6593
|
`,exitCode:1};let i=parseInt(r,10);if(i<1)return{stdout:``,stderr:`tab-select index must be a positive integer
|
|
6594
|
-
`,exitCode:1};let a=await U8(e,t);if(i>a.length)return{stdout:``,stderr:`tab-select index ${i} out of range (${a.length} tab${a.length===1?``:`s`} open)\n`,exitCode:1};let o=a[i-1].targetId;return await e.withTab(o,async t=>{await e.getTransport().send(`Page.bringToFront`,{},t)}),{stdout:`Selected tab ${i} [targetId: ${o}]\n`,stderr:``,exitCode:0}},
|
|
6594
|
+
`,exitCode:1};let a=await U8(e,t);if(i>a.length)return{stdout:``,stderr:`tab-select index ${i} out of range (${a.length} tab${a.length===1?``:`s`} open)\n`,exitCode:1};let o=a[i-1].targetId;return await e.withTab(o,async t=>{await e.getTransport().send(`Page.bringToFront`,{},t)}),{stdout:`Selected tab ${i} [targetId: ${o}]\n`,stderr:``,exitCode:0}},Bre=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`resize requires <width> <height>
|
|
6595
6595
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseInt(n[0],10),o=parseInt(n[1],10);return isNaN(a)||isNaN(o)||a<=0||o<=0?{stdout:``,stderr:`resize requires positive integer width and height
|
|
6596
|
-
`,exitCode:1}:(await e.withTab(i.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Emulation.setDeviceMetricsOverride`,{width:a,height:o,deviceScaleFactor:1,mobile:!1},n)}),t.snapshots.delete(i.targetId),{stdout:`Resized viewport to ${a}x${o}\n`,stderr:``,exitCode:0})},e5=r(`playwright-teleport`);function
|
|
6596
|
+
`,exitCode:1}:(await e.withTab(i.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Emulation.setDeviceMetricsOverride`,{width:a,height:o,deviceScaleFactor:1,mobile:!1},n)}),t.snapshots.delete(i.targetId),{stdout:`Resized viewport to ${a}x${o}\n`,stderr:``,exitCode:0})},e5=r(`playwright-teleport`);function Vre(){e5.info(`Listing available follower runtimes`);let e=r8();if(!e)return{stdout:``,stderr:`teleport: not connected to a tray
|
|
6597
6597
|
`,exitCode:1};let t=e();if(t.length===0)return{stdout:`No followers connected to the tray.
|
|
6598
6598
|
`,stderr:``,exitCode:0};let n=[`Available runtimes for teleport:`];for(let e of t){let t=[e.runtimeId];if(e.floatType&&t.push(`[${e.floatType}]`),e.runtime&&t.push(`(${e.runtime})`),e.lastActivity){let n=Math.round((Date.now()-e.lastActivity)/1e3);t.push(`active ${n}s ago`)}n.push(` ${t.join(` `)}`)}return{stdout:n.join(`
|
|
6599
6599
|
`)+`
|
|
6600
|
-
`,stderr:``,exitCode:0}}function
|
|
6601
|
-
`,stderr:``,exitCode:0}}function
|
|
6602
|
-
`,exitCode:1};let o=
|
|
6603
|
-
`,exitCode:1};let c=n.runtime;if(c){let e=
|
|
6600
|
+
`,stderr:``,exitCode:0}}function Hre({state:e,flags:t}){let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};e5.info(`Disarming teleport watcher via --off`,{targetId:n.targetId});let r=e.teleportWatchers.get(n.targetId);return r&&(a8(r),e.teleportWatchers.delete(n.targetId)),{stdout:`Teleport watcher disarmed
|
|
6601
|
+
`,stderr:``,exitCode:0}}function Ure(e,t){let n,r;try{n=new RegExp(e)}catch{return{error:`Invalid regex for --start: ${e}\n`}}try{r=new RegExp(t)}catch{return{error:`Invalid regex for --return: ${t}\n`}}return{startPattern:n,returnPattern:r}}function Wre(e){return(r8()?.()??[]).find(t=>t.runtimeId===e)?.runtime===`slicc-cherry`?`teleport: runtime ${e} is a cherry host and cannot serve a cookie teleport (no Network.* access)\n`:null}async function Gre({browser:e,state:t,flags:n}){let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n.start||n[`teleport-start`],a=n.return||n[`teleport-return`];if(!i||!a)return{stdout:``,stderr:`teleport requires --start <regex> and --return <regex>
|
|
6602
|
+
`,exitCode:1};let o=Ure(i,a);if(`error`in o)return{stdout:``,stderr:o.error,exitCode:1};let s=n.timeout?parseInt(n.timeout,10):300;if(isNaN(s)||s<=0)return{stdout:``,stderr:`--timeout must be a positive number
|
|
6603
|
+
`,exitCode:1};let c=n.runtime;if(c){let e=Wre(c);if(e)return{stdout:``,stderr:e,exitCode:1}}let l=t.teleportWatchers.get(r.targetId);l&&(e5.info(`Disarming existing teleport watcher before re-arming`,{targetId:r.targetId}),a8(l),t.teleportWatchers.delete(r.targetId));let u;try{await e.attachToPage(r.targetId);let t=await e.evaluate(`window.location.href`);u=typeof t==`string`?t:String(t)}catch{}return e5.info(`Arming teleport via explicit subcommand`,{targetId:r.targetId,timeoutSec:s,runtimeSelection:c?`explicit`:`auto`}),e5.debug(`Arming teleport via explicit subcommand details`,{targetId:r.targetId,startPattern:i,returnPattern:a,timeoutSec:s,runtimeId:c??`auto`,leaderUrl:u}),o8(e,t,o.startPattern,o.returnPattern,s*1e3,c,u,r.targetId),{stdout:`Teleport armed on tab ${r.targetId}. Will trigger when URL matches ${i}\n`,stderr:``,exitCode:0}}const Kre=async e=>e.flags.list===`true`?Vre():e.flags.off===`true`?Hre(e):Gre(e),qre={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,pdf:`application/pdf`,txt:`text/plain`,json:`application/json`,csv:`text/csv`,html:`text/html`,htm:`text/html`,xml:`application/xml`,zip:`application/zip`,mp4:`video/mp4`,mp3:`audio/mpeg`};function Jre(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return qre[t]??`application/octet-stream`}function Yre(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const Xre=new Map([[`teleport`,Kre],[`open`,Q8],[`tab-new`,Q8],[`fetch`,m6],[`goto`,m8],[`navigate`,m8],[`snapshot`,Mre],[`frames`,Nre],[`screenshot`,Fre],[`click`,b6],[`type`,x6],[`fill`,S6],[`eval`,c6],[`eval-file`,l6],[`press`,C6],[`keydown`,w6],[`keyup`,T6],[`go-back`,h8],[`go-forward`,g8],[`reload`,_8],[`tab-list`,Rre],[`tab-close`,$8],[`close`,$8],[`dblclick`,E6],[`hover`,D6],[`select`,O6],[`check`,k6],[`uncheck`,A6],[`drag`,j6],[`resize`,Bre],[`dialog-accept`,r6],[`dialog-dismiss`,i6],[`cookie-list`,X3],[`cookie-get`,Z3],[`cookie-set`,Q3],[`cookie-delete`,$3],[`cookie-clear`,e6],[`localstorage-list`,Y8.list],[`localstorage-get`,Y8.get],[`localstorage-set`,Y8.set],[`localstorage-delete`,Y8.del],[`localstorage-clear`,Y8.clear],[`sessionstorage-list`,X8.list],[`sessionstorage-get`,X8.get],[`sessionstorage-set`,X8.set],[`sessionstorage-delete`,X8.del],[`sessionstorage-clear`,X8.clear],[`record`,yre],[`stop-recording`,bre],[`tab-select`,zre],[`pdf`,Pre],[`network-state-set`,v8],[`upload`,async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`upload requires at least one file path
|
|
6604
6604
|
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=null,s=r,c=n.snapshots.get(a.targetId);if(c&&r.length>0&&c.refToBackendNodeId.has(r[0])&&(o=r[0],s=r.slice(1)),s.length===0)return{stdout:``,stderr:`upload requires at least one file path
|
|
6605
|
-
`,exitCode:1};let l=[];for(let e of s){let n=await t.readFile(e),r=e.split(`/`).pop()??e,i=
|
|
6605
|
+
`,exitCode:1};let l=[];for(let e of s){let n=await t.readFile(e),r=e.split(`/`).pop()??e,i=Jre(r),a=Yre(typeof n==`string`?new TextEncoder().encode(n):n);l.push({name:r,type:i,base64:a})}if(o){let t=c.refToBackendNodeId.get(o);await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`DOM.enable`,{},n);let{object:i}=await r.send(`DOM.resolveNode`,{backendNodeId:t},n),a=await r.send(`Runtime.callFunctionOn`,{objectId:i.objectId,functionDeclaration:`function(filesData) {
|
|
6606
6606
|
const el = this;
|
|
6607
6607
|
if (el.tagName !== 'INPUT' || el.type !== 'file') {
|
|
6608
6608
|
throw new Error('Element ' + el.tagName + ' is not a file input');
|
|
@@ -6633,7 +6633,7 @@ Options:
|
|
|
6633
6633
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6634
6634
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6635
6635
|
return el.files.length;
|
|
6636
|
-
})()`,r=await e.getTransport().send(`Runtime.evaluate`,{expression:n,returnByValue:!0,awaitPromise:!1},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`File upload failed`;throw Error(e)}});let u=s.map(e=>e.split(`/`).pop()??e).join(`, `);return{stdout:`Uploaded ${s.length} file(s): ${u}\n`,stderr:``,exitCode:0}}],[`state-save`,
|
|
6636
|
+
})()`,r=await e.getTransport().send(`Runtime.evaluate`,{expression:n,returnByValue:!0,awaitPromise:!1},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`File upload failed`;throw Error(e)}});let u=s.map(e=>e.split(`/`).pop()??e).join(`, `);return{stdout:`Uploaded ${s.length} file(s): ${u}\n`,stderr:``,exitCode:0}}],[`state-save`,Ire],[`state-load`,Lre],[`console`,Y3],[`requests`,C8],[`request`,w8],[`request-headers`,T8],[`request-body`,E8],[`response-headers`,D8],[`response-body`,O8],[`mousemove`,I6],[`mousedown`,L6],[`mouseup`,R6],[`mousewheel`,z6],[`drop`,B6],[`route`,wre],[`route-list`,Tre],[`unroute`,Ere],[`generate-locator`,t6],[`highlight`,n6]]);function Zre(e){return`Usage: ${e} <command> [args...]
|
|
6637
6637
|
|
|
6638
6638
|
Commands:
|
|
6639
6639
|
open [url|/vfs/path] [--foreground|--fg] [--runtime=<id>] [--discover]
|
|
@@ -6756,11 +6756,11 @@ Commands:
|
|
|
6756
6756
|
Highlight an element with a visual overlay (--hide to remove)
|
|
6757
6757
|
help Show this help message
|
|
6758
6758
|
|
|
6759
|
-
Aliases: ${
|
|
6760
|
-
`,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),c,l;try{({positional:c,flags:l}=
|
|
6761
|
-
`);let a=[];for(let[e,t]of
|
|
6759
|
+
Aliases: ${j3.filter(t=>t!==e).join(`, `)}`}function Qre(e,t,n){let r=Zre(e),i=t?N3(t,n):null;return B(e,async a=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`)return{stdout:r+`
|
|
6760
|
+
`,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),c,l;try{({positional:c,flags:l}=W3(s))}catch(t){return{stdout:``,stderr:`${e} ${o}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}let u,d=Xre.get(o);if(!d)u={stdout:``,stderr:`Unknown command: ${o}\nRun "playwright-cli help" for usage.\n`,exitCode:1};else try{u=await d({browser:t,fs:n,state:i,positional:c,flags:l})}catch(e){u={stdout:``,stderr:`Error: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let f=l.tab??null,p=null;I3.has(o)&&u.exitCode===0&&f&&(p=await Dre(t,n,f,i));try{await Ore(n,i,{command:o,args:s,result:u,snapshotPath:p,targetId:f})}catch{}return u})}const $re=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`,`file`,`rmdir`,`rsync`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`,`column`,`comm`,`egrep`,`fgrep`,`expand`,`unexpand`,`fold`,`join`,`nl`,`od`,`paste`,`rev`,`split`,`strings`,`tac`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`,`gunzip`,`gzip`,`zcat`]],[`Media`,[`convert`,`magick`,`ffmpeg`,`screencapture`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,`echo.printf.env.printenv.export.alias.unalias.history.clear.true.false.bash.sh.commands.which.uname.man.host.oauth-token.secret.nuke.models.local-llm.cost.hostname.whoami.help.sleep.time.timeout.oauth-domain`.split(`.`)],[`Data processing`,[`xargs`,`jq`,`base64`,`date`,`expr`,`seq`]],[`Hashes`,[`md5sum`,`sha1sum`,`sha256sum`]],[`Network`,[`curl`,`wget`,`dig`,`websocat`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Build tools`,[`tsc`,`test`,`esbuild`,`biome`]],[`Packages`,[`ipk`,`hf`,`npm`,`i`,`ipx`,`npx`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...j3,`sprinkle`]],[`Clipboard`,[`pbcopy`,`pbpaste`,`xclip`,`xsel`]],[`Filesystem`,[`mount`,`fswatch`]],[`Scoops & agents`,[`agent`,`mcp`,`webhook`,`crontask`]],[`Process`,[`ps`,`kill`]]]);function eie(e,t=[],n=[]){let r=[],i=new Set(e);for(let e of t)i.delete(e);for(let e of n)i.delete(e);r.push(`Available commands:
|
|
6761
|
+
`);let a=[];for(let[e,t]of $re){let n=t.filter(e=>i.has(e));if(n.length>0){r.push(` ${e}:`),r.push(` ${n.join(`, `)}\n`);for(let e of n)i.delete(e)}}for(let e of i)a.push(e);return a.length>0&&(r.push(` Other:`),r.push(` ${a.sort().join(`, `)}\n`)),t.length>0&&(r.push(` User scripts (.jsh):`),r.push(` ${t.sort().join(`, `)}\n`)),n.length>0&&(r.push(` Workflows:`),r.push(` ${n.sort().join(`, `)}\n`)),r.push(`Use '<command> --help' for details on a specific command.`),r.join(`
|
|
6762
6762
|
`)+`
|
|
6763
|
-
`}function
|
|
6763
|
+
`}function tie(e={}){return B(`commands`,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`commands - display available commands
|
|
6764
6764
|
|
|
6765
6765
|
Usage: commands [command]
|
|
6766
6766
|
|
|
@@ -6771,7 +6771,7 @@ If a command name is provided, shows help for that command.
|
|
|
6771
6771
|
Otherwise, lists all available commands.
|
|
6772
6772
|
|
|
6773
6773
|
Note: This is an enhanced version of 'help' that shows all custom commands.
|
|
6774
|
-
`,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout
|
|
6774
|
+
`,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout:eie(n.getRegisteredCommands?.()??[],await e.getJshCommands?.()??[],await e.getWorkflowCommands?.()??[]),stderr:``,exitCode:0}})}function nie(e){return{stdout:`hf - download model repos from the Hugging Face Hub into the VFS
|
|
6775
6775
|
|
|
6776
6776
|
Usage:
|
|
6777
6777
|
hf download <repo> [files...] [--to <dir>] [--revision <rev>] [--force]
|
|
@@ -6793,8 +6793,8 @@ Notes:
|
|
|
6793
6793
|
unless --force is passed.
|
|
6794
6794
|
- Weights are read by the speech engines via the preview SW from the
|
|
6795
6795
|
target directory; transformers expects <localModelPath>/<repo>/.
|
|
6796
|
-
`,stderr:``,exitCode:e}}function t5(e){return{stdout:``,stderr:`hf: ${e}\n`,exitCode:1}}const
|
|
6797
|
-
`)}\n`}function u5(e){return`${
|
|
6796
|
+
`,stderr:``,exitCode:e}}function t5(e){return{stdout:``,stderr:`hf: ${e}\n`,exitCode:1}}const rie=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;function iie(e){let t=null,n=`main`,r=!1,i=[],a=0;for(;a<e.length;){let o=e[a];if(o===`--to`){let n=e[a+1];if(typeof n!=`string`)return{error:`--to requires a value`};t=n,a+=2;continue}if(o===`--revision`||o===`--rev`){let t=e[a+1];if(typeof t!=`string`)return{error:`${o} requires a value`};n=t,a+=2;continue}if(o===`--force`||o===`-f`){r=!0,a+=1;continue}if(o.startsWith(`--`))return{error:`unknown option: ${o}`};i.push(o),a+=1}if(i.length===0)return{error:`download requires <repo>`};let o=i[0];return rie.test(o)?{repo:o,files:i.slice(1),to:t,revision:n,force:r}:{error:`invalid repo '${o}' — expected <owner>/<name>`}}function n5(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function aie(e,t,n){let r=iie(e);if(`error`in r)return t5(r.error);let i=Xt(r.repo,r.to,t.cwd),a=``;try{let e=await Wt({fetch:n,fs:t.fs,repo:r.repo,targetDir:i,files:r.files,revision:r.revision,force:r.force,progress:{onListed:({files:e})=>{a+=`hf: ${e.length} file(s) listed in ${r.repo}@${r.revision}\n`},onFile:e=>{a+=e.status===`downloaded`?`hf: downloaded ${e.file} (${n5(e.bytes)})\n`:`hf: skipped ${e.file} (already at ${i})\n`}}}),o=`hf: ${e.downloaded} downloaded, ${e.skipped} skipped, ${n5(e.totalBytes)} total into ${i}\n`;return{stdout:``,stderr:a+o,exitCode:0}}catch(e){return e instanceof Bt?(a+=`hf: failed ${e.file}: ${e.message}\n`,{stdout:``,stderr:a,exitCode:1}):t5(e instanceof Error?e.message:String(e))}}function oie(e){return{name:`hf`,async execute(t,n){if(t.length===0||t[0]===`--help`||t[0]===`-h`)return nie(+(t.length===0));let r=t[0];return r===`download`?aie(t.slice(1),n,e.fetch):t5(`unknown subcommand: ${r}`)}}}const sie=new Set([`--vid`,`--pid`,`--usage-page`,`--usage`,`--__resolved`,`--timeout`]);function cie(e){return zF(e,sie)}function r5(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function lie(e){let t={};return e.has(`--vid`)&&(t.vendorId=r5(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=r5(e.get(`--pid`),`pid`)),e.has(`--usage-page`)&&(t.usagePage=r5(e.get(`--usage-page`),`usage-page`)),e.has(`--usage`)&&(t.usage=r5(e.get(`--usage`),`usage`)),Object.keys(t).length>0?[t]:[]}function i5(e){let t=iZ(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function a5(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function uie(e){return e.toString(16).padStart(2,`0`)}function o5(e){return`0x${e.toString(16).padStart(4,`0`)}`}function s5(e){let t=e.productName||`(unknown)`,n=e.opened?` [open]`:``,r=e.usagePage===void 0?``:`\t${o5(e.usagePage)}:${o5(e.usage??0)}`;return`${e.handle}\t${o5(e.vendorId)}:${o5(e.productId)}${r}\t${t}${n}`}function c5(e,t){let n=t?.usagePage,r=t?.usage;if(n===void 0&&r===void 0)return e;let i=e.findIndex(e=>(n===void 0||e.usagePage===n)&&(r===void 0||e.usage===r));if(i<=0)return e;let a=e.slice(),[o]=a.splice(i,1);return a.unshift(o),a}function l5(e){return`${e.map(s5).join(`
|
|
6797
|
+
`)}\n`}function u5(e){return`${uie(e.reportId)} ${a5(e.bytes)}`.trimEnd()}function d5(e){return{stdout:e,stderr:``,exitCode:0}}function f5(e){return{stdout:``,stderr:`hid: ${e}\n`,exitCode:1}}const die=`hid - access HID devices via WebHID
|
|
6798
6798
|
|
|
6799
6799
|
Usage: hid <subcommand> [options]
|
|
6800
6800
|
|
|
@@ -6817,19 +6817,19 @@ Options:
|
|
|
6817
6817
|
--timeout <ms> query: wait this long for an input report (default 1000)
|
|
6818
6818
|
-h, --help
|
|
6819
6819
|
|
|
6820
|
-
Report payloads are capped at ${
|
|
6821
|
-
`;function p5(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return d5(t)}return d5(e.length?`${a5(e)}\n`:``)}function
|
|
6820
|
+
Report payloads are capped at ${xJ} bytes (4 MiB).
|
|
6821
|
+
`;function p5(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return d5(t)}return d5(e.length?`${a5(e)}\n`:``)}function fie(e){return!e||e.aborted?Promise.resolve():new Promise(t=>{e.addEventListener(`abort`,()=>t(),{once:!0})})}async function pie(e){let t=await e.list();return t.length===0?d5(`no granted HID devices
|
|
6822
6822
|
`):d5(`${t.map(s5).join(`
|
|
6823
|
-
`)}\n`)}async function
|
|
6824
|
-
`)}\n`:``)}async function
|
|
6823
|
+
`)}\n`)}async function mie(e,t){let n=e.get(`--__resolved`),r=lie(e),i=r[0];if(n){let e=n.split(`,`).filter(e=>e.length>0);return e.length===0?f5(`request: missing resolved handle`):d5(l5(c5(await Promise.all(e.map(e=>t.info(e))),i)))}let a=me();return a?hie(r,i,a,t):d5(l5(c5(await t.request(r),i)))}async function hie(e,t,n,r){let i=await N(`hid-device`,e,n),a,o;if(i.handle){let e=await r.info(i.handle);a=e.vendorId,o=e.productId}else{let e=i.info,t=hJ();if(!t)return f5(`request: WebHID unavailable for device re-acquire`);let n=await t.getDevices(),r=bJ(),s=n.filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId);if(s.length===0)return f5(`request: granted device could not be re-acquired`);for(let e of s)r.register(e);a=e.vendorId,o=e.productId}let s=(await r.list()).filter(e=>e.vendorId===a&&e.productId===o),c=c5(s.length>0?s:[],t);return c.length===0?f5(`request: granted device could not be re-acquired`):d5(l5(c))}async function gie(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):await n.close(r),d5(``)):f5(`${e}: handle required`)}async function _ie(e,t,n,r){let[,i,a]=t;if(!i||a===void 0)return f5(`${e}: handle and report-id required`);let o=r5(a,`report-id`),s=i5(n);return s.length>4194304?f5(`${e} payload exceeds 4 MiB limit`):(e===`send`?await r.sendReport(i,o,s):await r.sendFeatureReport(i,o,s),d5(``))}async function vie(e,t,n){let[,r,i]=e;return!r||i===void 0?f5(`feature-get: handle and report-id required`):p5((await t.receiveFeatureReport(r,r5(i,`report-id`))).bytes,n)}async function yie(e,t,n){let r=e[1];if(!r)return f5(`watch: handle required`);let i=[],a=await n.subscribeInputReports(r,e=>{i.push(u5(e))});try{await fie(t.signal)}finally{await a()}return d5(i.length?`${i.join(`
|
|
6824
|
+
`)}\n`:``)}async function bie(e,t,n,r,i){let[,a,o]=e;if(!a||o===void 0)return f5(`query: handle and report-id required`);let s=r5(o,`report-id`),c=i5(t);if(c.length>4194304)return f5(`query payload exceeds 4 MiB limit`);let l=n.has(`--timeout`)?r5(n.get(`--timeout`),`timeout`):1e3,u=()=>{},d=new Promise(e=>{u=e}),f=await r.subscribeInputReports(a,e=>{u(e)}),p;try{await r.sendReport(a,s,c);let e=new Promise(e=>{p=setTimeout(()=>e(`timeout`),l)}),t=await Promise.race([d,e]);return t===`timeout`?f5(`query: no input report within ${l}ms`):i?p5(t.bytes,!0):d5(`${u5(t)}\n`)}finally{p!==void 0&&clearTimeout(p),await f()}}async function xie(e,t,n){let{positionals:r,flags:i,bools:a}=cie(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return pie(n);case`request`:return mie(i,n);case`open`:case`close`:return gie(o,r,n);case`send`:case`feature-send`:return _ie(o,r,t,n);case`feature-get`:return vie(r,n,s);case`watch`:return yie(r,t,n);case`query`:return bie(r,t,i,n,s);default:return f5(`unknown subcommand '${o??``}'. Try 'hid --help'.`)}}function Sie(){return B(`hid`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return d5(die);let n=HJ(a(),i());if(!n)return f5(`WebHID is unavailable in this environment`);try{return await xie(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?f5(`user cancelled or no device selected`):f5(t)}})}function Cie(){return{stdout:`imgcat - preview image and video files in the preview tab
|
|
6825
6825
|
|
|
6826
6826
|
Usage: imgcat <path> [path...]
|
|
6827
6827
|
|
|
6828
6828
|
Options:
|
|
6829
6829
|
-h, --help Show this help message
|
|
6830
|
-
`,stderr:``,exitCode:0}}function
|
|
6830
|
+
`,stderr:``,exitCode:0}}function wie(e={}){return B(`imgcat`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Cie();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`imgcat: browser APIs are unavailable in this environment
|
|
6831
6831
|
`,exitCode:1};if(!e.onMediaPreview)return{stdout:``,stderr:`imgcat: terminal preview is unavailable
|
|
6832
|
-
`,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let i=Se(t);if(!F(i))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let a=await n.fs.readFileBuffer(t),o=new Uint8Array(a.byteLength);o.set(a),r.push({path:t,mimeType:i,bytes:o})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const
|
|
6832
|
+
`,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let i=Se(t);if(!F(i))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let a=await n.fs.readFileBuffer(t),o=new Uint8Array(a.byteLength);o.set(a),r.push({path:t,mimeType:i,bytes:o})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const Tie=new Set([`install`,`i`,`add`]);function m5(e){return`${e} - install packages from the npm registry into node_modules
|
|
6833
6833
|
|
|
6834
6834
|
Usage:
|
|
6835
6835
|
${e} install [<pkg>[@<spec>] ...]
|
|
@@ -6855,11 +6855,11 @@ Installed packages are extracted into <cwd>/node_modules and named installs
|
|
|
6855
6855
|
are recorded in <cwd>/package.json under dependencies. Existing fields are
|
|
6856
6856
|
preserved. Idempotent: re-installing an already-satisfied package is a clean
|
|
6857
6857
|
no-op.
|
|
6858
|
-
`}function
|
|
6858
|
+
`}function Eie(e){return e.includes(`--help`)||e.includes(`-h`)}function h5(e){return e instanceof Error?e.message:String(e)}async function Die(e,t,n){let r;try{r=await Gt({fs:n.fs,fetch:n.fetch,cwd:t.cwd})}catch(t){return t instanceof Yt?{stdout:``,stderr:`${e}: ${t.message}\n`,exitCode:1}:{stdout:``,stderr:`${e}: install failed: ${h5(t)}\n`,exitCode:1}}if(r.empty&&r.errors.length===0)return{stdout:`${e}: nothing to install (package.json declares no dependencies)\n`,stderr:``,exitCode:0};let i=r.results.map(t=>`${e}: installed ${t.name}@${t.version} -> ${t.installPath}`),a=r.errors.map(t=>`${e}: failed to install ${t.spec}: ${h5(t.error)}`);return{stdout:i.length>0?`${i.join(`
|
|
6859
6859
|
`)}\n`:``,stderr:a.length>0?`${a.join(`
|
|
6860
|
-
`)}\n`:``,exitCode:r.errors.length===0?0:1}}async function g5(e,t,n,r){let i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return
|
|
6860
|
+
`)}\n`:``,exitCode:r.errors.length===0?0:1}}async function g5(e,t,n,r){let i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return Die(e,n,r);let a;try{a=await qt(i,{fs:r.fs,fetch:r.fetch,cwd:n.cwd})}catch(t){return{stdout:``,stderr:`${e}: install failed: ${h5(t)}\n`,exitCode:1}}let o=a.results.map(t=>`${e}: installed ${t.name}@${t.version} -> ${t.installPath}`),s=a.errors.map(t=>`${e}: failed to install ${t.spec}: ${h5(t.error)}`);return{stdout:o.length>0?`${o.join(`
|
|
6861
6861
|
`)}\n`:``,stderr:s.length>0?`${s.join(`
|
|
6862
|
-
`)}\n`:``,exitCode:a.errors.length===0?0:1}}function _5(e,t){let n=e===`i`;return B(e,async(r,i)=>{if(
|
|
6862
|
+
`)}\n`:``,exitCode:a.errors.length===0?0:1}}function _5(e,t){let n=e===`i`;return B(e,async(r,i)=>{if(Eie(r))return{stdout:m5(e),stderr:``,exitCode:0};if(n)return g5(e,r,i,t);if(r.length===0)return{stdout:m5(e),stderr:`${e}: missing subcommand\n`,exitCode:1};let a=r[0],o=r.slice(1);return Tie.has(a)?g5(e,o,i,t):{stdout:``,stderr:`${e}: unknown subcommand '${a}' (supported: install, i)\n`,exitCode:1}})}const Oie=/require\(\s*["']([^"']+)["']\s*\)/;function kie(e){return`${e} - run an installed package's executable bin
|
|
6863
6863
|
|
|
6864
6864
|
Usage:
|
|
6865
6865
|
${e} <pkg-or-bin> [args...]
|
|
@@ -6870,12 +6870,12 @@ forwarding argv and stdin. Exit codes propagate.
|
|
|
6870
6870
|
|
|
6871
6871
|
Options:
|
|
6872
6872
|
-h, --help Show this help message
|
|
6873
|
-
`}async function v5(e,t){let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)}async function y5(e,t){try{return(await e.stat(t)).type===`file`}catch{return!1}}async function
|
|
6874
|
-
`)}\n`:``}}catch(n){return{error:w5(e,`failed to install '${t}': ${C5(n)}`)}}}async function
|
|
6875
|
-
`,exitCode:1};let r=
|
|
6876
|
-
`)}\n`:``,exitCode:+!i}})}function
|
|
6877
|
-
`,exitCode:2};let i=E5(n);if(i instanceof Error)return{ok:!1,stderr:`kill: ${i.message}\n`,exitCode:2};t=i;continue}if(i.startsWith(`-`)){let e=
|
|
6878
|
-
`,exitCode:2}:
|
|
6873
|
+
`}async function v5(e,t){let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)}async function y5(e,t){try{return(await e.stat(t)).type===`file`}catch{return!1}}async function Aie(e,t){try{return(await e.stat(t)).type===`directory`}catch{return!1}}function*b5(e){let t=lt(e);for(;yield ut(t,`node_modules`),t!==`/`;)t=ct(t).dir}async function jie(e,t,n){for(let r of b5(t)){let t=ut(r,`.bin`,n);if(!await y5(e,t))continue;let i=await v5(e,t),a=Oie.exec(i),o=ct(t).dir;return{binFilePath:a?ut(o,a[1]):t,argvName:t}}return null}function x5(e){if(e.startsWith(`@`)){let t=e.indexOf(`/`);if(t!==-1)return e.slice(t+1)}return e}function Mie(e,t){if(typeof e==`string`)return{binName:x5(t),binPath:e};if(typeof e!=`object`||!e)return null;let n=e,r=[t,x5(t)];for(let e of r)if(typeof n[e]==`string`)return{binName:e,binPath:n[e]};let i=Object.entries(n).filter(([,e])=>typeof e==`string`);if(i.length===1){let[e,t]=i[0];return{binName:e,binPath:t}}return null}async function Nie(e,t,n){for(let r of b5(t)){let t=ut(r,n),i=ut(t,`package.json`);if(!await y5(e,i))continue;let a;try{a=JSON.parse(await v5(e,i))}catch{return null}let o=Mie(a.bin,n);return o?{binFilePath:ut(t,o.binPath.replace(/^\.\//,``)),argvName:ut(r,`.bin`,o.binName)}:null}return null}async function S5(e,t,n){return await jie(e,t,n)??await Nie(e,t,n)}async function Pie(e,t,n){for(let r of b5(t))if(await y5(e,ut(r,n,`package.json`)))return!0;return!1}function C5(e){return e instanceof Error?e.message:String(e)}function w5(e,t){return{stdout:``,stderr:`${e}: ${t}\n`,exitCode:1}}async function Fie(e,t,n,r){try{let i=await qt([t],{fs:r.fs,fetch:r.fetch,cwd:n.cwd});if(i.errors.length>0)return{error:w5(e,`failed to install '${t}': ${C5(i.errors[0].error)}`)};let a=i.results.map(t=>`${e}: installed ${t.name}@${t.version}`);return{progress:a.length>0?`${a.join(`
|
|
6874
|
+
`)}\n`:``}}catch(n){return{error:w5(e,`failed to install '${t}': ${C5(n)}`)}}}async function Iie(e,t,n,r){return await y5(r,n)?null:await Aie(r,n)?w5(e,`bin target '${n}' is a directory, not a file`):w5(e,`bin file '${n}' for '${t}' does not exist`)}function T5(e,t){return{name:e,trusted:!0,async execute(n,r){if(n.length===0||n[0]===`--help`||n[0]===`-h`)return{stdout:kie(e),stderr:``,exitCode:+(n.length===0)};let i=n[0],a=n.slice(1),o;try{o=await S5(t.fs,r.cwd,i)}catch(t){return w5(e,C5(t))}let s=``;if(!o){if(await Pie(t.fs,r.cwd,i))return w5(e,`package '${i}' does not expose an executable bin`);let n=await Fie(e,i,r,t);if(`error`in n)return n.error;if(s=n.progress,o=await S5(t.fs,r.cwd,i),!o)return w5(e,`package '${i}' was installed but does not expose an executable bin`)}let c=await Iie(e,i,o.binFilePath,t.fs);if(c)return c;let l=await oZ(eJ(await v5(t.fs,o.binFilePath)),[`node`,o.argvName,...a],r,void 0,{filename:o.binFilePath});return{stdout:l.stdout,stderr:s+l.stderr,exitCode:l.exitCode}}}}const Lie=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]);function Rie(e={}){return B(`kill`,async t=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return Uie();let n=e.processManager??zie();if(!n)return{stdout:``,stderr:`kill: no process manager available in this runtime
|
|
6875
|
+
`,exitCode:1};let r=Bie(t);if(!r.ok)return{stdout:``,stderr:r.stderr,exitCode:r.exitCode};let{allDelivered:i,errors:a}=Vie(n,r.pids,r.signal);return{stdout:``,stderr:a.length?`${a.join(`
|
|
6876
|
+
`)}\n`:``,exitCode:+!i}})}function zie(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.signal==`function`?e:null}function Bie(e){let t=`SIGTERM`,n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`-s`||i===`--signal`){let n=e[++r];if(!n)return{ok:!1,stderr:`kill: -s requires a signal name
|
|
6877
|
+
`,exitCode:2};let i=E5(n);if(i instanceof Error)return{ok:!1,stderr:`kill: ${i.message}\n`,exitCode:2};t=i;continue}if(i.startsWith(`-`)){let e=Hie(i);if(e instanceof Error)return{ok:!1,stderr:`kill: ${e.message}\n`,exitCode:2};t=e;continue}let a=Number.parseInt(i,10);if(!Number.isFinite(a)||String(a)!==i)return{ok:!1,stderr:`kill: invalid pid '${i}'\n`,exitCode:2};n.push(a)}return n.length===0?{ok:!1,stderr:`kill: no pids supplied
|
|
6878
|
+
`,exitCode:2}:Lie.has(t)?{ok:!0,signal:t,pids:n}:{ok:!1,stderr:`kill: signal ${t} not supported\n`,exitCode:2}}function Vie(e,t,n){let r=!0,i=[];for(let a of t)e.signal(a,n)||(r=!1,i.push(e.get(a)?`kill: (${a}) - process already terminated`:`kill: (${a}) - no such process`));return{allDelivered:r,errors:i}}function E5(e){let t=e.toUpperCase(),n=t.startsWith(`SIG`)?t:`SIG${t}`;return n===`SIGINT`||n===`SIGTERM`||n===`SIGKILL`||n===`SIGSTOP`||n===`SIGCONT`?n:Error(`unknown signal '${e}'`)}function Hie(e){return e===`-9`?`SIGKILL`:E5(e.slice(1))}function Uie(){return{stdout:`Usage: kill [-s SIGNAL | -INT | -TERM | -KILL | -STOP | -CONT | -9] PID [PID …]
|
|
6879
6879
|
|
|
6880
6880
|
Send a signal to one or more processes tracked by the kernel.
|
|
6881
6881
|
|
|
@@ -6897,7 +6897,7 @@ Examples:
|
|
|
6897
6897
|
kill -INT 1024 1025 SIGINT both
|
|
6898
6898
|
kill -STOP 1024 pause; \`kill -CONT 1024\` resumes
|
|
6899
6899
|
kill -s SIGKILL 1024 explicit signal name
|
|
6900
|
-
`,stderr:``,exitCode:0}}const D5=Rn.id;function
|
|
6900
|
+
`,stderr:``,exitCode:0}}const D5=Rn.id;function Wie(){return`local-llm — inspect and configure the Local LLM provider
|
|
6901
6901
|
|
|
6902
6902
|
Usage:
|
|
6903
6903
|
local-llm Show current config + verify connection
|
|
@@ -6916,20 +6916,20 @@ Common base URLs:
|
|
|
6916
6916
|
llama.cpp http://localhost:8080/v1
|
|
6917
6917
|
vLLM http://localhost:8000/v1
|
|
6918
6918
|
Jan http://localhost:1337/v1
|
|
6919
|
-
`}function
|
|
6919
|
+
`}function Gie(){return B(D5,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Wie(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-Bv01tMmE.js`),{verifyConnection:a}=await import(`./local-llm-4lJSiK5z.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(D5);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6920
6920
|
`,exitCode:1};let c=await a(s,t(D5)??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(`
|
|
6921
6921
|
`)+`
|
|
6922
6922
|
`,exitCode:1}}if(o===`discover`){let e=n(D5)??``;return i(D5,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(`
|
|
6923
6923
|
`)+`
|
|
6924
6924
|
`,stderr:``,exitCode:0}}return{stdout:[`✓ ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` models: ${c.models.length}`,...c.models.map(e=>` • ${e}`)].join(`
|
|
6925
6925
|
`)+`
|
|
6926
|
-
`,stderr:``,exitCode:0}})}function
|
|
6926
|
+
`,stderr:``,exitCode:0}})}function Kie(){return{stdout:`usage: man <topic>
|
|
6927
6927
|
|
|
6928
6928
|
Fetches documentation for a given topic from sliccy.com.
|
|
6929
|
-
`,stderr:``,exitCode:0}}function
|
|
6929
|
+
`,stderr:``,exitCode:0}}function qie(e){return e.replace(/<[^>]*>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `).trimEnd()}function Jie(){let e=g();return B(`man`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return Kie();if(t.length===0)return{stdout:``,stderr:`What manual page do you want?
|
|
6930
6930
|
For example, try 'man commands'.
|
|
6931
|
-
`,exitCode:1};let n=t.join(`-`),r=`https://www.sliccy.com/man/${n}.plain.html`;try{let t=await e(r,{method:`GET`});return t.status===404?{stdout:``,stderr:`No manual entry for ${n}\n`,exitCode:1}:t.status<200||t.status>=300?{stdout:``,stderr:`man: failed to fetch manual page for ${n}: ${t.status} ${t.statusText}\n`,exitCode:1}:{stdout:
|
|
6932
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`man: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const O5=r(`mcp-command`),k5=`/workspace/.mcp/aliases`;function A5(e){return{stdout:e,stderr:``,exitCode:0}}function j5(e,t=1){return{stdout:``,stderr:`${e}\n`,exitCode:t}}function
|
|
6931
|
+
`,exitCode:1};let n=t.join(`-`),r=`https://www.sliccy.com/man/${n}.plain.html`;try{let t=await e(r,{method:`GET`});return t.status===404?{stdout:``,stderr:`No manual entry for ${n}\n`,exitCode:1}:t.status<200||t.status>=300?{stdout:``,stderr:`man: failed to fetch manual page for ${n}: ${t.status} ${t.statusText}\n`,exitCode:1}:{stdout:qie(new TextDecoder(`utf-8`).decode(t.body))+`
|
|
6932
|
+
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`man: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const O5=r(`mcp-command`),k5=`/workspace/.mcp/aliases`;function A5(e){return{stdout:e,stderr:``,exitCode:0}}function j5(e,t=1){return{stdout:``,stderr:`${e}\n`,exitCode:t}}function Yie(){return`usage: mcp <command> [args]
|
|
6933
6933
|
|
|
6934
6934
|
Commands:
|
|
6935
6935
|
add <url> <name> Register an MCP server. Runs OAuth if required.
|
|
@@ -6951,7 +6951,7 @@ Examples:
|
|
|
6951
6951
|
mcp search forecast
|
|
6952
6952
|
mcp auth weather
|
|
6953
6953
|
mcp delete weather
|
|
6954
|
-
`}function
|
|
6954
|
+
`}function Xie(e={}){return B(`mcp`,async t=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return A5(Yie());let n=t[0],r=t.slice(1);try{switch(n){case`add`:return await Zie(r,e);case`list`:case`ls`:return await $ie(r,e);case`delete`:case`rm`:return await nae(r,e);case`invoke`:return await rae(r,e);case`search`:return await eae(r,e);case`refresh`:return await pae(r,e);case`auth`:return await mae(r,e);default:return j5(`mcp: unknown subcommand "${n}" (try \`mcp --help\`)`)}}catch(e){let t=e instanceof Error?e.message:String(e);return O5.error(`mcp subcommand failed`,{sub:n,error:t}),e instanceof zn?j5(`mcp ${n}: ${t}`,124):j5(`mcp ${n}: ${t}`)}})}async function Zie(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp add <url> <name>
|
|
6955
6955
|
|
|
6956
6956
|
Probes <url> with an unauthenticated MCP \`initialize\`. If the server
|
|
6957
6957
|
returns 401, runs OAuth discovery → dynamic client registration → PKCE
|
|
@@ -6960,20 +6960,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
6960
6960
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
6961
6961
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
6962
6962
|
short name resolves on the PATH.
|
|
6963
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return j5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return j5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return j5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
6963
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return j5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return j5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return j5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-J9T9BcgY.js`).then(e=>e.r);if(await a(i,t.fs))return j5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BliYDaDA.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 Qie(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>F5(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await vae(i,t);let m=await R5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-DXnAAcyy.js`);e({name:i,serverUrl:r,auth:u})}return A5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${k5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
6964
6964
|
`)+`
|
|
6965
|
-
`)}async function
|
|
6966
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
6965
|
+
`)}async function Qie(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-Bv01tMmE.js`),c=await gae(r.oauthFetchImpl),l=r.oauthLauncher??await I5(),u=await i(e,n,c);O5.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await hae(),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}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function $ie(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp list
|
|
6966
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-DXnAAcyy.js`);await n();let{listServers:r}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return A5("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 A5(M5(o))}function M5(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(`
|
|
6967
6967
|
`)+`
|
|
6968
|
-
`}async function
|
|
6968
|
+
`}async function eae(e,t){if(e[0]===`--help`||e[0]===`-h`)return A5(`usage: mcp search <query>
|
|
6969
6969
|
|
|
6970
6970
|
Case-insensitive substring search across the cached tools of every
|
|
6971
6971
|
registered MCP server. Matches tool name OR description and prints a
|
|
6972
6972
|
table of (server, tool, description, match-field) rows.
|
|
6973
|
-
`);if(e.length===0)return j5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
6974
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
6973
|
+
`);if(e.length===0)return j5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-DXnAAcyy.js`);await i();let{listServers:a}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return A5("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 A5(`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,tae(e.description),e.match]);return A5(M5(l))}function tae(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function nae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp delete: expected <name>`):A5(`usage: mcp delete <name>
|
|
6974
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-DXnAAcyy.js`);await r(n);let{deleteServer:a}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),o=await a(n,t.fs);await yae(n,t),await bae(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-Bv01tMmE.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){O5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?j5(`mcp delete: no server, alias, or account found for "${n}"`):A5([`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(`
|
|
6975
6975
|
`)+`
|
|
6976
|
-
`)}async function
|
|
6976
|
+
`)}async function rae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp invoke: expected <name>`):A5(aae());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-DXnAAcyy.js`);await i(n);let{getServer:a}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return j5(`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 A5(oae(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return j5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=iae(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return A5(sae(n,l));let p=cae(d,l.inputSchema);if(!p.ok)return j5(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-BliYDaDA.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=fae(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function iae(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=N5(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=N5(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 N5(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 aae(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
6977
6977
|
|
|
6978
6978
|
mcp invoke <name> List tools on <name>.
|
|
6979
6979
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -6990,20 +6990,20 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
6990
6990
|
string/integer/number/boolean. Bare \`--flag\` (no value or "--" next)
|
|
6991
6991
|
is treated as true. Repeating a flag accumulates into an array when
|
|
6992
6992
|
the schema declares \`type: array\`.
|
|
6993
|
-
`}function
|
|
6993
|
+
`}function oae(e,t,n){let r=[];if(r.push(`MCP server "${e}" → ${t.url}`),n.length===0)r.push(" (no tools cached — run `mcp refresh "+e+"`)");else{r.push(``),r.push(`Tools:`);let t=n.reduce((e,t)=>Math.max(e,t.name.length),0);for(let e of n)r.push(` ${e.name.padEnd(t)} ${e.description??``}`.trimEnd());r.push(``),r.push(`Run \`${e} <tool> --help\` for tool-specific flags.`)}return r.join(`
|
|
6994
6994
|
`)+`
|
|
6995
|
-
`}function
|
|
6995
|
+
`}function sae(e,t){let n=t.inputSchema??{},r=n.properties??{},i=new Set(Array.isArray(n.required)?n.required:[]),a=[];a.push(`usage: ${e} ${t.name} [flags]`),t.description&&(a.push(``),a.push(t.description));let o=Object.keys(r);if(o.length===0)return a.push(``),a.push(`(no flags declared)`),a.join(`
|
|
6996
6996
|
`)+`
|
|
6997
6997
|
`;a.push(``),a.push(`Flags:`);let s=o.map(e=>{let t=r[e]??{};return` --${e} <${typeof t.type==`string`?t.type:`string`}>`}),c=s.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;e<o.length;e++){let t=o[e],n=r[t]??{},l=typeof n.description==`string`?n.description:``,u=i.has(t)?` (required)`:``;a.push(`${s[e].padEnd(c)} ${l}${u}`.trimEnd())}return a.join(`
|
|
6998
6998
|
`)+`
|
|
6999
|
-
`}function
|
|
6999
|
+
`}function cae(e,t){let n=t??{},r=n.properties??{},i=new Set(Array.isArray(n.required)?n.required:[]),a={},o=0;for(;o<e.length;){let t=lae(e,o,r,a);if(!t.ok)return t;o=t.nextIndex}for(let e of i)if(!(e in a))return{ok:!1,error:`missing required flag --${e}`};return{ok:!0,value:a}}function lae(e,t,n,r){let i=e[t];if(!i.startsWith(`--`))return{ok:!1,error:`unexpected positional argument "${i}"`};let{key:a,inlineValue:o}=uae(i),s=n[a],c=typeof s?.type==`string`?s.type:`string`,l=c===`array`,u=l&&s?.items&&typeof s.items.type==`string`?s.items.type:`string`,d=o,f;if(d===void 0){let n=e[t+1];if(c===`boolean`&&(n===void 0||n.startsWith(`--`)))return r[a]=!0,{ok:!0,nextIndex:t+1};if(n===void 0)return{ok:!1,error:`flag --${a} requires a value`};d=n,f=t+2}else f=t+1;let p=dae(d,l?u:c);if(!p.ok)return{ok:!1,error:`--${a}: ${p.error}`};if(l){let e=r[a];Array.isArray(e)?e.push(p.value):r[a]=[p.value]}else r[a]=p.value;return{ok:!0,nextIndex:f}}function uae(e){let t=e.indexOf(`=`);return t>2?{key:e.slice(2,t),inlineValue:e.slice(t+1)}:{key:e.slice(2),inlineValue:void 0}}function dae(e,t){switch(t){case`integer`:return/^-?\d+$/.test(e)?{ok:!0,value:Number(e)}:{ok:!1,error:`expected integer, got "${e}"`};case`number`:{let t=Number(e);return Number.isFinite(t)?{ok:!0,value:t}:{ok:!1,error:`expected number, got "${e}"`}}case`boolean`:return e===`true`||e===`1`||e===`yes`?{ok:!0,value:!0}:e===`false`||e===`0`||e===`no`?{ok:!0,value:!1}:{ok:!1,error:`expected boolean, got "${e}"`};default:return{ok:!0,value:e}}}function fae(e){let t=e??{},n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n)if(!(!e||typeof e!=`object`))switch(e.type){case`text`:typeof e.text==`string`&&r.push(e.text);break;case`image`:r.push(`[image: ${e.mimeType??`unknown mime`}]`);break;case`resource`:{let t=e.resource?.uri??e.uri??`unknown uri`;r.push(`[resource: ${t}]`);break}default:r.push(`[${e.type??`unknown`}]`)}let i=r.join(`
|
|
7000
7000
|
`),a=i.endsWith(`
|
|
7001
7001
|
`)?``:`
|
|
7002
|
-
`;return t.isError?{stdout:``,stderr:(i||`(tool reported error)`)+a,exitCode:1}:{stdout:i+(i?a:``),stderr:``,exitCode:0}}async function
|
|
7002
|
+
`;return t.isError?{stdout:``,stderr:(i||`(tool reported error)`)+a,exitCode:1}:{stdout:i+(i?a:``),stderr:``,exitCode:0}}async function pae(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?j5(`mcp refresh: expected <name>`):A5(`usage: mcp refresh <name>
|
|
7003
7003
|
|
|
7004
7004
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
7005
7005
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
7006
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
7006
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-DXnAAcyy.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return j5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-BliYDaDA.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>F5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return j5(`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,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await R5(n,d,t);return A5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function mae(e,t){if(e.includes(`--help`)||e.includes(`-h`))return A5(`usage: mcp auth <name> [--silent | --interactive]
|
|
7007
7007
|
|
|
7008
7008
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
7009
7009
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7015,7 +7015,7 @@ Options:
|
|
|
7015
7015
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7016
7016
|
directly. Use after revoking a refresh token or
|
|
7017
7017
|
when the AS no longer accepts the cached one.
|
|
7018
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return j5(`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 j5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
7018
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return j5(`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 j5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-DXnAAcyy.js`),s=await o(r),{getServer:c}=await import(`./store-J9T9BcgY.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return j5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return j5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return j5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BoV1YFxZ.js`).then(e=>e.r),f=d(u);if(!f)return j5(`mcp auth: provider "${u}" is not registered`);if(a)return await P5(r,f,t);if(!f.onSilentRenew)return i?j5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await P5(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 j5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);O5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?A5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?j5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await P5(r,f,t)}async function P5(e,t,n){if(!t.onOAuthLogin)return j5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await I5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?A5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):j5(`mcp auth: interactive login for "${e}" did not complete`)}async function F5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-Bv01tMmE.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BoV1YFxZ.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){O5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function I5(){let{createOAuthLauncher:e}=await import(`./oauth-service-foejPYvF.js`);return e()}async function hae(){if(ce()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime?.id??``}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-foejPYvF.js`),{origin:t}=await e();return`${t}/auth/callback`}async function gae(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-ldIfAeIb.js`).then(e=>e.o),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 L5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-Bmq507Od.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function _ae(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7019
7019
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7020
7020
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7021
7021
|
const escape = (s) => {
|
|
@@ -7029,7 +7029,7 @@ const r = await exec(cmd);
|
|
|
7029
7029
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7030
7030
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7031
7031
|
process.exit(r.exitCode || 0);
|
|
7032
|
-
`}async function
|
|
7032
|
+
`}async function vae(e,t){let n=await L5(t.fs);await n.mkdir(k5,{recursive:!0}),await n.writeFile(`${k5}/${e}.jsh`,_ae(e)),t.scriptCatalog?.invalidateJsh()}async function yae(e,t){let n=await L5(t.fs),r=`${k5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){O5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function bae(e,t){let{removeAppSprinkles:n}=await import(`./apps-BtS9MYxU.js`);await n(e,t.fs)}async function R5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-BtS9MYxU.js`);return(await r(e,t,n.fs)).length}catch(t){return O5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const z5=`/.cache/artificial-analysis.json`;async function xae(e,t=!1){if(e&&!t)try{let t=await e.readFile(z5),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=g(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(z5,JSON.stringify(t))}catch{}}return s}function B5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function Sae(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=B5(e),a=t.find(e=>B5(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function Cae(){return`models - list available LLM models
|
|
7033
7033
|
|
|
7034
7034
|
Usage: models [options]
|
|
7035
7035
|
|
|
@@ -7041,24 +7041,24 @@ Options:
|
|
|
7041
7041
|
--refresh Force re-fetch benchmark data from Artificial Analysis
|
|
7042
7042
|
--no-benchmarks Skip benchmark data enrichment (faster, works offline)
|
|
7043
7043
|
-h, --help Show this help message
|
|
7044
|
-
`}function
|
|
7044
|
+
`}function wae(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function V5(e){return`$${e.toFixed(2)}`}const Tae=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function Eae(e){let t=`${e.id} ${e.name??``}`;return!Tae.test(t)}function Dae(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 Oae(e){let t=new Map;for(let n of e){let e=Dae(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function kae(e,t,n,r,i){let a=i?Sae(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 Aae(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=`${V5(e.cost.input)} / ${V5(e.cost.output)}`,a=`${wae(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(`
|
|
7045
7045
|
`)+`
|
|
7046
|
-
`}function
|
|
7047
|
-
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await
|
|
7046
|
+
`}function jae(e){return B(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-Bv01tMmE.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Cae(),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.
|
|
7047
|
+
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await xae(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(Eae);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>kae(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=Oae(n)),w.push(...n),!l){let t=i(e);T.push(Aae(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7048
7048
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7049
7049
|
`);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(`
|
|
7050
|
-
`),stderr:``,exitCode:0}})}function
|
|
7051
|
-
`,stderr:``,exitCode:0}}function
|
|
7052
|
-
`,exitCode:9};r=t[1],i=`[eval]`,a=[`node`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let e=t[0],o=n.fs.resolvePath(n.cwd,e);if(!await n.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${e}'\n`,exitCode:1};r=await n.fs.readFile(o),i=o,a=[`node`,o,...t.slice(1)]}else if(
|
|
7053
|
-
`,exitCode:9};return
|
|
7050
|
+
`),stderr:``,exitCode:0}})}function Mae(){return{stdout:`usage: node -e <code> [args...]
|
|
7051
|
+
`,stderr:``,exitCode:0}}function Nae(){return{stdout:`${En}\n`,stderr:``,exitCode:0}}function Pae(e={}){return{name:`node`,trusted:!0,async execute(t,n){if(t.includes(`--help`)||t.includes(`-h`))return Mae();if(t.includes(`--version`)||t.includes(`-v`))return Nae();let r=``,i,a,o=n;if(t.length>0&&(t[0]===`-e`||t[0]===`--eval`)){if(!t[1])return{stdout:``,stderr:`node: option requires an argument -- eval
|
|
7052
|
+
`,exitCode:9};r=t[1],i=`[eval]`,a=[`node`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let e=t[0],o=n.fs.resolvePath(n.cwd,e);if(!await n.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${e}'\n`,exitCode:1};r=await n.fs.readFile(o),i=o,a=[`node`,o,...t.slice(1)]}else if(rZ(n.stdin).trim().length>0)r=rZ(n.stdin),i=`<stdin>`,a=[`node`],o={...n,stdin:``};else if(t.length>0)return{stdout:``,stderr:`node: unsupported option '${t[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
|
|
7053
|
+
`,exitCode:9};return oZ(eJ(r),a,o,e.buildProcessConfig?.(),{filename:i})}}}const Fae=[`slicc:welcome-flow-fired`,`slicc.trayJoinUrl`,`slicc.trayWorkerBaseUrl`];async function Iae(){try{let e=await navigator.serviceWorker?.getRegistrations?.();e&&await Promise.all(e.map(e=>e.unregister().catch(()=>!1)))}catch{}try{let e=await indexedDB.databases();await Promise.all(e.filter(e=>!!e.name).map(e=>new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()})))}catch{}try{let e=navigator.storage;if(typeof e?.getDirectory==`function`){let t=await e.getDirectory(),n=[];for await(let e of t.keys())n.push(e);await Promise.all(n.map(e=>t.removeEntry(e,{recursive:!0}).catch(()=>{})))}}catch{}}function Lae(){return B(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
|
|
7054
7054
|
|
|
7055
7055
|
Completely reset the environment by deleting all local data and reloading.
|
|
7056
7056
|
Destroys the file system, chat history, and scoops database.
|
|
7057
7057
|
Requires the secret launch code to proceed.
|
|
7058
|
-
`,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{await
|
|
7058
|
+
`,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{await Iae(),Rae(Fae)})(),{stdout:`Nuking everything…
|
|
7059
7059
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
|
|
7060
7060
|
Run nuke again with the secret launch code to proceed.
|
|
7061
|
-
`,exitCode:1})}function
|
|
7061
|
+
`,exitCode:1})}function Rae(e=[]){let t=[...e];try{if(typeof BroadcastChannel==`function`){let e=new BroadcastChannel(`slicc-nuke-control`);e.postMessage({type:`nuke-reload`,keysToRemove:t}),setTimeout(()=>e.close(),100)}}catch{}for(let e of t)try{globalThis.localStorage?.removeItem(e)}catch{}try{globalThis.location?.reload?.()}catch{}}function H5(){return`oauth-domain — manage extra allowed domains for OAuth-issued tokens
|
|
7062
7062
|
|
|
7063
7063
|
Usage:
|
|
7064
7064
|
oauth-domain list List extra domains for every provider
|
|
@@ -7083,7 +7083,7 @@ Examples:
|
|
|
7083
7083
|
oauth-domain add adobe '*.da.live'
|
|
7084
7084
|
oauth-domain list adobe
|
|
7085
7085
|
oauth-domain remove adobe admin.da.live
|
|
7086
|
-
`}function
|
|
7086
|
+
`}function zae(){return B(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:H5(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-Bv01tMmE.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(`
|
|
7087
7087
|
`)+`
|
|
7088
7088
|
`,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)
|
|
7089
7089
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7091,7 +7091,7 @@ Examples:
|
|
|
7091
7091
|
`,stderr:``,exitCode:0}}case`add`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
7092
7092
|
`,exitCode:1};let e=t(a),r=o.toLowerCase();return e.some(e=>e.toLowerCase()===r)?{stdout:`(${o} already in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,[...e,o]),{stdout:`Added ${o} to ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`remove`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
7093
7093
|
`,exitCode:1};let e=t(a),r=o.toLowerCase(),i=e.filter(e=>e.toLowerCase()!==r);return i.length===e.length?{stdout:`(${o} not found in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,i),{stdout:`Removed ${o} from ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`clear`:return a?(await n(a,[]),{stdout:`Cleared extra domains for ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`oauth-domain clear: requires <providerId>
|
|
7094
|
-
`,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${H5()}`,exitCode:1}}}catch(e){return{stdout:``,stderr:`oauth-domain: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function
|
|
7094
|
+
`,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${H5()}`,exitCode:1}}}catch(e){return{stdout:``,stderr:`oauth-domain: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Bae(){return`oauth-token — get an OAuth access token for a provider, or run an
|
|
7095
7095
|
ad-hoc OAuth interception against an arbitrary authorize URL.
|
|
7096
7096
|
|
|
7097
7097
|
Usage:
|
|
@@ -7141,16 +7141,16 @@ Examples:
|
|
|
7141
7141
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7142
7142
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7143
7143
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7144
|
-
`}function
|
|
7144
|
+
`}function Vae(){return B(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-Bv01tMmE.js`),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-BoV1YFxZ.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Bae(),stderr:``,exitCode:0};if(e.includes(`--list`))return Wae(i,o,a,n);if(e.includes(`--renew`))return Hae(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return Uae(e,t);let s,c=e.indexOf(`--scope`);if(c>=0){if(s=e[c+1]?.trim(),!s||s.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
|
|
7145
7145
|
`,exitCode:1};e.splice(c,2)}let l,u=e.indexOf(`--provider`);if(u>=0){if(l=e[u+1],!l)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
7146
7146
|
`,exitCode:1}}else if(e.length>0)l=e[0];else{let e=r(),t=a(e);if(t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted))l=e;else if(l=o().find(e=>{let t=a(e);return t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted)}),!l)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
7147
7147
|
`,exitCode:1}}let d=a(l);if(!d)return{stdout:``,stderr:`oauth-token: unknown provider "${l}"\n`,exitCode:1};if(!d.isOAuth||!d.onOAuthLogin&&!d.onOAuthLoginIntercepted)return{stdout:``,stderr:`oauth-token: provider "${l}" is not an OAuth provider\n`,exitCode:1};if(!s){let e=n(l);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}}try{if(d.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:e}=await import(`./oauth-service-foejPYvF.js`),t=await e();if(!t)return{stdout:``,stderr:`oauth-token: provider "${l}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.\n`,exitCode:1};await d.onOAuthLoginIntercepted(t,()=>{},s?{scopes:s}:void 0)}else if(d.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-foejPYvF.js`),t=e();await d.onOAuthLogin(t,()=>{},s?{scopes:s}:void 0)}else return{stdout:``,stderr:`oauth-token: provider "${l}" has no OAuth login hook\n`,exitCode:1};let e=n(l);if(e?.token){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${l}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
7148
|
-
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function
|
|
7148
|
+
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function Hae(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-Bv01tMmE.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BoV1YFxZ.js`).then(e=>e.r),a=e.filter(e=>!e.startsWith(`-`))[0];if(!a){let e=t();a=r(e)?.onSilentRenew?e:i().find(e=>r(e)?.onSilentRenew)}if(!a)return G5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return G5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return G5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${U5(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: ${U5(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(`
|
|
7149
7149
|
`)+`
|
|
7150
|
-
`,stderr:``,exitCode:+!u}}function U5(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
|
|
7150
|
+
`,stderr:``,exitCode:+!u}}function U5(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 Uae(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-foejPYvF.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return G5(`oauth-token: --from-file requires a path`);try{let e=t.fs.resolvePath(t.cwd,n),r=await t.fs.readFile(e);i=JSON.parse(typeof r==`string`?r:new TextDecoder().decode(r))}catch(e){return G5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=W5(e,`--authorize-url`),n=W5(e,`--redirect-pattern`);if(!t)return G5(`oauth-token: --authorize-url is required`);if(!n)return G5(`oauth-token: --redirect-pattern is required`);let r=[];for(let t=0;t<e.length;t++){if(e[t]!==`--rewrite`)continue;let n=e[t+1];if(!n)return G5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return G5(`oauth-token: --rewrite "${n}" must be "<match>=<key>=<value>"`);let[a,o,...s]=i;r.push({match:a,appendParams:{[o]:s.join(`=`)}})}i={authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.length>0?{rewrite:r}:{}}}let o=n(i);if(!o.ok)return G5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return G5(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let c=await s(o.config);return c?{stdout:`${c}\n`,stderr:``,exitCode:0}:G5(`oauth-token: intercept timed out or was cancelled`)}function W5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function G5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function Wae(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7151
7151
|
`,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`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
7152
7152
|
`)+`
|
|
7153
|
-
`,stderr:``,exitCode:0}}const
|
|
7153
|
+
`,stderr:``,exitCode:0}}const Gae=new Set([`--download`,`-d`,`--view`,`-v`]),K5={low:256,medium:768,high:1536};function q5(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
7154
7154
|
|
|
7155
7155
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
7156
7156
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -7164,19 +7164,19 @@ Examples:
|
|
|
7164
7164
|
medium (768x768), high (1536x1536), or a custom WxH
|
|
7165
7165
|
box like 512x512. The image is fit inside the box
|
|
7166
7166
|
with aspect ratio preserved and is never upscaled.
|
|
7167
|
-
`,stderr:``,exitCode:0}}function
|
|
7167
|
+
`,stderr:``,exitCode:0}}function Kae(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function qae(e){if(e in K5){let t=K5[e];return{maxW:t,maxH:t}}let t=/^(\d+)x(\d+)$/.exec(e);if(t){let e=parseInt(t[1],10),n=parseInt(t[2],10);if(e>0&&n>0)return{maxW:e,maxH:n}}return null}function Jae(e,t){if(t===`image/png`||t===`image/apng`){if(e.length<26)return!1;let t=e[25];return t===4||t===6}if(t===`image/webp`){if(e.length<16)return!1;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);return t===`VP8L`?!0:t===`VP8X`?e.length<21?!1:(e[20]&16)!=0:!1}return!1}function Yae(){return`open --view requires --size to bound the inlined image. Use one of:
|
|
7168
7168
|
--size low (256x256)
|
|
7169
7169
|
--size medium (768x768)
|
|
7170
7170
|
--size high (1536x1536)
|
|
7171
7171
|
--size WxH (custom box, e.g. 512x512)
|
|
7172
|
-
`}const
|
|
7173
|
-
`)}async function
|
|
7174
|
-
`);let r;try{r=await n(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e}${Z5(r)}`)}async function
|
|
7175
|
-
`);let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=new Uint8Array(a.byteLength);o.set(a);let s=new Blob([o.buffer],{type:_n(t)}),c=URL.createObjectURL(s),l=document.createElement(`a`);return l.href=c,l.download=wn(t)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),Y5(`downloaded ${t}`)}async function
|
|
7176
|
-
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=An(e,await Tn(t.fs,i?e:un(e))),o;try{o=await r(a)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e} → ${a}${Z5(o)}`)}async function
|
|
7177
|
-
`);if(mn(e))return
|
|
7172
|
+
`}const Xae=new Set([`image/png`,`image/webp`]);function J5(e){let t=new ArrayBuffer(e.byteLength),n=new Uint8Array(t);return n.set(e),n}async function Zae(e,t){let n=J5(e),r=new Blob([n],{type:t}),i=await createImageBitmap(r);try{return{width:i.width,height:i.height}}finally{i.close?.()}}async function Qae(e,t,n,r){let i=J5(e),a=new Blob([i],{type:t}),o=await createImageBitmap(a);try{let i=o.width,a=o.height,s=Math.min(n/i,r/a,1),c=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(a*s)),u=new OffscreenCanvas(c,l),d=u.getContext(`2d`);if(!d)throw Error(`failed to acquire 2d context for resize`);d.drawImage(o,0,0,c,l);let f=Jae(e,t)?Xae.has(t)?t:`image/png`:`image/jpeg`,p=await u.convertToBlob(f===`image/jpeg`?{type:`image/jpeg`,quality:.85}:{type:f});return{bytes:new Uint8Array(await p.arrayBuffer()),mime:f,width:c,height:l,nativeWidth:i,nativeHeight:a}}finally{o.close?.()}}function $ae(e){let t={download:!1,view:!1,sizeSpec:void 0,targets:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--download`||r===`-d`)t.download=!0;else if(r===`--view`||r===`-v`)t.view=!0;else if(r===`--size`){let r=e[n+1];if(r===void 0||Gae.has(r)||r===`--size`||r.startsWith(`--size=`))return t.error=`open: --size requires a value (low|medium|high|WxH)`,t;t.sizeSpec=r,n++}else r.startsWith(`--size=`)?t.sizeSpec=r.slice(7):t.targets.push(r)}return t}function Y5(e){return{ok:!0,message:e}}function X5(e){return{ok:!1,result:{stdout:``,stderr:e,exitCode:1}}}function Z5(e){return e?` (targetId: ${e})`:``}function eoe(e,t,n){return async r=>{if(e)return e.createPage(r);if(t){window.open(r,`_blank`,`noopener,noreferrer`);return}try{await n.call(`window-open`,{url:r,target:`_blank`,features:`noopener,noreferrer`})}catch(e){throw Error(`open: ${e instanceof Error?e.message:String(e)}`)}}}async function toe(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,e);if(n){let e=(a.split(`/`).pop()??``).replace(/\.shtml$/,``);try{return await n.open(e),Y5(`opened sprinkle ${e} from ${a}`)}catch(e){return X5(`open: ${e instanceof Error?e.message:String(e)}\n`)}}if(r){let e=An(a,await Tn(t.fs,un(a))),n;try{n=await i(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${a} → ${e}${Z5(n)}`)}return X5(`open: sprinkle manager not initialized
|
|
7173
|
+
`)}async function noe(e,t,n){if(!t)return X5(`open: browser APIs are unavailable in this environment
|
|
7174
|
+
`);let r;try{r=await n(e)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e}${Z5(r)}`)}async function roe(e,t,n,r){let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=_n(t),s=new Uint8Array(a),c=null;if(r!==void 0&&(c=qae(r),!c))return X5(`open: invalid --size spec '${r}' (expected low|medium|high or WxH such as 512x512)\n`);if(!c){let n;try{n=await Zae(s,o)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let r=Math.round(s.byteLength/1024);return X5(`open --view: ${t} is ${n.width}x${n.height} (${r} KB, ${o})\n`+Yae())}let l;try{l=await Qae(s,o,c.maxW,c.maxH)}catch(t){return X5(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let u=Kae(l.bytes),d=Math.round(l.bytes.byteLength/1024);return Y5(`${t} (${l.nativeWidth}x${l.nativeHeight} → ${l.width}x${l.height}, ${d} KB, ${l.mime})\n<img:data:${l.mime};base64,${u}>`)}async function ioe(e,t,n,r){if(!r)return X5(`open: --download requires the in-panel terminal (DOM-only)
|
|
7175
|
+
`);let i;try{i=await n.fs.stat(t)}catch{return X5(`open: no such file: ${e}\n`)}if(!i.isFile)return X5(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return X5(`open: failed to read: ${e}\n`)}let o=new Uint8Array(a.byteLength);o.set(a);let s=new Blob([o.buffer],{type:_n(t)}),c=URL.createObjectURL(s),l=document.createElement(`a`);return l.href=c,l.download=wn(t)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),Y5(`downloaded ${t}`)}async function aoe(e,t,n,r){if(!n)return X5(`open: browser APIs are unavailable in this environment
|
|
7176
|
+
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=An(e,await Tn(t.fs,i?e:un(e))),o;try{o=await r(a)}catch(e){return X5(`${e instanceof Error?e.message:String(e)}\n`)}return Y5(`opened ${e} → ${a}${Z5(o)}`)}async function ooe(e,t,n,r){if(!mn(e)&&e.endsWith(`.shtml`)&&t.fs)return toe(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return X5(`open: browser APIs are unavailable in this environment
|
|
7177
|
+
`);if(mn(e))return noe(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?roe(e,i,t,n.sizeSpec):n.download?ioe(e,i,t,r.hasDom):aoe(i,t,r.canOpenWindow,r.openExternal)}function soe(e){return B(`open`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return q5();let r=$ae(t);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:a,view:o,sizeSpec:s,targets:c}=r;if(c.length===0)return q5();let l=globalThis.__slicc_sprinkleManager,u=typeof window<`u`&&typeof document<`u`,d=u?null:i(),f={canOpenWindow:!!e||u||!!d,hasDom:u,sprinkleManager:l,openExternal:eoe(e,u,d)},p=[];for(let e of c){let t=await ooe(e,n,{view:o,download:a,sizeSpec:s},f);if(!t.ok)return t.result;p.push(t.message)}return{stdout:p.join(`
|
|
7178
7178
|
`)+`
|
|
7179
|
-
`,stderr:``,exitCode:0}})}let Q5=null,$5=null;async function e7(){return Q5||=import(`./es-CP2z28j0.js`),Q5}async function
|
|
7179
|
+
`,stderr:``,exitCode:0}})}let Q5=null,$5=null;async function e7(){return Q5||=import(`./es-CP2z28j0.js`),Q5}async function coe(){return $5||=import(`./dist-Cc2eS9kS.js`),$5}function loe(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function t7(e){let{range:t,rotation:n}=loe(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function n7(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function uoe(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
|
|
7180
7180
|
|
|
7181
7181
|
Operations:
|
|
7182
7182
|
dump_data Print metadata (page count, title, author, etc.)
|
|
@@ -7200,14 +7200,14 @@ Page ranges:
|
|
|
7200
7200
|
1-endright Pages 1 to end, rotated 90° clockwise
|
|
7201
7201
|
3left Page 3 rotated 270° (counterclockwise)
|
|
7202
7202
|
1-5down Pages 1-5 rotated 180°
|
|
7203
|
-
`,stderr:``,exitCode:0}}function r7(e=`pdftk`){return B(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return
|
|
7203
|
+
`,stderr:``,exitCode:0}}function r7(e=`pdftk`){return B(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return uoe();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await e7(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
|
|
7204
7204
|
`)+`
|
|
7205
|
-
`,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await
|
|
7206
|
-
`,stderr:``,exitCode:0}}if(a===`cat`){let a=await e7(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>{o.addPage(e)});continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=t7(t),c=n7(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await e7(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=t7(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=n7(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}const i7=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],
|
|
7207
|
-
`,exitCode:1};let r=
|
|
7208
|
-
`,exitCode:2};let a=
|
|
7205
|
+
`,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await coe(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
|
|
7206
|
+
`,stderr:``,exitCode:0}}if(a===`cat`){let a=await e7(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>{o.addPage(e)});continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=t7(t),c=n7(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await e7(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=t7(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=n7(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}const i7=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],doe=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],foe={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function poe(e={}){return B(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return Toe();let n=e.processManager??moe();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
7207
|
+
`,exitCode:1};let r=doe,i=!1,a=!1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`-a`||n===`-A`||n===`-e`||n===`--all`){a=!0;continue}if(n===`-T`||n===`--tree`){i=!0;continue}if(n===`-o`||n.startsWith(`--columns=`)||n.startsWith(`-o=`)){let i=n.startsWith(`-o=`)?n.slice(3):n.startsWith(`--columns=`)?n.slice(10):t[++e];if(typeof i!=`string`)return{stdout:``,stderr:`ps: -o requires an argument
|
|
7208
|
+
`,exitCode:2};let a=hoe(i);if(a instanceof Error)return{stdout:``,stderr:`ps: ${a.message}\n`,exitCode:2};r=a;continue}return{stdout:``,stderr:`ps: unrecognized argument '${n}'\n`,exitCode:2}}let o=n.list().sort((e,t)=>e.pid-t.pid),s=a?o:o.filter(e=>e.status===`running`||e.status===`pending`),c=(i?woe(s):s.map(e=>({proc:e,depth:0}))).map(({proc:e,depth:t})=>voe(e,r,t,i));return{stdout:[goe(r),...c].join(`
|
|
7209
7209
|
`)+`
|
|
7210
|
-
`,stderr:``,exitCode:0}})}function
|
|
7210
|
+
`,stderr:``,exitCode:0}})}function moe(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.list==`function`?e:null}function hoe(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Error(`-o requires at least one column`);let n=[];for(let e of t){if(!i7.includes(e))return Error(`unknown column '${e}'; supported: ${i7.join(`, `)}`);n.push(e)}return n}function goe(e){return e.map(e=>_oe(e)).join(` `)}function _oe(e){switch(e){case`pid`:return`PID`.padStart(5);case`ppid`:return`PPID`.padStart(5);case`kind`:return`KIND`.padEnd(10);case`stat`:return`STAT`;case`start`:return`START`;case`scoop`:return`SCOOP`.padEnd(10);case`command`:return`COMMAND`}}function voe(e,t,n,r){return t.map(t=>yoe(e,t,n,r)).join(` `)}function yoe(e,t,n,r){switch(t){case`pid`:return String(e.pid).padStart(5);case`ppid`:return String(e.ppid).padStart(5);case`kind`:return e.kind.padEnd(10);case`stat`:return foe[e.status];case`start`:return boe(e.startedAt);case`scoop`:return xoe(e).padEnd(10);case`command`:return Soe(e,n,r)}}function boe(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`}function xoe(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?.slice(0,10)??`scoop`}function Soe(e,t,n){let r=n&&t>0?` `.repeat(t-1)+`└─ `:``,i=e.argv.length===0?`[${e.kind}]`:e.argv.map(Coe).join(` `);return r+(i.length>80?i.slice(0,79)+`…`:i)}function Coe(e){return e===``?`''`:/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function woe(e){let t=new Map;for(let n of e)t.set(n.pid,n);let n=new Map,r=[];for(let i of e)if(t.has(i.ppid)){let e=n.get(i.ppid)??[];e.push(i),n.set(i.ppid,e)}else r.push(i);let i=[],a=new Set,o=(e,t)=>{if(a.has(e.pid))return;a.add(e.pid),i.push({proc:e,depth:t});let r=n.get(e.pid)??[];for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,t+1)};for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,0);return i}function Toe(){return{stdout:`Usage: ps [-a] [-T] [-o col[,col…]]
|
|
7211
7211
|
|
|
7212
7212
|
List processes tracked by the kernel.
|
|
7213
7213
|
|
|
@@ -7237,9 +7237,9 @@ Examples:
|
|
|
7237
7237
|
ps -T live tree
|
|
7238
7238
|
ps -a -T full tree
|
|
7239
7239
|
ps -o pid,kind,stat just three columns
|
|
7240
|
-
`,stderr:``,exitCode:0}}const
|
|
7241
|
-
`,stderr:``,exitCode:0}}function
|
|
7242
|
-
`,stderr:``,exitCode:0}}async function
|
|
7240
|
+
`,stderr:``,exitCode:0}}const Eoe=new Set([`dev`,`proc`,`lib`,`bin`,`usr`,`etc`,`home`,`tmp`]);async function Doe(e,t=Eoe){let n=[],r=new Set;try{let i=await e.readdir(`/`);for(let a of i){if(!a||a.includes(`/`)||t.has(a))continue;let i=`/${a}`,o=!1;try{o=!!(await e.stat(i)).isDirectory}catch{continue}o&&(r.has(i)||(r.add(i),n.push(i)))}}catch{}return r.has(`/tmp`)||(r.add(`/tmp`),n.push(`/tmp`)),n}function Ooe(e,t){let n=e;if(typeof n.listMountPoints!=`function`)return[];let r=e=>{for(let n of t)if(e===n||e.startsWith(n===`/`?`/`:n+`/`)||n.startsWith(e+`/`))return!0;return!1},i=[];for(let e of n.listMountPoints())e.kind!==`proc`&&r(e.path)&&i.push({path:e.path,kind:e.kind});return i}function koe(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`slicc-fs`}catch{}}function Aoe(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},fromDir:e.cwd}}async function joe(e,t){try{let n=await e.readFile(`${t}/package.json`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function Moe(e,t){return`installed pyodide ${e} is not the supported version ${t}: run \`ipk uninstall pyodide\` then \`ipk add pyodide@${t}\``}function Noe(){return{stdout:`usage: python3 [-c code | script.py] [args...]
|
|
7241
|
+
`,stderr:``,exitCode:0}}function Poe(){return{stdout:`Python 3.14 (Pyodide)
|
|
7242
|
+
`,stderr:``,exitCode:0}}async function Foe(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return rZ(n.stdin).trim().length>0?{kind:`ok`,code:rZ(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function Ioe(e){let t=Aoe(e),n=await zz(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${Lz}\n`,exitCode:1}};let r=await joe(t.reader,n);return r?r===Fz?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${Moe(r,Fz)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${Lz}\n`,exitCode:1}}}function a7(e,t={}){return B(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return Noe();if(n.includes(`--version`)||n.includes(`-V`))return Poe();let i=await Foe(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await Doe(r.fs),u=Ooe(r.fs,l),d=t.buildProcessConfig?.(),f=d?.processManager??Loe(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??Mq(),g=t.pyodideIndexURL??Iq(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await Ioe(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:rZ(r.stdin),y=koe();return f?QX({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):Roe({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function Loe(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let o7=null;async function Roe(e){if(!o7){let{ProcessManager:e}=await import(`./process-manager-B5dz0PkO.js`).then(e=>e.n);o7=new e}return QX({pm:o7,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function s7(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function zoe(){return null}function Boe(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=c7(r),o=c7(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function c7(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function l7(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
|
|
7243
7243
|
|
|
7244
7244
|
Usage:
|
|
7245
7245
|
rsync [flags] <local-path> <runtime-id>:<remote-path> # push
|
|
@@ -7255,21 +7255,21 @@ Examples:
|
|
|
7255
7255
|
rsync /workspace follower-abc123:/workspace
|
|
7256
7256
|
rsync --delete /shared leader:/shared
|
|
7257
7257
|
rsync follower-abc123:/workspace/project /workspace/project
|
|
7258
|
-
`,stderr:``,exitCode:0}}async function u7(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function d7(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function
|
|
7258
|
+
`,stderr:``,exitCode:0}}async function u7(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function d7(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function Voe(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function Hoe(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function f7(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function Uoe(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=s7(await u7(e,i),await d7(t,o,a),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7259
7259
|
`)+`
|
|
7260
|
-
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await
|
|
7260
|
+
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let s=i+`/`+n,c=a+`/`+n;await Hoe(t,o,f7(c));let l=await t(o,{op:`writeFile`,path:c,content:f(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!l[0].ok)return{stdout:r.join(`
|
|
7261
7261
|
`)+`
|
|
7262
7262
|
`,stderr:`Error writing ${c}: ${l[0].error}\n`,exitCode:1}}for(let e of l.toDelete){let n=a+`/`+e,i=await t(o,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
|
|
7263
7263
|
`)+`
|
|
7264
7264
|
`,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7265
7265
|
`)+`
|
|
7266
|
-
`,stderr:``,exitCode:0}}async function
|
|
7266
|
+
`,stderr:``,exitCode:0}}async function Woe(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=s7(await d7(t,o,a),await u7(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7267
7267
|
`)+`
|
|
7268
|
-
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=f7(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=h(await
|
|
7268
|
+
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=f7(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=h(await Voe(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7269
7269
|
`)+`
|
|
7270
|
-
`,stderr:``,exitCode:0}}function
|
|
7270
|
+
`,stderr:``,exitCode:0}}function Goe(e={}){let t=e.fs,n=e.getSendFsRequest??zoe;return B(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return l7();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
|
|
7271
7271
|
`,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
|
|
7272
|
-
`,exitCode:1};let i=
|
|
7272
|
+
`,exitCode:1};let i=Boe(e);if(`error`in i)return i.error===`__help__`?l7():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await Uoe(t,r,i):await Woe(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function p7(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
|
|
7273
7273
|
say --status | --warmup
|
|
7274
7274
|
|
|
7275
7275
|
Speaks the given text. Uses on-device Kokoro voices when the model
|
|
@@ -7289,11 +7289,11 @@ Examples:
|
|
|
7289
7289
|
`,stderr:``,exitCode:0}}function m7(e){switch(e.state){case`ready`:return`voice engine: ready
|
|
7290
7290
|
`;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
|
|
7291
7291
|
`;case`idle`:return`voice engine: not downloaded (run say --warmup)
|
|
7292
|
-
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function h7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function g7(e){return e instanceof Error?e.message:String(e)}let _7=!1,v7=null;function y7(){return _7?Promise.resolve(speechSynthesis.getVoices()):(v7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){_7=!0,e(t);return}let n=()=>{_7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),_7=!0,e(speechSynthesis.getVoices())},1e3)}),v7)}const b7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function
|
|
7292
|
+
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function h7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function g7(e){return e instanceof Error?e.message:String(e)}let _7=!1,v7=null;function y7(){return _7?Promise.resolve(speechSynthesis.getVoices()):(v7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){_7=!0,e(t);return}let n=()=>{_7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),_7=!0,e(speechSynthesis.getVoices())},1e3)}),v7)}const b7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function Koe(e,t,n){switch(t){case`-v`:return e.voiceName=n,null;case`-l`:return e.lang=n,null;case`-o`:case`--out`:return e.outFile=n,null;case`-r`:{let t=parseFloat(n);return Number.isNaN(t)||t<.1||t>10?`rate must be between 0.1 and 10`:(e.rate=t,null)}default:return`unknown option: ${t}`}}function qoe(e){let t={voiceName:null,rate:1,lang:null,outFile:null,text:``},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i in b7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return h7(`${i} requires ${b7[i]}`);let a=Koe(t,i,n);if(a)return h7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return h7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function x7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function Joe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-aEIq7SEP.js`),t=e().map(e=>x7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await y7()).map(e=>x7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
|
|
7293
7293
|
`)+`
|
|
7294
7294
|
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>x7(e)).join(`
|
|
7295
7295
|
`)+`
|
|
7296
|
-
`,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function
|
|
7296
|
+
`,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function Yoe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-aEIq7SEP.js`),n=t().map(e=>({name:e.id})),r=(await y7()).map(e=>({name:e.name}));return[...n,...r]}async function Xoe(e,t){let n=(await Yoe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:h7(`voice "${t}" not found. Use --list to see available voices.`)}}async function S7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-aEIq7SEP.js`);return{stdout:m7(t?n():e()),stderr:``,exitCode:0}}return{stdout:m7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function Zoe(e,t){return t.includes(`--list`)?Joe(e):t.includes(`--status`)?S7(e,!1):t.includes(`--warmup`)?S7(e,!0):null}async function Qoe(e){try{let{speak:t}=await import(`./speak-aEIq7SEP.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(`speech synthesis error: ${g7(e)}`)}}async function $oe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return h7(g7(e))}}async function ese(e){let{synthesizeToWav:t}=await import(`./speak-aEIq7SEP.js`);try{return{bytes:await t(e)}}catch(e){return h7(g7(e))}}async function tse(e,t){try{let n=await e.panelRpc.call(`synthesize-to-wav`,{text:t.text,lang:t.lang,...t.voice?{voice:t.voice}:{},rate:t.rate},{timeoutMs:5*6e4});return{bytes:new Uint8Array(n.bytes)}}catch(e){return h7(g7(e))}}async function nse(e,t,n,r){let i=e.local?await ese(r):await tse(e,r);if(`exitCode`in i)return i;let a=t.fs.resolvePath(t.cwd,n);try{await t.fs.writeFile(a,i.bytes)}catch(e){return h7(`failed to write ${n}: ${g7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function rse(){return B(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return p7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:i()};if(!n.local&&!n.panelRpc)return h7(`Web Speech API unavailable in this environment`);let r=await Zoe(n,e);if(r)return r;let a=qoe(e);if(`exitCode`in a)return a;if(!a.text)return p7();if(!a.lang)return h7(`-l language tag is required`);let o;if(a.voiceName){let{resolved:e,error:t}=await Xoe(n,a.voiceName);if(t)return t;o=e}let s={text:a.text,lang:a.lang,voice:o,rate:a.rate};return a.outFile?nse(n,t,a.outFile,s):n.local?Qoe(s):$oe(n,s)})}function ise(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
|
|
7297
7297
|
|
|
7298
7298
|
Usage: screencapture [options] <output-file>
|
|
7299
7299
|
|
|
@@ -7309,12 +7309,12 @@ Examples:
|
|
|
7309
7309
|
screencapture screenshot.png # Capture to file
|
|
7310
7310
|
screencapture -c # Capture to clipboard
|
|
7311
7311
|
screencapture -v capture.png # Capture and return for agent vision
|
|
7312
|
-
`,stderr:``,exitCode:0}}function
|
|
7313
|
-
`,exitCode:1};if(n&&!
|
|
7312
|
+
`,stderr:``,exitCode:0}}function ase(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function ose(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function sse(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(r,0,0,i,a);let c=await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)});return{bytes:new Uint8Array(await c.arrayBuffer()),mimeType:e}}finally{n.getTracks().forEach(e=>{e.stop()})}}function cse(){return B(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return ise();let n=a(),r=i();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
|
|
7313
|
+
`,exitCode:1};if(n&&!c4()&&!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
|
|
7314
7314
|
`,exitCode:1};let o=e.includes(`--clipboard`)||e.includes(`-c`),s=e.includes(`--view`)||e.includes(`-v`),c=[`--clipboard`,`-c`,`--view`,`-v`,`--help`,`-h`],l=e.indexOf(`--`),u=(l>=0?e.slice(l+1):e.filter(e=>!c.includes(e)))[0];if(!o&&!u)return{stdout:``,stderr:`screencapture: output file required (or use -c for clipboard)
|
|
7315
|
-
`,exitCode:1};let d=u||`screenshot.png`,f=
|
|
7316
|
-
`,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(o)try{if(
|
|
7317
|
-
`,exitCode:1};if(n){let e=await
|
|
7315
|
+
`,exitCode:1};let d=u||`screenshot.png`,f=ose(d),p=f===`image/png`?1:.92,m;try{if(c4())m=(await u4({kind:`screen`,mimeType:f,quality:p})).bytes;else if(n)m=(await sse(f,p)).bytes;else{let e=await r.call(`screencapture`,{mimeType:f,quality:p},{timeoutMs:5*6e4});m=new Uint8Array(e.bytes)}}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
|
|
7316
|
+
`,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(o)try{if(c4()&&typeof document<`u`&&typeof document.hasFocus==`function`&&!document.hasFocus())return{stdout:``,stderr:`screencapture: clipboard capture needs a focused window; save to a file instead
|
|
7317
|
+
`,exitCode:1};if(n){let e=await lse(m,f),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await use(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{stdout:`captured ${Math.round(n.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}return await r.call(`clipboard-write-image`,{bytes:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),mimeType:f},{timeoutMs:5*6e4}),{stdout:`captured ${Math.round(m.byteLength/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let h=t.fs.resolvePath(t.cwd,d);try{await t.fs.writeFile(h,m)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let g=Math.round(m.length/1024);return s?{stdout:`${h} (${g} KB)\n<img:data:${f};base64,${ase(m)}>`,stderr:``,exitCode:0}:{stdout:`captured ${g} KB to ${wn(h)}\n`,stderr:``,exitCode:0}})}async function lse(e,t){if(t===`image/png`)return e;let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=new Blob([n],{type:t}),i=URL.createObjectURL(r);try{let e=new Image;await new Promise((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(Error(`Failed to load image for conversion`)),e.src=i});let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(`Failed to get canvas context`);n.drawImage(e,0,0);let r=await new Promise((e,n)=>{t.toBlob(t=>t?e(t):n(Error(`Failed to create PNG blob`)),`image/png`)});return new Uint8Array(await r.arrayBuffer())}finally{URL.revokeObjectURL(i)}}async function use(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}function dse(e){return new Promise((t,n)=>{chrome.runtime.sendMessage(e,e=>{let r=chrome.runtime.lastError;if(r){n(Error(r.message??`chrome.runtime.lastError`));return}t(e)})})}async function C7(e,t,n){let r={method:e,headers:b({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(y(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function fse(){return{async list(){let[e,t]=await Promise.all([C7(`GET`,``),C7(`GET`,`/session`)]),n=[];if(e.ok)for(let t of e.data)n.push({name:t.name,domains:t.domains,persisted:!0});if(t.ok)for(let e of t.data)n.push({name:e.name,domains:e.domains,persisted:!1});return n},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){let{ok:t,data:n}=await C7(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await C7(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await C7(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await C7(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error(T7(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await C7(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error(T7(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await C7(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error(T7(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function w7(e){let t=t=>e(t);return{async list(){let[e,n]=await Promise.all([t({type:`secrets.list`}),t({type:`secrets.session.list`})]),r=[];for(let t of e?.entries??[])r.push({name:t.name,domains:t.domains,persisted:!0});for(let e of n?.entries??[])r.push({name:e.name,domains:e.domains,persisted:!1});return r},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){return((await t({type:`secrets.list-masked-entries`}))?.entries??[]).find(t=>t.name===e)??null},async peek(e){let n=await t({type:`secrets.peek`,name:e});if(n?.error)throw Error(n.error);return n?.record??null},async setSession(e,n,r){let i=await t({type:`secrets.session.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.session.set failed`)},async setPersisted(e,n,r){let i=await t({type:`secrets.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.set failed`)},async setScope(e,n){let r=await t({type:`secrets.set-domains`,name:e,domains:n});if(!r?.ok)throw Error(r?.error??`secrets.set-domains failed`)},async delete(e){let n=await t({type:`secrets.delete`,name:e});if(!n?.ok)throw Error(n?.error??`secrets.delete failed`);return{removed:n.removed??!0,fromSession:n.fromSession}}}}function pse(){return w7(e=>dse(e))}function mse(){return w7(e=>{let{type:t,...n}=e;return ee(t,n)})}function T7(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function hse(e){switch(e){case`extension-direct`:return pse();case`extension-delegate`:return mse();default:return fse()}}function gse(){return`secret — manage secrets for the fetch proxy and mount backends
|
|
7318
7318
|
|
|
7319
7319
|
No approval (session-only, in-memory, never persisted):
|
|
7320
7320
|
secret set <name> <value> [--domain <pat>] Set a session secret. Free for a
|
|
@@ -7351,24 +7351,24 @@ Examples:
|
|
|
7351
7351
|
secret peek OPENAI_KEY
|
|
7352
7352
|
secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
|
|
7353
7353
|
secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
|
|
7354
|
-
`}function E7(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const
|
|
7355
|
-
`,exitCode:1}}function
|
|
7354
|
+
`}function E7(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const _se={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},vse=new Set;function D7(e,t){if(e===t)return!0;try{return Tt(e).test(t)}catch{return!1}}function yse(e,t){for(let n of e)if(D7(n,t))return!0;return!1}function O7(){return{stdout:``,stderr:`secret: approval denied
|
|
7355
|
+
`,exitCode:1}}function bse(e){let t=O(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??hse(t),i=e.grants??vse,a=e.broker,o=()=>(a??=VE(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(yse(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${_se[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&D7(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&pO(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function xse(e){let t=rZ(e);if(t.length!==0)return t.endsWith(`\r
|
|
7356
7356
|
`)?t.slice(0,-2):t.endsWith(`
|
|
7357
|
-
`)?t.slice(0,-1):t}async function
|
|
7358
|
-
`,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):O7()}async function
|
|
7359
|
-
`,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=
|
|
7357
|
+
`)?t.slice(0,-1):t}async function Sse(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
|
|
7358
|
+
`,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):O7()}async function Cse(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?O7():(await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}"${n.length>0?` (domains: ${n.join(`, `)})`:``} — in-memory only, not persisted.\n`,stderr:``,exitCode:0})}async function wse(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
|
|
7359
|
+
`,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=xse(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
|
|
7360
7360
|
`,exitCode:1};let o=i??a;if(o===void 0)return{stdout:``,stderr:`secret: set requires a <value>: secret set <name> <value> [--domain <patterns>] [--persist]
|
|
7361
7361
|
or pipe the value on stdin: echo "$TOKEN" | secret set <name> [--domain ...]
|
|
7362
|
-
`,exitCode:1};let s=E7(e)??[];return e.includes(`--persist`)?
|
|
7363
|
-
`,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7364
|
-
`,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7362
|
+
`,exitCode:1};let s=E7(e)??[];return e.includes(`--persist`)?Sse(r,o,s,n):Cse(r,o,s,n)}async function Tse(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
|
|
7363
|
+
`,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function Ese(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
|
|
7364
|
+
`,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function Dse(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
|
|
7365
7365
|
`,exitCode:1};let r=E7(e)??[];return r.length===0?{stdout:``,stderr:`secret: scope requires --domain <patterns>
|
|
7366
|
-
`,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):O7()}async function
|
|
7367
|
-
`,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function
|
|
7368
|
-
`,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?C(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7366
|
+
`,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):O7()}async function Ose(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
|
|
7367
|
+
`,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function kse(e,t,n){let r=e[1];if(!r)return{stdout:``,stderr:`secret: ${t} requires a <name>\n`,exitCode:1};let i=await n.backend.delete(r);return i.removed?{stdout:`Removed ${i.fromSession===!0?`session`:`persisted`} secret "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function Ase(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
|
|
7368
|
+
`,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?C(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function jse(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
|
|
7369
7369
|
(changes are picked up on the next request — no restart needed)
|
|
7370
7370
|
`,stderr:``,exitCode:0};try{return await chrome.runtime.openOptionsPage(),{stdout:`Opened Mount Secrets options page in a new tab.
|
|
7371
|
-
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function
|
|
7371
|
+
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function Mse(e,t,n){let r=e[0];switch(r){case`set`:return wse(e,t,n);case`get`:case`read`:return Tse(e,n);case`peek`:return Ese(e,n);case`scope`:return Dse(e,n);case`list`:return Ose(n);case`delete`:case`rm`:return kse(e,r,n);case`test`:return Ase(e,n);case`edit`:return jse(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function Nse(e={}){let t=bse(e);return B(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:gse(),stderr:``,exitCode:0};try{return await Mse(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function Pse(){return null}function k7(){return null}function Fse(){return globalThis.__slicc_lickManager??null}let A7=null;async function Ise(){if(A7)return A7;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return A7=e(),A7}async function j7(){let e=Fse();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(D())return null;let t=await Ise(),{listWebhooksAsync:n}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return{createWebhook:(e,n,r)=>t.createWebhook(e,n,r),deleteWebhook:e=>t.deleteWebhook(e),listWebhooks:()=>n()}}function M7(){return{stdout:`usage: serve [--entry <relative-path>] [--bridge | --no-bridge] [--max-tabs <n>] [--quiet] [--stop <token>] [--list] <directory>
|
|
7372
7372
|
|
|
7373
7373
|
Mint a worker-hosted preview URL for a VFS directory, broadcast it to
|
|
7374
7374
|
all connected followers, and open it in the leader's browser.
|
|
@@ -7384,17 +7384,17 @@ Examples:
|
|
|
7384
7384
|
--list List active previews on this tray.
|
|
7385
7385
|
--project Obsolete; ignored. Root-absolute paths work natively
|
|
7386
7386
|
under unified preview.
|
|
7387
|
-
`,stderr:``,exitCode:0}}function
|
|
7387
|
+
`,stderr:``,exitCode:0}}function Lse(e){return`error`in e}function Rse(e,t,n){if(e===`--entry`)return t?(n.entry=t,{skip:1}):{error:`serve: missing value for --entry
|
|
7388
7388
|
`};if(e.startsWith(`--entry=`))return n.entry=e.slice(8),{skip:0};if(e===`--bridge`)return n.bridge=!0,{skip:0};if(e===`--no-bridge`)return n.noBridge=!0,{skip:0};if(e===`--project`)return n.project=!0,{skip:0};if(e===`--stop`)return t?(n.stop=t,{skip:1}):{error:`serve: missing value for --stop
|
|
7389
7389
|
`};if(e.startsWith(`--stop=`))return n.stop=e.slice(7),{skip:0};if(e===`--list`)return n.list=!0,{skip:0};if(e===`--max-tabs`){if(!t)return{error:`serve: missing value for --max-tabs
|
|
7390
7390
|
`};let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?{error:`serve: --max-tabs must be a positive integer
|
|
7391
7391
|
`}:(n.maxTabs=e,{skip:1})}if(e.startsWith(`--max-tabs=`)){let t=Number.parseInt(e.slice(11),10);return!Number.isFinite(t)||t<=0?{error:`serve: --max-tabs must be a positive integer
|
|
7392
7392
|
`}:(n.maxTabs=t,{skip:0})}return e===`--quiet`?(n.quiet=!0,{skip:0}):e.startsWith(`-`)?{error:`serve: unknown option: ${e}\n`}:n.directory?{error:`serve: expected a single directory argument
|
|
7393
|
-
`}:(n.directory=e,{skip:0})}function
|
|
7394
|
-
`,exitCode:1};if(t.webhookId){let n=await j7();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function
|
|
7393
|
+
`}:(n.directory=e,{skip:0})}function zse(e){let t={entry:`index.html`,bridge:!1,noBridge:!1,project:!1,list:!1,quiet:!1};for(let n=0;n<e.length;n+=1){let r=Rse(e[n],e[n+1],t);if(Lse(r))return{...t,error:r.error};n+=r.skip}return t}async function Bse(e,t,n,r){if(!bn(t))return{stdout:``,stderr:`serve: invalid entry file: ${t}\n`,exitCode:1};let i=n.resolvePath(r,e),a;try{a=await n.stat(i)}catch{return{stdout:``,stderr:`serve: no such directory: ${e}\n`,exitCode:1}}if(!a.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${e}\n`,exitCode:1};let o=On(i,t),s;try{s=await n.stat(o)}catch{return{stdout:``,stderr:`serve: entry file not found: ${o}\n`,exitCode:1}}return s.isFile?{fullDirectory:i,entryPath:o}:{stdout:``,stderr:`serve: entry is not a file: ${o}\n`,exitCode:1}}function Vse(e){return`exitCode`in e}async function Hse(e){let t,n=k7();if(n)t=await n({type:`stop`,previewToken:e});else{let n=i();if(!n)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=await n.call(`tray-revoke-preview`,{previewToken:e})}if(!t.revoked)return{stdout:``,stderr:`serve: preview token not found or already revoked
|
|
7394
|
+
`,exitCode:1};if(t.webhookId){let n=await j7();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function Use(){let e=k7();if(e){let t=(await e({type:`list`})).previews??[];return t.length===0?{stdout:`No active previews
|
|
7395
7395
|
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${t.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}let t=i();if(!t)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};let n=(await t.call(`tray-list-previews`,void 0)).previews??[];return n.length===0?{stdout:`No active previews
|
|
7396
|
-
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function N7(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function
|
|
7397
|
-
`:``,c=await
|
|
7396
|
+
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function N7(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function Wse(e){let t=Pse();if(t)return t(e);let n=i();if(!n)throw Error("no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.");return n.call(`tray-open-preview`,e)}async function Gse(e,t){if(t)return t.createPage(e);typeof window<`u`&&typeof window.open==`function`&&window.open(e,`_blank`,`noopener,noreferrer`)}async function Kse(e,t){if(!e)return{ok:!0};let n=await j7();if(!n)return{ok:!1,result:{stdout:``,stderr:`${t}serve: --bridge requires an active lick manager\n`,exitCode:1}};try{return{ok:!0,webhookId:(await n.createWebhook(`preview-bridge`)).id}}catch(e){return{ok:!1,result:{stdout:``,stderr:`${t}serve: webhook creation failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}}async function qse(e,t,n,r,i,a){let o;try{o=await Wse({entryPath:n,servedRoot:t,bridge:e.bridge,noBridge:e.noBridge,maxTabs:e.maxTabs,quiet:e.quiet,webhookId:r})}catch(e){if(r){let e=await j7();e&&await e.deleteWebhook(r).catch(()=>{})}return{stdout:``,stderr:`${i}serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let s=await Gse(o.url,a),c=`${o.pushed} follower${o.pushed===1?``:`s`}`,l=s?` (targetId: ${s})`:``;return{stdout:`Preview URL: ${o.url}${l}\nPushed to ${c}\n`,stderr:i,exitCode:0}}async function Jse(e,t,n){if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return M7();let r=zse(e);if(r.error)return{stdout:``,stderr:r.error,exitCode:1};if(r.stop){let e=r.stop;return await N7(()=>Hse(e))}if(r.list)return await N7(()=>Use());if(!r.directory)return M7();let i=await Bse(r.directory,r.entry,t.fs,t.cwd);if(Vse(i))return i;let{fullDirectory:a,entryPath:o}=i,s=r.project?`serve: --project is obsolete; ignored (root-absolute paths work natively under unified preview)
|
|
7397
|
+
`:``,c=await Kse(!r.noBridge&&r.bridge,s);return c.ok?qse(r,a,o,c.webhookId,s,n):c.result}function Yse(e,t){return B(`serve`,(t,n)=>Jse(t,n,e))}const P7=`slicc-sprinkle-routes`;function F7(){try{let e=localStorage.getItem(P7);return e?JSON.parse(e):{}}catch{return{}}}function I7(e){try{localStorage.setItem(P7,JSON.stringify(e))}catch{}}function Xse(e){return F7()[e]}function Zse(e,t){let n=F7();n[e]=t,I7(n)}function Qse(e){let t=F7();delete t[e],I7(t)}function $se(){return F7()}function ece(){return{stdout:`usage: sprinkle <subcommand> [args]
|
|
7398
7398
|
|
|
7399
7399
|
list List available .shtml sprinkles
|
|
7400
7400
|
open <name> Open a sprinkle by name
|
|
@@ -7408,26 +7408,26 @@ Examples:
|
|
|
7408
7408
|
chat <html> Show inline HTML in chat (Tool UI)
|
|
7409
7409
|
Use data-action="name" on buttons for callbacks
|
|
7410
7410
|
Pipe HTML: echo "<div>...</div>" | sprinkle chat
|
|
7411
|
-
`,stderr:``,exitCode:0}}function
|
|
7411
|
+
`,stderr:``,exitCode:0}}function tce(){return globalThis.__slicc_sprinkleManager??null}async function nce(e,t){let n=e.slice(1).join(` `);if(!n){let e=rZ(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
|
|
7412
7412
|
`,exitCode:1};let r=await he({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
|
|
7413
7413
|
`,exitCode:1}:{stdout:JSON.stringify(r)+`
|
|
7414
|
-
`,stderr:``,exitCode:0}}async function
|
|
7414
|
+
`,stderr:``,exitCode:0}}async function rce(e){await e.refresh();let t=e.available();if(t.length===0)return{stdout:`No .shtml sprinkles found.
|
|
7415
7415
|
`,stderr:``,exitCode:0};let n=new Set(e.opened());return{stdout:t.map(e=>{let t=n.has(e.name)?` [open]`:``;return` ${e.name}${t} ${e.title} (${e.path})`}).join(`
|
|
7416
7416
|
`)+`
|
|
7417
|
-
`,stderr:``,exitCode:0}}async function
|
|
7418
|
-
`,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function
|
|
7419
|
-
`,exitCode:1}}async function
|
|
7420
|
-
`,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function
|
|
7417
|
+
`,stderr:``,exitCode:0}}async function ice(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle open: name required
|
|
7418
|
+
`,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function ace(e,t){let n=t[1];return n?(e.close(n),{stdout:`Sprinkle "${n}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
|
|
7419
|
+
`,exitCode:1}}async function oce(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle reload: name required
|
|
7420
|
+
`,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function sce(e){await e.refresh();let t=e.available().length;return{stdout:`Found ${t} sprinkle${t===1?``:`s`}.\n`,stderr:``,exitCode:0}}function cce(e){let t=e[1];if(!t){let e=$se(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
|
|
7421
7421
|
`,stderr:``,exitCode:0}:{stdout:`Sprinkle routes:
|
|
7422
7422
|
`+t.map(([e,t])=>` ${e} -> ${t}`).join(`
|
|
7423
7423
|
`)+`
|
|
7424
|
-
`,stderr:``,exitCode:0}}if(e.includes(`--clear`))return
|
|
7424
|
+
`,stderr:``,exitCode:0}}if(e.includes(`--clear`))return Qse(t),{stdout:`Route cleared for sprinkle "${t}" (licks will go to cone).\n`,stderr:``,exitCode:0};let n=e.indexOf(`--scoop`),r=n===-1?void 0:e[n+1];if(!r){let e=Xse(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return Zse(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function lce(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle send: name required
|
|
7425
7425
|
`,exitCode:1};let r=t.slice(2).join(` `);if(!r)return{stdout:``,stderr:`sprinkle send: JSON data required
|
|
7426
7426
|
`,exitCode:1};let i;try{i=JSON.parse(r)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
|
|
7427
|
-
`,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function
|
|
7428
|
-
`,exitCode:1};switch(n){case`list`:return
|
|
7429
|
-
`,stderr:``,exitCode:0}}function L7(e=`sqlite3`){return B(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return
|
|
7430
|
-
`)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function
|
|
7427
|
+
`,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function uce(){return B(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return ece();let n=e[0];if(n===`chat`)return nce(e,t);let r=tce();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
|
|
7428
|
+
`,exitCode:1};switch(n){case`list`:return rce(r);case`open`:return ice(r,e);case`close`:return ace(r,e);case`reload`:return oce(r,e);case`refresh`:return sce(r);case`route`:return cce(e);case`send`:return lce(r,e);default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function dce(){return{stdout:`usage: sqlite3 [database] [sql]
|
|
7429
|
+
`,stderr:``,exitCode:0}}function L7(e=`sqlite3`){return B(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return dce();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||rZ(n.stdin).trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await yn(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(fn).join(`|`));return{stdout:l.length>0?`${l.join(`
|
|
7430
|
+
`)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function fce(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return B(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
|
|
7431
7431
|
`,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
|
|
7432
7432
|
|
|
7433
7433
|
Request human approval to run <command> with elevation. If approved, the
|
|
@@ -7442,11 +7442,11 @@ Options:
|
|
|
7442
7442
|
`,stderr:``,exitCode:0};if(!t)return{stdout:``,stderr:`sudo: command-level approval is not configured
|
|
7443
7443
|
`,exitCode:1};if(!i.exec)return{stdout:``,stderr:`sudo: cannot dispatch inner command in this context
|
|
7444
7444
|
`,exitCode:1};let a=e.join(` `).trim(),o=await t.requestApproval({kind:`command`,detail:a});if(o.decision===`deny`)return{stdout:``,stderr:`sudo: approval denied
|
|
7445
|
-
`,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}function
|
|
7446
|
-
`,stderr:``,exitCode:0}}function R7(e){return{stdout:``,stderr:`tar: ${e}\n`,exitCode:1}}function
|
|
7447
|
-
`)}\n`:``,stderr:``,exitCode:0}}async function
|
|
7448
|
-
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=
|
|
7449
|
-
`)}\n`:``,stderr:``,exitCode:0}}function
|
|
7445
|
+
`,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}function pce(){return{stdout:`usage: tar (-c|-x|-t) [-zv] -f <archive> [-C <dir>] [paths...]
|
|
7446
|
+
`,stderr:``,exitCode:0}}function R7(e){return{stdout:``,stderr:`tar: ${e}\n`,exitCode:1}}function mce(e,t){if(e.mode)return R7(`exactly one of -c, -x, or -t is required`);e.mode=t}function hce(e,t,n){if(n)return[n,t];let r=e[t+1];return r===void 0?void 0:[r,t+1]}const gce={c:`create`,x:`extract`,t:`list`};function _ce(e,t,n,r,i){let a=gce[e];if(a)return{nextIndex:r,error:mce(i,a)};if(e===`z`)return i.gzip=!0,{nextIndex:r};if(e===`v`)return i.verbose=!0,{nextIndex:r};if(e!==`f`&&e!==`C`)return{nextIndex:r,error:R7(`unsupported option -${e}`)};let o=hce(n,r,t);return o?(e===`f`?i.archive=o[0]:i.directory=o[0],{nextIndex:o[1],consumedValue:!0}):{nextIndex:r,error:R7(`option -${e} requires an argument`)}}function vce(e,t,n){let r=e[t];for(let i=1;i<r.length;i++){let a=_ce(r[i],r.slice(i+1),e,t,n);if(a.error||a.consumedValue)return a}return{nextIndex:t}}function yce(e){let t={gzip:!1,verbose:!1,directory:`.`,paths:[]};for(let n=0;n<e.length;n++){let r=e[n];if(!r.startsWith(`-`)||r===`-`){t.paths.push(r);continue}if(r.startsWith(`--`))return R7(`unsupported option ${r}`);let i=vce(e,n,t);if(i.error)return i.error;n=i.nextIndex}return t}function bce(e,t){let n=e.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^(?:\.\/)+/,``);return n?n===`.`?`.`:n.replace(/\/+$/,``):wn(t)}async function z7(e,t,n,r){let i=await e.fs.stat(t);if(i.isFile){r.push({path:n,bytes:await e.fs.readFileBuffer(t)});return}if(!i.isDirectory)throw Error(`unsupported file type: ${t}`);let a=n.endsWith(`/`)?n:`${n}/`;r.push({path:a,bytes:new Uint8Array,directory:!0});for(let n of await e.fs.readdir(t))await z7(e,gn(t,n),`${a}${n}`,r)}function xce(e,t){let n=e.length>=2&&e[0]===31&&e[1]===139;return Kt(t||n?Ut(e):e,{stripNpmPrefix:!1,includeDirectories:!0,preserveRawPaths:!0})}function Sce(e,t,n){let r=n.replace(/\\/g,`/`);if(!r||r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)||r.split(`/`).includes(`..`))return;let i=e.fs.resolvePath(t,r);return Sn(t,i)?i:void 0}async function Cce(e,t){if(e.paths.length===0)return R7(`create mode requires at least one input path`);let n=[],r=t.fs.resolvePath(t.cwd,e.directory);for(let i of e.paths){let e=t.fs.resolvePath(r,i);await z7(t,e,bce(i,e),n)}let i=t.fs.resolvePath(t.cwd,e.archive),a=Jt(n);return await t.fs.writeFile(i,e.gzip?zt(a):a),{stdout:e.verbose?`${n.map(e=>e.path).join(`
|
|
7447
|
+
`)}\n`:``,stderr:``,exitCode:0}}async function wce(e,t){if(e.paths.length>0)return R7(`${e.mode} mode does not accept input paths`);let n=t.fs.resolvePath(t.cwd,e.archive),r=xce(await t.fs.readFileBuffer(n),e.gzip);if(e.mode===`list`){let e=r.map(e=>e.path).join(`
|
|
7448
|
+
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=Sce(t,i,e.path);if(!n)return R7(`blocked suspicious path ${e.path}`);if(e.directory)await t.fs.mkdir(n,{recursive:!0});else{let r=un(n);r!==`/`&&await t.fs.mkdir(r,{recursive:!0}),await t.fs.writeFile(n,e.bytes)}a.push(e.path)}return{stdout:e.verbose?`${a.join(`
|
|
7449
|
+
`)}\n`:``,stderr:``,exitCode:0}}function Tce(){return B(`tar`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return pce();let n=yce(e);return`exitCode`in n?n:n.mode?n.archive?n.mode===`list`&&n.directory!==`.`?R7(`-C is only supported in create or extract mode`):n.mode===`create`?Cce(n,t):wce(n,t):R7(`option -f requires an archive path`):R7(`exactly one of -c, -x, or -t is required`)})}var Ece=`/**
|
|
7450
7450
|
* Standalone assertions - no dependency on test runner
|
|
7451
7451
|
*
|
|
7452
7452
|
* Each assertion:
|
|
@@ -7634,7 +7634,7 @@ function sameMembers(a, b) {
|
|
|
7634
7634
|
}
|
|
7635
7635
|
|
|
7636
7636
|
const slice = a => (isPrimitive(a) ? a : a.slice ? a.slice() : Object.assign({}, a))
|
|
7637
|
-
`,
|
|
7637
|
+
`,Dce=`/**
|
|
7638
7638
|
* tst - minimal test runner
|
|
7639
7639
|
*
|
|
7640
7640
|
* - Standalone assertions (assert.js works anywhere)
|
|
@@ -8288,27 +8288,27 @@ Install:
|
|
|
8288
8288
|
Then \`tsc --version\` and the transpile commands above. There is no
|
|
8289
8289
|
bundled binary, no CDN fallback; a missing package exits non-zero
|
|
8290
8290
|
with a clear \`ipk add\` hint.
|
|
8291
|
-
`;function
|
|
8292
|
-
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function
|
|
8293
|
-
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function
|
|
8291
|
+
`;function Oce(e){let t=[],n=!1,r=null,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s===`-h`||s===`--help`){i=!0;continue}if(s===`-v`||s===`--version`){a=!0;continue}if(s===`--noEmit`){n=!0;continue}if(s===`--outDir`){let t=e[o+1];if(typeof t!=`string`||t.startsWith(`-`))throw Error(`tsc: --outDir requires a value`);r=t,o+=1;continue}if(s.startsWith(`--outDir=`)){r=s.slice(9);continue}if(s.startsWith(`-`))throw Error(`tsc: unknown option: ${s}`);t.push(s)}return{files:t,noEmit:n,outDir:r,showHelp:i,showVersion:a}}function kce(e,t){let n=`${wn(e).replace(/\.(ts|tsx|mts|cts)$/i,``)}.js`;return t?`${t.endsWith(`/`)?t.slice(0,-1):t}/${n}`:`${un(e)}/${n}`}async function Ace(e,t){let n=t||`/`,r=``;for(;n&&n!==r;){let t=n===`/`?`/tsconfig.json`:`${n}/tsconfig.json`;if(await e.exists(t))return t;r=n,n=un(n)}return null}const H7={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function jce(e,t,n){let r=await Ace(e,n);if(!r)return{compilerOptions:{...H7}};let i;try{i=await e.readFile(r)}catch{return{compilerOptions:{...H7}}}let{config:a,error:o}=t.parseConfigFileTextToJson(r,i);if(o||!a)return{compilerOptions:{...H7}};let s=a.compilerOptions??{};return{compilerOptions:{...H7,...s}}}function U7(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
|
|
8292
|
+
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function Mce(e,t){let n=t.toLowerCase();return n.endsWith(`.tsx`)?e.ScriptKind.TSX:n.endsWith(`.jsx`)?e.ScriptKind.JSX:n.endsWith(`.js`)||n.endsWith(`.mjs`)||n.endsWith(`.cjs`)?e.ScriptKind.JS:e.ScriptKind.TS}function W7(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function Nce(e,t,n,r){let{outputText:i,diagnostics:a}=W7(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>U7(e,t)),s=o.length>0?`${o.join(`
|
|
8293
|
+
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function Pce(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,n);if(!await t.fs.exists(a))return{stderr:`tsc: ${n}: no such file\n`,hadError:!0};let o;try{o=await t.fs.readFile(a)}catch(e){return{stderr:`tsc: ${n}: ${e instanceof Error?e.message:String(e)}\n`,hadError:!0}}Mce(e,a);let{outputText:s,diagnostics:c}=W7(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${U7(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,kce(a,r.outDir));try{await t.fs.writeFile(d,s)}catch(e){l.push(`tsc: ${d}: ${e instanceof Error?e.message:String(e)}\n`),u=!0}return{stderr:l.join(``),hadError:u}}async function Fce(e,t){let n;try{n=Oce(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:V7,stderr:``,exitCode:0}};let r;try{r=await Dn(B7(t))}catch(e){return{done:{stdout:``,stderr:`tsc: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}return n.showVersion?{done:{stdout:`Version ${r.version}\n`,stderr:``,exitCode:0}}:{parsed:n,ts:r}}function Ice(){return B(`tsc`,async(e,t)=>{let n=await Fce(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await jce(t.fs,i,t.cwd);if(r.files.length===0){let e=rZ(t.stdin);return e?Nce(i,r,a,e):{stdout:V7,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await Pce(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const Lce=[`**/*.test.{js,ts}`];function Rce(e){let t=[],n=`tap`,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`-h`||a===`--help`){r=!0;continue}if(a===`--reporter`){let t=e[i+1];if(t!==`tap`&&t!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=t,i+=1;continue}if(a.startsWith(`--reporter=`)){let e=a.slice(11);if(e!==`tap`&&e!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=e;continue}if(a.startsWith(`-`))throw Error(`test: unknown option: ${a}`);t.push(a)}return{globs:t.length>0?t:[...Lce],reporter:n,showHelp:r}}function G7(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=e.indexOf(`}`,t);if(n===-1)return[e];let r=e.slice(0,t),i=e.slice(n+1),a=e.slice(t+1,n).split(`,`),o=[];for(let e of a)for(let t of G7(`${r}${e}${i}`))o.push(t);return o}function zce(e){let t=``,n=0;for(;n<e.length;){let r=e[n];r===`*`&&e[n+1]===`*`?(t+=`(?:.*/)?`,n+=2,e[n]===`/`&&(n+=1)):r===`*`?(t+=`[^/]*`,n+=1):r===`?`?(t+=`[^/]`,n+=1):`.+^$()[]|\\`.includes(r)?(t+=`\\${r}`,n+=1):(t+=r,n+=1)}return RegExp(`^${t}$`)}async function Bce(e,t,n){let r=n.flatMap(G7).map(zce),i=new Set,a=t===`/`?``:t;async function o(t){let n;try{n=await e.readdir(t)}catch{return}for(let s of n){if(s===`node_modules`||s.startsWith(`.`))continue;let n=t===`/`?`/${s}`:`${t}/${s}`,c=!1;try{c=(await e.stat(n)).isDirectory}catch{continue}if(c){await o(n);continue}let l=n.startsWith(`${a}/`)?n.slice(a.length+1):n;r.some(e=>e.test(l))&&i.add(n)}}return await o(t),[...i].sort()}let K7=null;async function Vce(e){if(K7)return K7;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return K7=`
|
|
8294
8294
|
if (typeof process !== 'undefined' && !process.versions) {
|
|
8295
8295
|
try { process.versions = { node: '20.0.0' }; } catch (_) { /* readonly process.versions is fine */ }
|
|
8296
8296
|
}
|
|
8297
8297
|
const __tst_assert_exports = (function () {
|
|
8298
8298
|
const module = { exports: {} };
|
|
8299
8299
|
const exports = module.exports;
|
|
8300
|
-
${e.transpileModule(
|
|
8300
|
+
${e.transpileModule(Ece,{compilerOptions:t,fileName:`assert.js`}).outputText}
|
|
8301
8301
|
return module.exports;
|
|
8302
8302
|
})();
|
|
8303
8303
|
const __tst_module_exports = (function () {
|
|
8304
8304
|
const module = { exports: {} };
|
|
8305
8305
|
const exports = module.exports;
|
|
8306
|
-
${e.transpileModule(
|
|
8306
|
+
${e.transpileModule(Dce,{compilerOptions:t,fileName:`tst.js`}).outputText.replace(/require\(["']\.\/assert\.js["']\)/g,`__tst_assert_exports`).replace(/\bimport\.meta\b/g,`({url:""})`).replace(/await\s+import\(['"](?:worker_threads|fs|path)['"]\)/g,`await Promise.reject(new Error("test: fork mode is not supported in the realm"))`)}
|
|
8307
8307
|
return module.exports;
|
|
8308
8308
|
})();
|
|
8309
8309
|
const __tst = __tst_module_exports.default || __tst_module_exports;
|
|
8310
8310
|
__tst.manual = true;
|
|
8311
|
-
`.trim(),K7}function q7(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function
|
|
8311
|
+
`.trim(),K7}function q7(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function Hce(e){let t=new Set,n=/(?:^|[^\w$.])require\(\s*(["'`])([^"'`]+)\1\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[2]);return[...t]}async function Uce(e,t,n){let r=lt(`${t}/${n}`),i=[r];r.endsWith(`.js`)&&i.push(`${r.slice(0,-3)}.ts`),/\.[a-zA-Z0-9]+$/.test(r)||i.push(`${r}.ts`,`${r}.js`);for(let t of i)if(await e.exists(t))return t;return null}async function Wce(e,t,n,r,i){let a=new Map,o=new Map,s=[{path:n,cjs:r}];for(;s.length>0;){let{path:n,cjs:r}=s.shift(),c=un(n),l=new Map;for(let n of Hce(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await Uce(e,c,n);if(!r||(l.set(n,r),a.has(r)))continue;let o=await e.readFile(r),u=t.transpileModule(o,{compilerOptions:i,fileName:r}).outputText;a.set(r,u),s.push({path:r,cjs:u})}o.set(n,l)}return{modules:a,edgeRewrites:o}}function Gce(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=q7(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
|
|
8312
8312
|
${e}
|
|
8313
8313
|
const __tstReq = (id) => {
|
|
8314
8314
|
if (id === "tst") return __tst_module_exports;
|
|
@@ -8340,7 +8340,7 @@ const __state = await __tst.run({ format: ${JSON.stringify(o)} });
|
|
|
8340
8340
|
await Promise.resolve();
|
|
8341
8341
|
await new Promise((resolve) => setTimeout(resolve));
|
|
8342
8342
|
if (__state && __state.failed && __state.failed.length > 0) process.exit(1);
|
|
8343
|
-
`}const
|
|
8343
|
+
`}const Kce={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function qce(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...Kce}}async function Jce(e,t){let n;try{n=Rce(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:`test - run *.test.{js,ts} files with the bundled tst runner
|
|
8344
8344
|
|
|
8345
8345
|
Usage:
|
|
8346
8346
|
test [options] [glob...]
|
|
@@ -8353,7 +8353,7 @@ Notes:
|
|
|
8353
8353
|
- Default glob: **/*.test.{js,ts}, walked from the current cwd.
|
|
8354
8354
|
- .ts files are transpiled via the bundled typescript package.
|
|
8355
8355
|
- Each file runs in its own realm (same engine as 'node').
|
|
8356
|
-
`,stderr:``,exitCode:0}};let r=await
|
|
8356
|
+
`,stderr:``,exitCode:0}};let r=await Bce(t.fs,t.cwd,n.globs);if(r.length===0)return{done:{stdout:``,stderr:`test: no test files matched ${n.globs.join(` `)}\n`,exitCode:1}};let i;try{i=await Dn(B7(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await Vce(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:qce(i)}}function Yce(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function Xce(e,t,n,r){let{ts:i,harness:a,userOpts:o,parsed:s}=t,c;try{c=await e.fs.readFile(n)}catch(e){return{stdout:``,stderr:`test: ${n}: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let l;try{l=i.transpileModule(c,{compilerOptions:o,fileName:n}).outputText}catch(e){return{stdout:``,stderr:`test: ${n}: transpile error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let u,d;try{({modules:u,edgeRewrites:d}=await Wce(e.fs,i,n,l,o))}catch(e){return{stdout:``,stderr:`test: ${n}: local-require resolve error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let f=await oZ(Gce(a,n,l,s.reporter,u,d),[`node`,n],e,void 0,{filename:n});return{stdout:r?`# ${n}\n${f.stdout}`:f.stdout,stderr:f.stderr,failed:f.exitCode!==0||Yce(f.stdout)}}function Zce(){return B(`test`,async(e,t)=>{let n=await Jce(e,t);if(`done`in n)return n.done;let r=n.files.length>1,i=``,a=``,o=!1;for(let e of n.files){let s=await Xce(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}const J7=`usage: theme <subcommand> [args]
|
|
8357
8357
|
|
|
8358
8358
|
Subcommands:
|
|
8359
8359
|
list List available preset and custom themes
|
|
@@ -8362,21 +8362,21 @@ Subcommands:
|
|
|
8362
8362
|
reset Reset to the default theme
|
|
8363
8363
|
current Show the currently active theme
|
|
8364
8364
|
export <id> <path> Export a theme to a VFS path
|
|
8365
|
-
`;function
|
|
8366
|
-
`),stderr:``,exitCode:0}}async function
|
|
8367
|
-
`,stderr:``,exitCode:0}}async function
|
|
8365
|
+
`;function Qce(){return B(`theme`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:J7,stderr:``,exitCode:0};let n=e[0];return n===`list`?$ce():n===`current`?ele():n===`reset`?tle():n===`apply`?nle(e.slice(1),t):n===`export`?rle(e.slice(1),t):{stdout:``,stderr:`theme: unknown subcommand "${n}"\n${J7}`,exitCode:1}})}async function $ce(){let{PRESETS:e}=await import(`./theme-presets-xiOb9AFN.js`),t=[`Presets:`];for(let n of e)t.push(` ${n.id.padEnd(16)} ${n.name}`);return t.push(``),{stdout:t.join(`
|
|
8366
|
+
`),stderr:``,exitCode:0}}async function ele(){return{stdout:`Check the Theme settings dialog for the active theme.
|
|
8367
|
+
`,stderr:``,exitCode:0}}async function tle(){let e=i();return e?(await e.call(`theme-apply`,{action:`reset`}),{stdout:`Theme reset to default.
|
|
8368
8368
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
8369
|
-
`,exitCode:1}}async function
|
|
8369
|
+
`,exitCode:1}}async function nle(e,t){if(e.length===0)return{stdout:``,stderr:`theme apply: missing theme id or path
|
|
8370
8370
|
`,exitCode:1};let n=i();if(!n)return{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
8371
8371
|
`,exitCode:1};let r=e[0],{PRESETS:a}=await import(`./theme-presets-xiOb9AFN.js`),o=a.find(e=>e.id===r);if(o){let e=JSON.stringify(o);return await n.call(`theme-apply`,{themeJson:e,action:`apply`}),{stdout:`Applied theme: ${o.name}\n`,stderr:``,exitCode:0}}let s=t.fs.resolvePath(t.cwd,r),c;try{c=await t.fs.readFile(s)}catch{return{stdout:``,stderr:`theme apply: "${r}" is not a known preset id and file not found at ${s}\n`,exitCode:1}}try{let e=JSON.parse(c);if(!e.id||!e.name||!e.base||!e.tokens)return{stdout:``,stderr:`theme apply: invalid theme file (missing id, name, base, or tokens)
|
|
8372
8372
|
`,exitCode:1}}catch{return{stdout:``,stderr:`theme apply: file is not valid JSON
|
|
8373
|
-
`,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:c,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function
|
|
8374
|
-
`,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function
|
|
8375
|
-
`,stderr:``,exitCode:0}}function
|
|
8373
|
+
`,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:c,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function rle(e,t){if(e.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
|
|
8374
|
+
`,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function ile(){return{stdout:`usage: uname
|
|
8375
|
+
`,stderr:``,exitCode:0}}function ale(){return B(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return ile();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
|
|
8376
8376
|
`,exitCode:1};let t=globalThis.navigator?.userAgent;return typeof t!=`string`||t.length===0?{stdout:``,stderr:`uname: navigator.userAgent is unavailable
|
|
8377
|
-
`,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function
|
|
8378
|
-
`,stderr:``,exitCode:0}}function
|
|
8379
|
-
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=Vt(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!Sn(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=un(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const
|
|
8377
|
+
`,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function ole(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
8378
|
+
`,stderr:``,exitCode:0}}function sle(){return B(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return ole();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
|
|
8379
|
+
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=Vt(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!Sn(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=un(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const cle=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function lle(e){return zF(e,cle)}function Y7(e,t){let n=/^0x/i.test(e)?parseInt(e,16):parseInt(e,10);if(!Number.isFinite(n)||Number.isNaN(n))throw Error(`invalid ${t}: '${e}'`);return n}function ule(e){let t={};return e.has(`--vid`)&&(t.vendorId=Y7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=Y7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=Y7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=Y7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=Y7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const dle=new Set([`standard`,`class`,`vendor`]),fle=new Set([`device`,`interface`,`endpoint`,`other`]);function X7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!dle.has(t))throw Error(`invalid --request-type: '${t}'`);if(!fle.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:Y7(e.get(`--request`)??`0`,`request`),value:Y7(e.get(`--value`)??`0`,`value`),index:Y7(e.get(`--index`)??`0`,`index`)}}function Z7(e){let t=iZ(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function ple(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Q7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function $7(e){let t=[e.manufacturerName,e.productName].filter(Boolean).join(` `)||`(unknown)`,n=e.serialNumber?` serial=${e.serialNumber}`:``,r=e.opened?` [open]`:``;return`${e.handle}\t${Q7(e.vendorId)}:${Q7(e.productId)}\t${t}${n}${r}`}function e9(e){return{stdout:e,stderr:``,exitCode:0}}function t9(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const mle=`usb - access USB devices via WebUSB
|
|
8380
8380
|
|
|
8381
8381
|
Usage: usb <subcommand> [options]
|
|
8382
8382
|
|
|
@@ -8404,10 +8404,10 @@ Options:
|
|
|
8404
8404
|
--raw Emit raw bytes for *-in transfers (default: hex dump)
|
|
8405
8405
|
-h, --help
|
|
8406
8406
|
|
|
8407
|
-
Transfers are capped at ${
|
|
8408
|
-
`;function n9(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return e9(t)}return e9(e.length?`${
|
|
8407
|
+
Transfers are capped at ${MY} bytes (4 MiB).
|
|
8408
|
+
`;function n9(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return e9(t)}return e9(e.length?`${ple(e)}\n`:``)}async function hle(e){let t=await e.list();return t.length===0?e9(`no granted USB devices
|
|
8409
8409
|
`):e9(`${t.map($7).join(`
|
|
8410
|
-
`)}\n`)}async function
|
|
8410
|
+
`)}\n`)}async function gle(e,t){let n=e.get(`--__resolved`);if(n)return e9(`${$7(await t.info(n))}\n`);let r=ule(e),i=me();if(i){let e=await N(`usb-device`,r,i);if(e.handle)return e9(`${$7(await t.info(e.handle))}\n`);let n=e.info,a=DY();if(!a)return t9(`request: WebUSB unavailable for device re-acquire`);let o=(await a.getDevices()).find(e=>e.vendorId===n.vendorId&&e.productId===n.productId&&(!n.serialNumber||e.serialNumber===n.serialNumber));return o?e9(`${$7(NY(jY().register(o),o))}\n`):t9(`request: granted device could not be re-acquired`)}return e9(`${$7(await t.request(r))}\n`)}async function _le(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):e===`close`?await n.close(r):await n.reset(r),e9(``)):t9(`${e}: handle required`)}async function vle(e,t){let[,n,r]=e;return!n||r===void 0?t9(`select-config: handle and value required`):(await t.selectConfig(n,Y7(r,`configuration`)),e9(``))}async function yle(e,t,n){let[,r,i]=t;return!r||i===void 0?t9(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,Y7(i,`interface`)),e9(``))}async function ble(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return t9(`control-in: handle and length required`);let o=Y7(a,`length`);return o>4194304?t9(`control-in length exceeds 4 MiB limit`):n9((await n.controlIn(i,X7(t),o)).bytes,r)}async function xle(e,t,n,r){let i=e[1];if(!i)return t9(`control-out: handle required`);let a=Z7(t);return a.length>4194304?t9(`control-out payload exceeds 4 MiB limit`):e9(`${(await r.controlOut(i,X7(n),a)).bytesWritten} bytes written\n`)}async function r9(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return t9(`transfer-in: handle, endpoint and length required`);let s=Y7(o,`length`);return s>4194304?t9(`transfer-in length exceeds 4 MiB limit`):n9((await n.transferIn(i,Y7(a,`endpoint`),s)).bytes,r)}async function Sle(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return t9(`transfer-out: handle and endpoint required`);let o=Z7(t);return o.length>4194304?t9(`transfer-out payload exceeds 4 MiB limit`):e9(`${(await r.transferOut(i,Y7(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function Cle(e,t,n){let{positionals:r,flags:i,bools:a}=lle(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return hle(n);case`request`:return gle(i,n);case`open`:case`close`:case`reset`:return _le(o,r,n);case`select-config`:return vle(r,n);case`claim`:case`release`:return yle(o,r,n);case`control-in`:return ble(r,i,n,s);case`control-out`:return xle(r,t,i,n);case`transfer-in`:return r9(r,i,n,s);case`transfer-out`:return Sle(r,t,i,n);default:return t9(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function wle(){return B(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return e9(mle);let n=nX(a(),i());if(!n)return t9(`WebUSB is unavailable in this environment`);try{return await Cle(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?t9(`user cancelled or no device selected`):t9(t)}})}function Tle(){return{stdout:`usage: webhook <command> [options]
|
|
8411
8411
|
|
|
8412
8412
|
Commands:
|
|
8413
8413
|
create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
|
|
@@ -8425,16 +8425,16 @@ Examples:
|
|
|
8425
8425
|
webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
|
|
8426
8426
|
webhook list
|
|
8427
8427
|
webhook delete abc123
|
|
8428
|
-
`,stderr:``,exitCode:0}}function
|
|
8428
|
+
`,stderr:``,exitCode:0}}function Ele(){return globalThis.__slicc_lickManager??null}async function i9(){if(Ele())return Je().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function a9(e,t){return t?Ye(t,e):D()?Ze(self.location.href,e):`(URL unavailable — connect a leader tray)`}function o9(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function Dle(e){let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook create: --scoop is required (every webhook must route to a scoop)
|
|
8429
8429
|
`,exitCode:1};if(!D()&&n)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
|
|
8430
|
-
`,exitCode:1};let s=await
|
|
8431
|
-
`,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await
|
|
8432
|
-
`,exitCode:1};let n=await j7();return n?await n.deleteWebhook(t)?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${t}" not found\n`,exitCode:1}:o9(`delete`)}async function
|
|
8433
|
-
`,exitCode:1}}return null}async function
|
|
8430
|
+
`,exitCode:1};let s=await Ale();if(s)return s;let c=await j7();if(!c)return o9(`create`);let l=await c.createWebhook(t,r,n),u=await jle(l.id),d=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${u}\n`;return l.scoop&&(d+=`Scoop: ${l.scoop}\n`),l.filter&&(d+=`Filter: ${l.filter}\n`),{stdout:d,stderr:``,exitCode:0}}async function Ole(){let e=await j7();if(!e)return o9(`list`);let t=await e.listWebhooks();if(t.length===0)return{stdout:`No active webhooks
|
|
8431
|
+
`,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await Mle();return{stdout:Nle(t.map(e=>({id:e.id,name:e.name,url:a9(e.id,n),createdAt:e.createdAt,filter:e.filter,scoop:e.scoop})),n,r),stderr:``,exitCode:0}}async function kle(e){let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
|
|
8432
|
+
`,exitCode:1};let n=await j7();return n?await n.deleteWebhook(t)?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${t}" not found\n`,exitCode:1}:o9(`delete`)}async function Ale(){if(D())return null;if(!await i9()){let e=Je().state;return{stdout:``,stderr:(e===`leader`?`webhook create: tray session is not connected yet — wait for the leader to attach`:`webhook create: requires extension-leader mode with a tray worker URL configured (current state: "${e}")`)+`
|
|
8433
|
+
`,exitCode:1}}return null}async function jle(e){try{return a9(e,await i9())}catch(e){return`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}}async function Mle(){try{return{trayUrlBase:await i9(),urlResolutionError:null}}catch(e){return{trayUrlBase:null,urlResolutionError:e instanceof Error?e.message:String(e)}}}function Nle(e,t,n){let r=`Active webhooks:
|
|
8434
8434
|
`;for(let t of e)r+=` ${t.id} ${t.name.padEnd(20)} ${t.url}`,t.scoop&&(r+=` -> ${t.scoop}`),t.filter&&(r+=` [filtered]`),r+=`
|
|
8435
8435
|
`;return n?r+=`\nNote: webhook URL resolution failed (${n}). Try again once the tray is connected.\n`:!D()&&!t&&(r+=`
|
|
8436
8436
|
Note: webhook URLs require a leader tray. Configure one in Settings to expose POST endpoints.
|
|
8437
|
-
`),r}function
|
|
8437
|
+
`),r}function Ple(){return B(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Tle();let t=e[0];try{switch(t){case`create`:return await Dle(e);case`list`:return await Ole();case`delete`:return await kle(e);default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){let n=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`webhook ${t??`?`}: ${n}\n`,exitCode:1}}})}function Fle(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
|
|
8438
8438
|
|
|
8439
8439
|
Minimal websocat client. Sends stdin lines as WebSocket messages and prints
|
|
8440
8440
|
received messages to stdout. Server mode and advanced specifiers (exec:, tcp:,
|
|
@@ -8476,19 +8476,19 @@ EXAMPLES:
|
|
|
8476
8476
|
echo 'Page.navigate {"url":"https://example.com"}' \\
|
|
8477
8477
|
| websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc \\
|
|
8478
8478
|
ws://127.0.0.1:9222/devtools/page/<id>
|
|
8479
|
-
`,stderr:``,exitCode:0}}const s9=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function
|
|
8479
|
+
`,stderr:``,exitCode:0}}const s9=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function Ile(e){let t={text:!0,binary:!1,oneMessage:!1,noClose:!1,exitOnEof:!1,unidirectional:!1,unidirectionalReverse:!1,insecure:!1,quiet:!1,verbose:0,nullTerminated:!1,base64:!1,jsonrpc:!1,jsonrpcOmit:!1,bufferSize:65536,connTimeoutMs:3e4,customHeaders:[],showHelp:!1},n=(n,r)=>{let i=e[n].indexOf(`=`);if(i!==-1&&e[n].startsWith(r))return{value:e[n].slice(i+1),next:n};let a=e[n+1];return a===void 0?(t.error=`websocat: missing value for ${r}\n`,null):{value:a,next:n+1}};for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return t.showHelp=!0,t;if(s9.has(i)||s9.has(i.split(`=`)[0]))return t.error=`websocat: flag '${i}' is not supported in slicc's minimal client\n`,t;if(i===`-t`||i===`--text`){t.text=!0,t.binary=!1;continue}if(i===`-b`||i===`--binary`){t.binary=!0,t.text=!1;continue}if(i===`-1n`||i===`-n1`){t.oneMessage=!0,t.noClose=!0;continue}if(i===`-1`||i===`--one-message`){t.oneMessage=!0;continue}if(i===`-n`||i===`--no-close`){t.noClose=!0;continue}if(i===`-E`||i===`--exit-on-eof`){t.exitOnEof=!0;continue}if(i===`-u`||i===`--unidirectional`){t.unidirectional=!0;continue}if(i===`-U`||i===`--unidirectional-reverse`){t.unidirectionalReverse=!0;continue}if(i===`-k`||i===`--insecure`){t.insecure=!0;continue}if(i===`-q`){t.quiet=!0;continue}if(i===`-v`){t.verbose+=1;continue}if(i===`-vv`){t.verbose+=2;continue}if(i===`-0`||i===`--null-terminated`){t.nullTerminated=!0;continue}if(i===`--base64`){t.base64=!0;continue}if(i===`--jsonrpc`){t.jsonrpc=!0;continue}if(i===`--jsonrpc-omit-jsonrpc`){t.jsonrpcOmit=!0,t.jsonrpc=!0;continue}if(i===`--close-status-code`||i.startsWith(`--close-status-code=`)){let e=n(r,`--close-status-code`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<1e3||i>4999)return t.error=`websocat: --close-status-code expects 1000..4999, got '${e.value}'\n`,t;t.closeStatus=i,r=e.next;continue}if(i===`--close-reason`||i.startsWith(`--close-reason=`)){let e=n(r,`--close-reason`);if(!e)return t;t.closeReason=e.value,r=e.next;continue}if(i===`-B`||i===`--buffer-size`||i.startsWith(`--buffer-size=`)){let e=n(r,i===`-B`?`-B`:`--buffer-size`);if(!e)return t;let a=Number(e.value);if(!Number.isFinite(a)||a<=0)return t.error=`websocat: --buffer-size expects positive integer
|
|
8480
8480
|
`,t;t.bufferSize=a,r=e.next;continue}if(i===`--max-messages`||i.startsWith(`--max-messages=`)){let e=n(r,`--max-messages`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --max-messages expects positive integer
|
|
8481
8481
|
`,t;t.maxMessages=i,r=e.next;continue}if(i===`--protocol`||i.startsWith(`--protocol=`)){let e=n(r,`--protocol`);if(!e)return t;t.protocol=e.value,r=e.next;continue}if(i===`--ping-interval`||i.startsWith(`--ping-interval=`)){let e=n(r,`--ping-interval`);if(!e)return t;t.pingInterval=Number(e.value),r=e.next;continue}if(i===`--conn-timeout`||i.startsWith(`--conn-timeout=`)){let e=n(r,`--conn-timeout`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --conn-timeout expects positive seconds
|
|
8482
8482
|
`,t;t.connTimeoutMs=Math.round(i*1e3),r=e.next;continue}if(i===`-H`||i===`--header`||i.startsWith(`--header=`)){let e=n(r,i===`-H`?`-H`:`--header`);if(!e)return t;t.customHeaders.push(e.value),r=e.next;continue}if(i.startsWith(`-`))return t.error=`websocat: unknown flag '${i}'\n`,t;if(t.url)return t.error=`websocat: extra positional argument '${i}' — advanced mode is not supported\n`,t;t.url=i}return t.closeReason!==void 0&&t.closeStatus===void 0&&(t.error=`websocat: --close-reason requires --close-status-code (the WebSocket close frame cannot carry a reason without a status code)
|
|
8483
|
-
`),t}function
|
|
8484
|
-
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function
|
|
8483
|
+
`),t}function Lle(e,t){if(!e)return[];let n=t?`\0`:`
|
|
8484
|
+
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function Rle(e,t,n){let r=e.trim();if(!r)return e;let i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1).trim(),s=[];if(o)try{s=JSON.parse(o)}catch{s=[o]}let c={id:t,method:a,params:s};return n||(c.jsonrpc=`2.0`),JSON.stringify(c)}function c9(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function zle(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return c9(e)}}async function Ble(e,t,n={}){let r=Ile(e);if(r.showHelp)return Fle();if(r.error)return{stdout:``,stderr:r.error,exitCode:2};if(!r.url)return{stdout:``,stderr:`websocat: missing ws:// or wss:// URL (use --help for usage)
|
|
8485
8485
|
`,exitCode:2};if(!/^wss?:\/\//i.test(r.url))return{stdout:``,stderr:`websocat: URL must start with ws:// or wss://, got '${r.url}'\n`,exitCode:2};let i=n.WebSocketCtor??(typeof WebSocket<`u`?WebSocket:void 0);if(!i)return{stdout:``,stderr:`websocat: no WebSocket implementation available in this runtime
|
|
8486
8486
|
`,exitCode:1};let a=[],o=e=>{r.quiet||a.push(`websocat: ${e}`)};r.verbose>=1&&(r.customHeaders.length>0&&o(`-H/--header is accepted for parity but browsers do not allow setting WebSocket request headers; only --protocol is honored`),r.pingInterval!==void 0&&o(`--ping-interval has no effect in browsers (no ping API exposed)`),r.insecure&&o(`-k/--insecure has no effect in browsers`));let s=[],c=r.nullTerminated?`\0`:`
|
|
8487
|
-
`,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?c9(t):
|
|
8487
|
+
`,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?c9(t):zle(t);s.length<d?s.push(i):(f===0&&o(`output buffer reached ${d} messages; dropping further inbound messages — use -1, --max-messages, or pipe to a file with a different tool for long-running streams`),f+=1)}if(u+=1,r.maxMessages!==void 0&&u>=r.maxMessages){C=!0,T();return}r.oneMessage&&(C=!0,T())}},l.onerror=()=>{x||(o(`websocket error`),b=1,p||h(Error(`connect failed`)))},l.onclose=e=>{if(clearTimeout(S),x){_(124);return}r.verbose>=1&&o(`closed code=${e.code} reason=${JSON.stringify(e.reason||``)}`),b===0&&e.code!==1e3&&e.code!==1005&&e.code!==1001&&(b=1),p||h(Error(`connect closed (code ${e.code})`)),_(b)};function w(e,t){try{t===void 0?l.close(e):l.close(e,t)}catch{}}function T(){if(r.noClose){_(b);return}w(r.closeStatus??1e3,r.closeReason)}try{await g}catch(e){clearTimeout(S);let t=e instanceof Error?e.message:String(e);return{stdout:s.join(c)+(s.length?c:``),stderr:a.concat([`websocat: ${t}`]).join(`
|
|
8488
8488
|
`)+`
|
|
8489
|
-
`,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=
|
|
8489
|
+
`,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=Lle(t.stdin,r.nullTerminated),n=1,i=0,a=r.oneMessage?e.slice(0,1):e;for(let e of a){let t=e;r.jsonrpc&&(t=Rle(e,n,r.jsonrpcOmit),n+=1),r.binary?l.send(new TextEncoder().encode(t).buffer):l.send(t),i+=1}!r.oneMessage&&!r.noClose&&(r.exitOnEof||i===0)&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0)}let E=await y;return f>0&&o(`dropped ${f} inbound message(s) due to output buffer cap`),{stdout:s.length?s.join(c)+c:``,stderr:a.length?a.join(`
|
|
8490
8490
|
`)+`
|
|
8491
|
-
`:``,exitCode:E}}function
|
|
8491
|
+
`:``,exitCode:E}}function Vle(){return B(`websocat`,async(e,t)=>Ble(e,{stdin:rZ(t.stdin)}))}function Hle(){return B(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function Ule(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?Pn(e.fs):new Map}async function Wle(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?Fn(e.fs):new Map}function Gle(e,t,n,r,i){if(r.has(e)){let r=[`/usr/bin/${e}`];return(t||n)&&r.push(` (shadowed by built-in ${e})`),{lines:r,found:!0}}if(t){let e=[t];return n&&e.push(` ${n.path} (workflow, shadowed by .jsh)`),{lines:e,found:!0}}return n?{lines:[`${n.path} (workflow)`],found:!0}:i.has(e)?{lines:[`/usr/bin/${e}`],found:!0}:{lines:[],found:!1}}function Kle(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return B(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
|
|
8492
8492
|
|
|
8493
8493
|
Usage: which <command> [command...]
|
|
8494
8494
|
|
|
@@ -8498,9 +8498,9 @@ Prints the path of the given command(s).
|
|
|
8498
8498
|
|
|
8499
8499
|
Exit code 0 if all commands found, 1 if any not found.
|
|
8500
8500
|
`,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
|
|
8501
|
-
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await
|
|
8501
|
+
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await Ule(t),o=await Wle(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=Gle(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
|
|
8502
8502
|
`)+`
|
|
8503
|
-
`:``,stderr:``,exitCode:+!l}})}const l9=r(`workflow-run-manager`),u9=`__slicc_workflows`,d9=`/shared/workflow-runs`,f9=1e3;function
|
|
8503
|
+
`:``,stderr:``,exitCode:+!l}})}const l9=r(`workflow-run-manager`),u9=`__slicc_workflows`,d9=`/shared/workflow-runs`,f9=1e3;function qle(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)=>Qle(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),Xle(t,n);let f=a(o.ctx,l),p=Zle(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=`${d9}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(d9,{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`?Yle(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 Jle(e){let t=qle(e);return globalThis[u9]=t,l9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Yle(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Xle(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 Zle(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 Qle(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?$le(n,t,a?.args??[],r):e===`agent`?eue(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function $le(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>f9&&i.logs.splice(0,i.logs.length-f9),r()}return{stdout:``,stderr:``,exitCode:0}}async function eue(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const tue=String.raw`
|
|
8504
8504
|
class WorkflowError extends Error {}
|
|
8505
8505
|
class WorkflowDeterminismError extends WorkflowError {}
|
|
8506
8506
|
class WorkflowAgentCapError extends WorkflowError {}
|
|
@@ -8610,11 +8610,11 @@ function log(message) {
|
|
|
8610
8610
|
}
|
|
8611
8611
|
const budget = { total: (__WF.budget == null ? null : __WF.budget), spent() { return 0; }, remaining() { return this.total == null ? Infinity : Math.max(0, this.total - this.spent()); } };
|
|
8612
8612
|
function workflow() { throw new WorkflowNestingUnsupportedError('nested workflow() unsupported in SP1'); }
|
|
8613
|
-
`;function p9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function
|
|
8613
|
+
`;function p9(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function nue(e){let t=aue(e);return t===null?{name:null,description:null}:{name:h9(t,`name`),description:h9(t,`description`)}}function rue(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function iue(e){return`const __emit = console.log.bind(console);
|
|
8614
8614
|
const __stringify = JSON.stringify.bind(JSON);
|
|
8615
|
-
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${
|
|
8615
|
+
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${rue(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function m9(e,t){let n=e.split(`
|
|
8616
8616
|
`);for(let e=n.length-1;e>=0;e--)if(n[e].startsWith(t)){let r=[...n.slice(0,e),...n.slice(e+1)].join(`
|
|
8617
|
-
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function
|
|
8617
|
+
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function aue(e){let t=/\bmeta\s*=\s*\{/.exec(e);if(!t)return null;let n=t.index+t[0].length-1,r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&--r===0)return e.slice(n+1,t);return null}function h9(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const g9=r(`workflow-command`);function _9(){return globalThis[u9]}function oue(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function sue(e,t,n,r){let i=t[n];switch(i){case`-h`:case`--help`:return{i:n,help:!0};case`--script`:return e.script=t[++n],{i:n};case`--wait`:return e.wait=!0,{i:n};case`--args`:try{e.args=JSON.parse(t[++n]??``),e.hasArgs=!0}catch{return{i:n,error:`workflow: --args must be valid JSON`}}return{i:n};case`--budget`:{let r=Number(t[++n]);return Number.isFinite(r)?(e.budget=r,{i:n}):{i:n,error:`workflow: --budget must be a number`}}case`--concurrency`:{let i=Number(t[++n]);return Number.isFinite(i)?(e.cap=Math.min(r,Math.max(1,Math.trunc(i))),{i:n}):{i:n,error:`workflow: --concurrency must be a number`}}default:return i.startsWith(`-`)?{i:n,error:`workflow: unknown flag '${i}'`}:e.file===void 0?(e.file=i,{i:n}):{i:n,error:`workflow: too many arguments`}}}function cue(e){if(e[0]!==`run`)return e.length===0||e.includes(`-h`)||e.includes(`--help`)?{help:!0}:{error:`workflow: unknown subcommand '${e[0]}' (only 'run' in SP1)`};let t=oue(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=sue(n,e,r,t);if(i.help)return{help:!0};if(i.error)return{error:i.error};r=i.i}return n.script===void 0&&n.file===void 0?{error:`workflow: a <file.js> or --script is required`}:n}function lue(e={}){return B(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return mue(t,n);if(t[0]===`save`)return pue(t,n,e);let r=cue(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
|
|
8618
8618
|
workflow run --script '<inline js>' [...]
|
|
8619
8619
|
workflow list
|
|
8620
8620
|
workflow status <runId>
|
|
@@ -8623,26 +8623,26 @@ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (asyn
|
|
|
8623
8623
|
Runs a Claude-Code-format dynamic workflow. Default is non-blocking (returns a run id);
|
|
8624
8624
|
pass --wait to block and print the full result.
|
|
8625
8625
|
`,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:r.error+`
|
|
8626
|
-
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=
|
|
8627
|
-
`,exitCode:1};let s=p9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p9(),u=
|
|
8628
|
-
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const
|
|
8629
|
-
`,exitCode:1};if(!
|
|
8626
|
+
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=nue(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
|
|
8627
|
+
`,exitCode:1};let s=p9().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=p9(),u=iue({prelude:tue,config:{...r.hasArgs?{args:r.args}:{},cap:r.cap??8,budget:r.budget??null,cwd:n.cwd,agentCwd:c},body:i,sentinel:l});return r.wait?uue(u,a,l,o,n):due({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function uue(e,t,n,r,i){let a;try{a=await oZ(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return g9.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return hue(r,a,n)}async function due(e){let t=_9();if(!t)return{stdout:``,stderr:`workflow: run manager not available
|
|
8628
|
+
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const fue=/^[a-z0-9][a-z0-9-]*$/,v9=`/workspace/.workflows`;async function pue(e,t,n){let r=!1,i=[];for(let t of e.slice(1))t===`--force`?r=!0:i.push(t);let[a,o,...s]=i;if(!a||!o||s.length>0)return{stdout:``,stderr:`usage: workflow save <runId> <name> [--force]
|
|
8629
|
+
`,exitCode:1};if(!fue.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=_9()?.getRun(a);if(!c)return{stdout:``,stderr:`workflow: no run '${a}' (only backgrounded runs are saveable; --wait runs are not)\n`,exitCode:1};if(!c.source)return{stdout:``,stderr:`workflow: run '${a}' has no source to save\n`,exitCode:1};let l=`${v9}/${o}.workflow.js`;if(await t.fs.exists(l)){if(!r)return{stdout:``,stderr:`workflow: ${l} already exists (pass --force to overwrite)\n`,exitCode:1}}else if(new Set(t.getRegisteredCommands?.()??[]).has(o))return{stdout:``,stderr:`workflow: '${o}' is already a command — choose another name\n`,exitCode:1};await t.fs.mkdir(v9,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){g9.warn(`workflow save: command re-sync failed; workflow saved, will register on next sync`,{name:o,error:e instanceof Error?e.message:String(e)})}return{stdout:`saved workflow '${o}' → ${l}\nrun it as '${o}' (or 'workflow run ${l}' if a built-in/.jsh shadows the name)\n`,stderr:``,exitCode:0}}async function mue(e,t){let n=_9();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
|
|
8630
8630
|
`,exitCode:1};let e=n.listRuns().map(e=>`${e.id} ${e.status.padEnd(7)} ${e.agentsDone}/${e.agentsStarted} ${e.name??``}`);return{stdout:(e.length?e.join(`
|
|
8631
8631
|
`):`(no runs)`)+`
|
|
8632
8632
|
`,stderr:``,exitCode:0}}let r=e[1],i=n?.getRun(r??``);if(!i)return{stdout:``,stderr:`workflow: no run '${r}'\n`,exitCode:1};if(e[0]===`status`)return{stdout:[`run ${i.id} (${i.name??`unnamed`}) status=${i.status}`,`agents ${i.agentsDone}/${i.agentsStarted} phase=${i.currentPhase??`-`}`,i.resultPath?`result: ${i.resultPath}`:``,i.preview?`preview: ${i.preview}`:``,i.error?`error: ${i.error}`:``].filter(Boolean).join(`
|
|
8633
8633
|
`)+`
|
|
8634
|
-
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function
|
|
8634
|
+
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function hue(e,t,n){let{result:r,log:i,hadResult:a}=m9(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?gue(i)+`
|
|
8635
8635
|
`:``;return t.exitCode!==0||!a?{stdout:o+s,stderr:t.stderr||(a?``:`workflow: script produced no result
|
|
8636
8636
|
`),exitCode:t.exitCode||1}:{stdout:o+s+(typeof r==`string`?r:JSON.stringify(r))+`
|
|
8637
|
-
`,stderr:t.stderr,exitCode:0}}function
|
|
8637
|
+
`,stderr:t.stderr,exitCode:0}}function gue(e){return e.split(`
|
|
8638
8638
|
`).map(e=>e.replace(/^WFPHASE/,`▸ `).replace(/^WFLOG/,`· `)).join(`
|
|
8639
|
-
`)}function y9(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function
|
|
8639
|
+
`)}function y9(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function _ue(e){if(e==null)throw Error(`missing option value`);let t=e.startsWith(`-`),n=t||e.startsWith(`+`)?e.slice(1):e,r;if(/^0x[0-9a-fA-F]+$/.test(n))r=parseInt(n.slice(2),16);else if(/^[0-9]+$/.test(n))r=parseInt(n,10);else throw Error(`invalid number: ${e}`);return t?-r:r}function b9(e,t){let n=e.toString(16).padStart(2,`0`);return t?n.toUpperCase():n}function x9(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}function vue(e){return e.replace(/[^0-9a-zA-Z]/g,`_`)}function yue(e,t,n,r,i){let a=[];for(let o=0;o<e.length;o+=t){let s=Math.min(o+t,e.length),c=(i+o).toString(16).padStart(8,`0`),l=``;for(let i=0;i<t;i++)n>0&&i>0&&i%n===0&&(l+=` `),l+=o+i<s?b9(e[o+i],r):` `;let u=``;for(let t=o;t<s;t++)u+=e[t]>=32&&e[t]<=126?String.fromCharCode(e[t]):`.`;a.push(`${c}: ${l} ${u}`)}return a.length?a.join(`
|
|
8640
8640
|
`)+`
|
|
8641
|
-
`:``}function
|
|
8642
|
-
`}return r}function
|
|
8641
|
+
`:``}function bue(e,t,n){let r=``;for(let i=0;i<e.length;i+=t){let a=``;for(let r=0;r<t&&i+r<e.length;r++)a+=b9(e[i+r],n);r+=a+`
|
|
8642
|
+
`}return r}function xue(e,t,n,r){let i=Array.from(e,e=>`0x${b9(e,n)}`),a=[];for(let e=0;e<i.length;e+=t)a.push(` `+i.slice(e,e+t).join(`, `));let o=a.join(`,
|
|
8643
8643
|
`);return r===null?i.length?o+`
|
|
8644
|
-
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function
|
|
8645
|
-
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const
|
|
8644
|
+
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function Sue(e){let t=e.replace(/[^0-9a-fA-F]/g,``),n=Math.floor(t.length/2),r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substr(e*2,2),16);return r}function Cue(e){let t=[],n=0;for(let r of e.split(`
|
|
8645
|
+
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const wue={"-u":`upper`,"-p":`plain`,"-ps":`plain`,"-postscript":`plain`,"-i":`include`,"-include":`include`,"-r":`revert`,"-revert":`revert`},Tue=[{key:`cols`,exact:[`-c`,`-cols`],attached:/^-c(0x)?[0-9]/},{key:`group`,exact:[`-g`,`-groupsize`],attached:/^-g(0x)?[0-9]/},{key:`length`,exact:[`-l`,`-len`],attached:/^-l(0x)?[0-9]/},{key:`seek`,exact:[`-s`,`-seek`],attached:/^-s[+-]?(0x)?[0-9]/}];function Eue(e){let t={upper:!1,plain:!1,include:!1,revert:!1,positional:[]};for(let n=0;n<e.length;n++){let r=e[n],i=wue[r];if(i){t[i]=!0;continue}let a=Tue.find(e=>e.exact.includes(r)||e.attached.test(r));if(a){t[a.key]=_ue(a.exact.includes(r)?e[++n]:r.slice(2));continue}if(r!==`-`&&r.startsWith(`-`)&&r.length>1)throw Error(`invalid option ${r}`);t.positional.push(r)}return t}function Due(e){return e.includes(`-h`)||e.includes(`--help`)||e.includes(`-help`)}async function Oue(e,t,n){if(!n&&t)return e.fs.readFileBuffer(e.fs.resolvePath(e.cwd,t));let r=iZ(e.stdin),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e)&255;return i}function kue(e,t,n,r,i){let a=e.cols&&e.cols>0?e.cols:e.plain?30:e.include?12:16;return e.plain?bue(t,a,e.upper):e.include?xue(t,a,e.upper,i?null:vue(r??``)):yue(t,a,e.group!=null&&e.group>=0?e.group:2,e.upper,n)}function Aue(e,t){let n=0,r=t;return e.seek!==void 0&&(n=e.seek<0?Math.max(0,r.length+e.seek):Math.min(e.seek,r.length),r=r.subarray(n)),e.length!==void 0&&(r=r.subarray(0,Math.max(0,e.length))),{data:r,base:n}}function jue(){return B(`xxd`,async(e,t)=>{if(Due(e))return{stdout:`usage: xxd [options] [infile [outfile]]
|
|
8646
8646
|
-c cols number of octets per line (default 16; 30 for -p; 12 for -i)
|
|
8647
8647
|
-g bytes number of octets per group (default 2; 0 disables grouping)
|
|
8648
8648
|
-l len stop after len octets
|
|
@@ -8652,11 +8652,11 @@ pass --wait to block and print the full result.
|
|
|
8652
8652
|
-i output in C include style
|
|
8653
8653
|
-r reverse: convert a hex dump back to binary (-r -p for plain)
|
|
8654
8654
|
-h show this help
|
|
8655
|
-
`,stderr:``,exitCode:0};let n;try{n=
|
|
8656
|
-
`,stderr:``,exitCode:0}}function
|
|
8655
|
+
`,stderr:``,exitCode:0};let n;try{n=Eue(e)}catch(e){return y9(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await Oue(t,r,a)}catch{return y9(`${r}: No such file or directory`)}if(n.revert){let e=x9(o),r=n.plain?Sue(e):Cue(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:x9(r),stderr:``,exitCode:0}}let{data:s,base:c}=Aue(n,o),l=kue(n,s,c,r,a);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),l),{stdout:``,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}})}async function S9(e,t,n,r){if((await e.fs.stat(t)).isFile)return r[n]=await e.fs.readFileBuffer(t),1;let i=await e.fs.readdir(t),a=0;for(let o of i){let i=gn(t,o),s=n?`${n}/${o}`:o;a+=await S9(e,i,s,r)}return a}function Mue(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
|
|
8656
|
+
`,stderr:``,exitCode:0}}function Nue(){return B(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Mue();let n=!1,r=[];for(let t of e){if(t===`-r`){n=!0;continue}if(t.startsWith(`-`))return{stdout:``,stderr:`zip: unsupported option ${t}\n`,exitCode:1};r.push(t)}if(r.length<2)return{stdout:``,stderr:`zip: expected archive path and at least one input path
|
|
8657
8657
|
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=r.slice(1),o={},s=0;for(let e of a){let r=t.fs.resolvePath(t.cwd,e),i=await t.fs.stat(r),a=(e.startsWith(`/`)?e.slice(1):e.replace(/^\.\//,``))||wn(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await S9(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
|
|
8658
|
-
`,exitCode:1};let c=Ht(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function Nue(e={}){let t=[eie({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),i1(),Jse(e.browserAPI,e.fs),ooe(e.browserAPI),Cie(e),Mue(),ole(),wce(),Aue(),L7(`sqlite3`),L7(`sqllite`),Fce(),Xce(),p2(),G$(),Nae({buildProcessConfig:e.buildProcessConfig}),a7(`python3`,{buildProcessConfig:e.buildProcessConfig}),a7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[_5(`ipk`,{fs:e.fs,fetch:e.fetch}),_5(`npm`,{fs:e.fs,fetch:e.fetch}),_5(`i`,{fs:e.fs,fetch:e.fetch}),T5(`ipx`,{fs:e.fs,fetch:e.fetch}),T5(`npx`,{fs:e.fs,fetch:e.fetch}),N0(`di`,{fs:e.fs,fetch:e.fetch}),N0(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[aie({fetch:e.fetch})]:[],$4(),Nle(),Ble(),X1(),Yie({fs:e.fs,scriptCatalog:e.scriptCatalog}),h3(),lce(),r7(`pdftk`),r7(`pdf`),B1(`convert`),B1(`magick`),Gle({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),Zce(),ile(),qie(),z0(),Bae(),Rae(),Wie(),Mse({setEnv:e.setEnv}),Woe({fs:e.fs}),sse(),E1(),D1(),O1(`xclip`),O1(`xsel`),nse(),k3(),XQ(),ZQ(),Aae(e.fs),bt(),Iae(),m$({getParentJid:e.getParentJid}),K0(),foe({processManager:e.processManager}),Lie({processManager:e.processManager}),Cle(),xie(),Y2(),o4(),y1({registry:e.cherryRuntimeRegistry}),r0(),u0({fs:e.fs}),d0({fs:e.fs}),dce(e.sudoCommand),cue({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),Vle()];return e.fs&&t.push(...A3.map(t=>Zre(t,e.browserAPI,e.fs))),t}const Pue=Reflect.get(yt,`DefenseInDepthBox`);var Fue=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=Pue?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=lt(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let e=Array(r.length);for(let t=0;t<r.length;t++)e[t]=String.fromCharCode(r[t]);return e.join(``)}})}async readFileBuffer(e){return this.trusted(async()=>{let t=lt(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async writeFile(e,t,n){return this.trusted(async()=>{let n=lt(e);if(typeof t==`string`){let e=d(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.trusted(async()=>{let n=lt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new P(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof P&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof P&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=lt(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(lt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t);return this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.trusted(async()=>{await this.vfs.rm(lt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=lt(e),i=lt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new P(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=ut(e,r.name),i=ut(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.trusted(async()=>{await this.vfs.rename(lt(e),lt(t))})}resolvePath(e,t){return t.startsWith(`/`)?lt(t):lt(ut(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,lt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(lt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(lt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function C9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?C9(e.getUnderlyingFS?.()):null}var w9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new Fue(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new wR({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new _O({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=C9(i)??C9(a);this.scriptCatalog=t.scriptCatalog??new Ln({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=g(),l=Nue({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),u=[s,this.createMountCustomCommand(),SQ(t.fs),UQ(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...Ct(),...vt()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new xt({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of vt())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let p=u.map(e=>e.name),m=f??[...Ct(),...vt()];this.builtinCommandNames=new Set([...m,...p]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return iZ(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){mr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await dZ(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=Nt(e);if(!n)return;let r=`${wt}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof P&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
8659
|
-
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return
|
|
8658
|
+
`,exitCode:1};let c=Ht(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function Pue(e={}){let t=[tie({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),a1(),Yse(e.browserAPI,e.fs),soe(e.browserAPI),wie(e),Nue(),sle(),Tce(),jue(),L7(`sqlite3`),L7(`sqllite`),Ice(),Zce(),m2(),K$(),Pae({buildProcessConfig:e.buildProcessConfig}),a7(`python3`,{buildProcessConfig:e.buildProcessConfig}),a7(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[_5(`ipk`,{fs:e.fs,fetch:e.fetch}),_5(`npm`,{fs:e.fs,fetch:e.fetch}),_5(`i`,{fs:e.fs,fetch:e.fetch}),T5(`ipx`,{fs:e.fs,fetch:e.fetch}),T5(`npx`,{fs:e.fs,fetch:e.fetch}),P0(`di`,{fs:e.fs,fetch:e.fetch}),P0(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[oie({fetch:e.fetch})]:[],e3(),Ple(),Vle(),Z1(),Xie({fs:e.fs,scriptCatalog:e.scriptCatalog}),g3(),uce(),r7(`pdftk`),r7(`pdf`),V1(`convert`),V1(`magick`),Kle({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),Qce(),ale(),Jie(),B0(),Vae(),zae(),Gie(),Nse({setEnv:e.setEnv}),Goe({fs:e.fs}),cse(),D1(),O1(),k1(`xclip`),k1(`xsel`),rse(),A3(),ZQ(),QQ(),jae(e.fs),bt(),Lae(),h$({getParentJid:e.getParentJid}),q0(),poe({processManager:e.processManager}),Rie({processManager:e.processManager}),wle(),Sie(),X2(),s4(),b1({registry:e.cherryRuntimeRegistry}),i0(),d0({fs:e.fs}),f0({fs:e.fs}),fce(e.sudoCommand),lue({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),Hle()];return e.fs&&t.push(...j3.map(t=>Qre(t,e.browserAPI,e.fs))),t}const Fue=Reflect.get(yt,`DefenseInDepthBox`);var Iue=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=Fue?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=lt(e),n=await this.vfs.readFile(t,{encoding:`binary`}),r=n instanceof Uint8Array?n:new TextEncoder().encode(n);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(r)}catch{let e=Array(r.length);for(let t=0;t<r.length;t++)e[t]=String.fromCharCode(r[t]);return e.join(``)}})}async readFileBuffer(e){return this.trusted(async()=>{let t=lt(e),n=await this.vfs.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)})}async writeFile(e,t,n){return this.trusted(async()=>{let n=lt(e);if(typeof t==`string`){let e=d(t);if(e){await this.vfs.writeFile(n,e);return}let r=!1;for(let e=0;e<t.length;e++)if(t.charCodeAt(e)>255){r=!0;break}if(r)await this.vfs.writeFile(n,new TextEncoder().encode(t));else{let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);await this.vfs.writeFile(n,e)}}else await this.vfs.writeFile(n,t)})}async appendFile(e,t,n){return this.trusted(async()=>{let n=lt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new P(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof P&&e.code===`EISDIR`)throw e}let r=new Uint8Array;try{let e=await this.vfs.readFile(n,{encoding:`binary`});r=e instanceof Uint8Array?new Uint8Array(e):new TextEncoder().encode(e)}catch(e){if(!(e instanceof P&&e.code===`ENOENT`))throw e}let i;if(typeof t==`string`){i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e)&255}else i=t instanceof Uint8Array?t:new Uint8Array(t);let a=new Uint8Array(r.length+i.length);a.set(r),a.set(i,r.length),await this.vfs.writeFile(n,a)})}async exists(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=lt(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(lt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`)return[`bin`];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort();let n=this.vfs.readDirSync(t);return n===null?(await this.vfs.readDir(t)).map(e=>e.name):n.map(e=>e.name)})}async readdirWithFileTypes(e){return this.trusted(async()=>{let t=lt(e);if(t===`/usr`)return[{name:`bin`,isFile:!1,isDirectory:!0,isSymbolicLink:!1}];if(t===`/usr/bin`)return this.getVirtualBinCommands().slice().sort().map(e=>({name:e,isFile:!0,isDirectory:!1,isSymbolicLink:!1}));let n=this.vfs.readDirSync(t);if(n!==null)return this.mapFastEntriesToDirents(n);let r=await this.vfs.readDir(t);return this.mapAsyncEntriesToDirents(r)})}mapFastEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}mapAsyncEntriesToDirents(e){return e.map(e=>this.entryToDirent(e))}entryToDirent(e){return e.type===`symlink`?{name:e.name,isFile:!1,isDirectory:!1,isSymbolicLink:!0}:{name:e.name,isFile:e.type===`file`,isDirectory:e.type===`directory`,isSymbolicLink:!1}}async rm(e,t){return this.trusted(async()=>{await this.vfs.rm(lt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=lt(e),i=lt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new P(`EISDIR`,`is a directory`,r);await this.cpDir(r,i)}else await this.vfs.copyFile(r,i)})}async cpDir(e,t){await this.vfs.mkdir(t,{recursive:!0});let n=await this.vfs.readDir(e);for(let r of n){let n=ut(e,r.name),i=ut(t,r.name);r.type===`directory`?await this.cpDir(n,i):await this.vfs.copyFile(n,i)}}async mv(e,t){return this.trusted(async()=>{await this.vfs.rename(lt(e),lt(t))})}resolvePath(e,t){return t.startsWith(`/`)?lt(t):lt(ut(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,lt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(lt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(lt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function C9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?C9(e.getUnderlyingFS?.()):null}var w9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new Iue(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new wR({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new _O({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=C9(i)??C9(a);this.scriptCatalog=t.scriptCatalog??new Ln({jshFs:i,bshFs:a,watcher:o}),this.ownsScriptCatalog=!t.scriptCatalog,o&&o.watch(`/`,e=>e.endsWith(`.jsh`)||e.endsWith(`.workflow.js`),()=>{this.syncJshCommands().catch(()=>void 0)});let s=this.createGitCustomCommand(),c=g(),l=Pue({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),u=[s,this.createMountCustomCommand(),CQ(t.fs),WQ(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...Ct(),...vt()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new xt({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:f,customCommands:u}),this.allowedCommands!==null){let e=this.bash;for(let t of vt())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let p=u.map(e=>e.name),m=f??[...Ct(),...vt()];this.builtinCommandNames=new Set([...m,...p]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return aZ(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){mr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await fZ(r,{policy:i,broker:n.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},defaultDisposition:n.defaultDisposition});return a.allowed?null:{stdout:``,stderr:`${a.message}\n`,exitCode:1}}registerSudoBypass(e){let t=e.trim();t&&this.pendingSudoBypasses.set(t,(this.pendingSudoBypasses.get(t)??0)+1)}consumeSudoBypass(e){let t=this.pendingSudoBypasses.get(e);return t?(t===1?this.pendingSudoBypasses.delete(e):this.pendingSudoBypasses.set(e,t-1),!0):!1}async flushPendingCommandGrants(){if(this.pendingCommandGrants.length===0)return;let e=this.pendingCommandGrants;this.pendingCommandGrants=[];for(let t of e)try{await this.persistCommandGrant(t)}catch{}}async persistCommandGrant(e){let t=this.options.sudo?.persistCommandGrant;if(t){await t(e);return}let n=Nt(e);if(!n)return;let r=`${wt}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof P&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
8659
|
+
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return oZ(t,[`node`,s,...e],{fs:a.fs,cwd:a.cwd,env:a.env,stdin:a.stdin,exec:o},n.buildJshProcessConfig())}let c=(await t.getWorkflowCommands()).get(i);if(c){let t=In(c.path,e);return o(t[0],{args:t.slice(1),cwd:a.cwd})}return{stdout:``,stderr:`${i}: command no longer exists\n`,exitCode:127}}}}createGitCustomCommand(){let e=this.gitCommands;return B(`git`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}createMountCustomCommand(){let e=this.mountCommands;return B(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?dZ(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await oZ(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig());return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}buildJshProcessConfig(){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>this.activeShellPid??this.options.getCurrentShellPid?.()}}};function T9(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}var Lue=class extends w9{terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;constructor(e){super(e)}async runCommand(e,t){return super.runCommand(e,t??this.execAbort?.signal)}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await import(`./xterm-DX7Hb5S-.js`),{FitAddon:r}=await import(`./addon-fit-Crogpbda.js`);await Promise.resolve({ });let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
|
|
8660
8660
|
`),this.showPrompt(),this.setupInputHandler()}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
|
|
8661
8661
|
`,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,super.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
|
|
8662
8662
|
`).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
|
|
@@ -8671,15 +8671,15 @@ pass --wait to block and print the full result.
|
|
|
8671
8671
|
`,this.cursorPos);if(e===-1&&(e=this.currentLine.length),this.cursorPos===e)return;let t=e-this.cursorPos;this.cursorPos=e,this.terminal?.write(`\x1b[${t}C`)}handleCtrlC(){this.terminal?.writeln(`^C`),this.currentLine=``,this.cursorPos=0,this.continuationBuffer=``,this.showPrompt()}handleHistoryUp(){this.history.length!==0&&this.historyIndex<this.history.length-1&&(this.historyIndex++,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex]))}handleHistoryDown(){this.historyIndex>0?(this.historyIndex--,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex])):this.historyIndex===0&&(this.historyIndex=-1,this.continuationBuffer=``,this.replaceCurrentLine(``))}insertAtCursor(e){e&&(this.currentLine=this.currentLine.slice(0,this.cursorPos)+e+this.currentLine.slice(this.cursorPos),this.cursorPos+=e.length,this.terminal?.write(e))}async handleTab(){if(!this.terminal)return;let e=this.currentLine.slice(0,this.cursorPos).split(/\s+/),t=e[e.length-1]||``,n=e.length<=1||e.length===2&&e[0]===``,r=t?`'`+t.replace(/'/g,`'\\''`)+`'`:`''`,i=n?`compgen -A command -- ${r}`:`compgen -f -- ${r}`;try{let e=(await this.bash.exec(i,{env:this.lastEnv,cwd:this.cwd})).stdout.split(`
|
|
8672
8672
|
`).filter(Boolean);if(e.length===0)return;e.length===1?await this.applySingleCompletion(t,e[0],n,r):this.applyMultiCompletion(t,e)}catch(e){console.warn(`[Shell] Tab completion failed:`,e instanceof Error?e.message:String(e))}}async applySingleCompletion(e,t,n,r){let i=t.slice(e.length);this.insertAtCursor(i);let a=` `;n||(await this.bash.exec(`compgen -d -- ${r.slice(0,-1)}${i}'`,{env:this.lastEnv,cwd:this.cwd})).stdout.trim()===t&&(a=`/`),this.insertAtCursor(a)}applyMultiCompletion(e,t){let n=t[0];for(let e of t)for(;!e.startsWith(n);)n=n.slice(0,-1);let r=n.slice(e.length);if(r){this.insertAtCursor(r);return}this.terminal?.writeln(``),this.terminal?.writeln(t.map(e=>e.split(`/`).pop()??e).join(` `)),this.showPrompt(),this.terminal?.write(this.currentLine);let i=this.currentLine.length-this.cursorPos;i>0&&this.terminal?.write(`\x1b[${i}D`)}replaceCurrentLine(e){let t=this.getCursorVisualLine();t>0&&this.terminal?.write(`\x1b[${t}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.currentLine=e,this.cursorPos=e.length,this.terminal?.write(e)}isIncomplete(e){if(e.endsWith(`\\`))return!0;let t=!1,n=!1,r=!1;for(let i of e){if(r){r=!1;continue}if(i===`\\`&&!t){r=!0;continue}if(i===`'`&&!n){t=!t;continue}i===`"`&&!t&&(n=!n)}return t||n}async handleEnter(){let e=this.currentLine.split(`
|
|
8673
8673
|
`);if(e.length>1){let t=this.getCursorVisualLine(),n=e.length-1-t;n>0&&this.terminal?.write(`\x1b[${n}B`);let r=e[e.length-1].length;this.terminal?.write(`\r`),r>0&&this.terminal?.write(`\x1b[${r}C`)}this.terminal?.writeln(``);let t=this.currentLine;this.currentLine=``,this.cursorPos=0;let n=this.continuationBuffer?this.continuationBuffer+`
|
|
8674
|
-
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${T9(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=T9(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}};const E9=r(`tool:bash`),
|
|
8674
|
+
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${T9(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=T9(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}};const E9=r(`tool:bash`),Rue=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function zue(e){let t=[],n=``,r=null,i=!1,a=()=>{t.push(n),n=``};for(let t=0;t<e.length;t++){let o=e[t];if(i){n+=o,i=!1;continue}if(o===`\\`){n+=o,i=!0;continue}if(r){n+=o,o===r&&(r=null);continue}if(o===`"`||o===`'`){n+=o,r=o;continue}if((o===`&`||o===`|`)&&e[t+1]===o){a(),t++;continue}if(o===`;`||o===`|`){a();continue}n+=o}return a(),t}function Bue(e){let t=zue(e);return(t[t.length-1]??``).trim()}function Vue(e,t,n){return t!==1||n.trim()?!1:Rue.test(Bue(e))}function Hue(e){return{name:`bash`,description:"Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run `commands` for full list.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;E9.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);E9.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!Vue(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return E9.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const D9=r(`tool:fs`);function Uue(e){return[Wue(e),Gue(e),Kue(e)]}function Wue(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;D9.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
8675
8675
|
`),a=Math.max(0,r-1),o=i===void 0?t.length:a+i;return{content:t.slice(a,o).map((e,t)=>`${String(a+t+1).padStart(6)} | ${e}`).join(`
|
|
8676
|
-
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function
|
|
8677
|
-
`)}async function
|
|
8678
|
-
`)}`}}function
|
|
8679
|
-
`)}}function
|
|
8680
|
-
`)}`}}async function hde(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),O9.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function gde(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>Yue(t,e)}}function _de(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...A9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>Que(t,e)}}function vde(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>$ue(t,e)}}function yde(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>ede(e)}}function bde(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes. Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...oE],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`}},required:[`name`]},execute:t=>rde(t,e)}}function xde(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>ide(t,e)}}function Sde(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>ade(t,e)}}function Cde(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>sde(t,e)}}function wde(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to wait for (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>ude(t,e)}}function Tde(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>fde(t,e)}}function Ede(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>pde(t,e)}}function Dde(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>mde(e)}}function Ode(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>hde(t,e)}}function kde(e){let t=[],n=e.scoop.isCone;return n||(t.push(gde(e)),e.onSudoRequest&&t.push(_de(e))),n&&(e.onFeedScoop&&t.push(vde(e)),t.push(yde(e)),e.onScoopScoop&&t.push(bde(e)),e.onDropScoop&&t.push(xde(e)),e.onMuteScoops&&t.push(Sde(e)),e.onUnmuteScoops&&t.push(Cde(e)),e.onScheduleScoopWait&&t.push(wde(e)),e.onSudoResolve&&(t.push(Tde(e)),t.push(Ede(e))),e.onListSudoRequests&&t.push(Dde(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(Ode(e))),t}const P9=r(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!dt(t).includes(`xhigh`)?`high`:e}function Ade(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function jde(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function I9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function L9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var Mde=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await BD(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await hO(),i=this.buildSudoWiring(),a=i?Ot(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new Iue({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),P9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await ID(n,this.skillsDir)}}async buildTools(e){let t=kde({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...Hue(e),Vue(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:k()};return this.processManager?ae(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):ae(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=E(e.messages);return this.sessionCreatedAt=e.createdAt,P9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){P9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Rt(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?pt(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):pt(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:oe()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:te({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>oe()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);P9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!oe()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?T(this.scoop.config.modelId):A(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=F9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new Bne({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>oe()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),P9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);P9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=se()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(P9.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return jde(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),cr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return tr(e)?(P9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),ir(this.scoop.isCone),cr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!I9(e)||t>=n)return!1;let a=r*2**(t-1);return P9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await L9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;P9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),cr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(P9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:I9(a)}),!!(t<n&&(await L9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?T(this.scoop.config.modelId):A();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=A();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=F9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,P9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await ID(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,P9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=F9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(oE.includes(e))return e;P9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8676
|
+
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Gue(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;D9.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function Kue(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;D9.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return D9.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const O9=r(`scoop-management-tools`);function k9(e,t){let n=t(),r=[],i=[];for(let t of e){let e=n.find(e=>!e.isCone&&(e.folder===t||e.name===t));e?r.push(e):i.push(t)}return{resolved:r,unknown:i}}const A9=[`command`,`read`,`write`,`secret`];function que(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function Jue(e){return e===void 0?{ok:!0}:sE(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${oE.join(`, `)}.`,isError:!0}}function j9(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function Yue(e,t){let n=t?.(e.jid),r=n?.status??`unknown`,i=n?.lastActivity?new Date(n.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,a=i?` — ${r} (since ${i})`:` — ${r}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${a}`:`- ${e.name} (${e.folder})${a}`}async function Xue(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),O9.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function Zue(e){let{kind:t,detail:n,suggested_pattern:r}=e;return A9.includes(t)?typeof n!=`string`||n.trim().length===0?{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}}:{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{}}}:{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${A9.join(`, `)}.`,isError:!0}}}function Que(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.decision===`deny`&&t.push(`The sensitive action was not approved. Do not retry without addressing the reason for refusal.`),t.join(`
|
|
8677
|
+
`)}async function $ue(e,t){let n=Zue(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return O9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:Que(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function ede(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return j9(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),O9.info(`Fed scoop`,{target:i.folder,promptLength:r.length}),{content:`Task sent to ${i.folder}. You will be notified when it completes.`}}catch(e){return{content:`Failed to feed scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function tde(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>Yue(t,e.getScoopTabState)).join(`
|
|
8678
|
+
`)}`}}function nde(e,t,n,r,i,a,o){return{name:e,folder:t,trigger:`@${t}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},visiblePaths:r??[`/workspace/`],writablePaths:i??[`/scoops/${t}/`,`/shared/`],...a?{allowedCommands:a}:{},...o?{thinkingLevel:o}:{}},configSchemaVersion:2}}async function rde(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return O9.error(`Auto-feed failed`,{name:n,error:t}),{content:`Scoop "${n}" created as "${r}" but the initial task could not be sent: ${t}. Use feed_scoop to retry.`,isError:!0}}return{content:`Scoop "${n}" created as "${r}" and task sent. It is now working on it.`}}async function ide(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=Jue(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=que(n);try{let e=nde(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return O9.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?rde(c,i,n,u,t.onFeedScoop):{content:`Scoop "${n}" created as "${u}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function ade(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return j9(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),O9.info(`Scoop dropped`,{name:r.name,folder:r.folder}),{content:`Scoop "${r.name}" (${r.folder}) has been dropped.`}}catch(e){return{content:`Failed to drop scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function M9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function N9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function ode(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);return r.length===0?N9(i):(t.onMuteScoops(r.map(e=>e.jid)),O9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function sde(e,t){if(e.length===0)return[`No stashed completions.`];let n=[``,`Stashed completions:`];for(let r of e){let e=t.get(r.jid)??r.jid;n.push(`--- ${e} ---`),r.notificationPath&&n.push(`VFS path: ${r.notificationPath}`),n.push(r.summary)}return n}async function cde(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return M9();let{resolved:r,unknown:i}=k9(n,t.getScoops);if(r.length===0)return N9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);O9.info(`Scoops unmuted`,{names:r.map(e=>e.folder),stashedCount:s.length});let c=[`Unmuted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`];return c.push(...sde(s,o)),{content:c.join(`
|
|
8679
|
+
`)}}function lde(e,t){return!Array.isArray(e)||e.length===0?M9():t!==void 0&&(typeof t!=`number`||!Number.isFinite(t)||t<0)?{content:`timeout_ms must be a non-negative finite number (or omitted).`,isError:!0}:null}function ude(e,t,n,r){return`scoop_wait scheduled for: ${e}${r===void 0?` (no timeout)`:` (timeout: ${r}ms)`}.${t.length>0?` Unknown (skipped): ${t.join(`, `)}.`:``}${n?` Dropped before schedule (skipped): ${n}.`:``} Continue with other work — a 'scoop-wait' lick will be delivered when all listed scoops complete or the timeout fires.`}async function dde(e,t){let{scoop_names:n,timeout_ms:r}=e,i=lde(n,r);if(i)return i;let{resolved:a,unknown:o}=k9(n,t.getScoops);if(a.length===0)return N9(o);let s=a.map(e=>e.jid),c=t.onScheduleScoopWait(s,r),l=new Map(a.map(e=>[e.jid,e.folder])),u=c.scheduled.map(e=>l.get(e)??e).join(`, `),d=c.unknown.map(e=>l.get(e)??e).join(`, `);return O9.info(`Wait scheduled`,{scheduled:c.scheduled.map(e=>l.get(e)??e),droppedAtSchedule:d?d.split(`, `):[],unknownNames:o,timeout_ms:r}),c.scheduled.length===0?{content:`scoop_wait could not be scheduled — every listed scoop was unregistered before the wait could start (dropped: ${d||c.unknown.join(`, `)}).${o.length>0?` Unknown names: ${o.join(`, `)}.`:``}`,isError:!0}:{content:ude(u,o,d,r)}}function fde(e,t){return t?e.persisted?`Approved (always) — persisted NOPASSWD rule for ${e.kind??`unknown`} pattern "${e.persistedPattern}" in /scoops/${e.scoopFolder??`<unknown>`}/etc/sudoers.`:e.persistError?`Approved (always) but could NOT persist a rule (${e.persistError}). The current action is allowed; future occurrences will prompt again.`:`Approved (always) — no persistable rule applied for this request.`:`Approved (once) — the current action proceeds; future ones will prompt again.`}async function pde(e,t){let{lick_id:n,always:r,pattern:i}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};let a=r?{decision:`always`,...i?{pattern:i}:{}}:{decision:`allow`};try{let e=await t.onSudoResolve(n,a);return e.settled?(O9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:fde(e,!!r)}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_confirm failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function mde(e,t){let{lick_id:n}=e;if(typeof n!=`string`||n.length===0)return{content:`lick_id must be a non-empty string.`,isError:!0};try{let e=await t.onSudoResolve(n,{decision:`deny`});return e.settled?(O9.info(`Lick dismissed`,{id:n}),e.message?{content:e.message}:{content:`Denied — the scoop will not run this action.`}):{content:`Lick "${n}" is unknown, already resolved, or timed out.`,isError:!0}}catch(e){return{content:`lick_dismiss failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function hde(e){let t=e.onListSudoRequests();return t.length===0?{content:`No pending sudo requests.`}:{content:`Pending sudo requests:\n${t.map(t=>{let n=e.getScoops().find(e=>e.jid===t.scoopJid)?.folder??t.scoopJid,r=t.request.suggestedPattern?` (suggested: ${t.request.suggestedPattern})`:``;return`- ${t.id} — ${n} — ${t.request.kind}: ${t.request.detail}${r}`}).join(`
|
|
8680
|
+
`)}`}}async function gde(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),O9.info(`Global memory updated`),{content:`Global memory updated successfully.`}}catch(e){return{content:`Failed to update global memory: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}function _de(e){return{name:`send_message`,description:`Send a progress message while still working. Your final output is also sent.`,inputSchema:{type:`object`,properties:{text:{type:`string`,description:`The message text to send`},sender:{type:`string`,description:`Optional sender name/role (e.g., "Researcher"). Defaults to assistant name.`}},required:[`text`]},execute:t=>Xue(t,e)}}function vde(e){return{name:`sudo_request`,description:`Ask the cone for an explicit sudo escalation before running a sensitive action. Use this when you know up-front that a command, read, or write will be gated and you want a clean approval round-trip instead of letting the gate fire mid-action. Resolves with the cone's decision (allow / always / deny). 'always' durably widens your sandbox by appending a NOPASSWD rule to /scoops/<folder>/etc/sudoers. 'deny' (or a timeout / dropped cone) resolves fail-closed.`,inputSchema:{type:`object`,properties:{kind:{type:`string`,enum:[...A9],description:`The kind of sensitive action being requested. command = a shell command; read/write = a VFS path; secret = a credential read. Only command/read/write can be persisted with "always" (no sudoers Secret directive).`},detail:{type:`string`,description:`The concrete subject of the request (e.g., the command line "git push origin main" or the VFS path "/workspace/.git/config"). The cone sees this verbatim.`},suggested_pattern:{type:`string`,description:`Optional pre-filled glob pattern for an "always" grant (e.g., "git push*" for a command or "/workspace/.git/**" for a path). The cone may override this.`}},required:[`kind`,`detail`]},execute:t=>$ue(t,e)}}function yde(e){return{name:`feed_scoop`,description:`Give a scoop a task. Provide a complete, self-contained prompt — the scoop has no access to your conversation. You'll be notified when it finishes.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`},prompt:{type:`string`,description:`Complete, self-contained instructions for the scoop. Include ALL context — the scoop cannot see your conversation.`}},required:[`scoop_name`,`prompt`]},execute:t=>ede(t,e)}}function bde(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>tde(e)}}function xde(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes. Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...oE],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`}},required:[`name`]},execute:t=>ide(t,e)}}function Sde(e){return{name:`drop_scoop`,description:`Remove a scoop and stop its work. The scoop will be unregistered and its context destroyed.`,inputSchema:{type:`object`,properties:{scoop_name:{type:`string`,description:`The scoop folder name (e.g., "test-scoop"). Use list_scoops to see available scoops.`}},required:[`scoop_name`]},execute:t=>ade(t,e)}}function Cde(e){return{name:`scoop_mute`,description:`Suspend scoop→cone notifications for the given scoops. While muted, a scoop's completion is stashed and will be delivered to the cone when you call scoop_unmute (or scoop_wait which consumes it). Use this when coordinating parallel work so each scoop's completion does not trigger its own cone turn.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to mute (e.g., ["writer-scoop", "reviewer-scoop"]).`}},required:[`scoop_names`]},execute:t=>ode(t,e)}}function wde(e){return{name:`scoop_unmute`,description:`Resume scoop→cone notifications for the given scoops. Any completion that landed while a scoop was muted is returned in this tool result (NOT dispatched as a new cone turn), so you can read all stashed summaries in the current turn. Scoops with no stashed completion are simply unmuted.`,inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to unmute (e.g., ["writer-scoop"]).`}},required:[`scoop_names`]},execute:t=>cde(t,e)}}function Tde(e){return{name:`scoop_wait`,description:"Schedule a non-blocking wait for the given scoops. Returns immediately — the cone keeps its turn — and a `scoop-wait` lick is delivered when every listed scoop completes or the optional timeout fires. Use this to coordinate parallel work without freezing the cone: feed several scoops, call scoop_wait, then continue with other work; you'll be woken by the lick with all per-scoop summaries in one shot. Already-completed scoops (including those whose completion arrived while you were processing your previous turn) are folded into the same lick.",inputSchema:{type:`object`,properties:{scoop_names:{type:`array`,items:{type:`string`},description:`Folder or display names of scoops to wait for (e.g., ["writer-scoop", "reviewer-scoop"]).`},timeout_ms:{type:`number`,description:"Optional timeout in milliseconds. If any listed scoop has not completed by the deadline, it is reported as timed-out in the eventual `scoop-wait` lick. Omit for no timeout."}},required:[`scoop_names`]},execute:t=>dde(t,e)}}function Ede(e){return{name:`lick_confirm`,description:`Confirm (approve) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. With always=true, the orchestrator additionally appends a NOPASSWD <directive> <pattern> rule to the requesting scoop's /scoops/<folder>/etc/sudoers so the same action won't prompt again. always=false (the default) is allow-once.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification, e.g. "lick-…"). Use list_sudo_requests to see outstanding ids.`},always:{type:`boolean`,description:`If true, persist a NOPASSWD rule into the requesting scoop's per-scoop sudoers so the action won't prompt again. Defaults to false (allow-once).`},pattern:{type:`string`,description:`Optional glob pattern to persist when always=true (e.g., "git push*" or "/workspace/.git/**"). Defaults to the request's suggestedPattern, then to the exact detail. Ignored when always=false.`}},required:[`lick_id`]},execute:t=>pde(t,e)}}function Dde(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>mde(t,e)}}function Ode(e){return{name:`list_sudo_requests`,description:`List all pending cone-mediated sudo requests (lick id, requesting scoop, kind, detail). Use to find a lick_id for lick_confirm / lick_dismiss.`,inputSchema:{type:`object`,properties:{}},execute:()=>hde(e)}}function kde(e){return{name:`update_global_memory`,description:`Update the global CLAUDE.md memory file that is shared across all scoops. Use this instead of write_file for /shared/CLAUDE.md.`,inputSchema:{type:`object`,properties:{content:{type:`string`,description:`The new content for the global memory file`}},required:[`content`]},execute:t=>gde(t,e)}}function Ade(e){let t=[],n=e.scoop.isCone;return n||(t.push(_de(e)),e.onSudoRequest&&t.push(vde(e))),n&&(e.onFeedScoop&&t.push(yde(e)),t.push(bde(e)),e.onScoopScoop&&t.push(xde(e)),e.onDropScoop&&t.push(Sde(e)),e.onMuteScoops&&t.push(Cde(e)),e.onUnmuteScoops&&t.push(wde(e)),e.onScheduleScoopWait&&t.push(Tde(e)),e.onSudoResolve&&(t.push(Ede(e)),t.push(Dde(e))),e.onListSudoRequests&&t.push(Ode(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(kde(e))),t}const P9=r(`scoop-context`);function F9(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!dt(t).includes(`xhigh`)?`high`:e}function jde(e){return/image exceeds.*maximum/i.test(e)||/Could not process image/i.test(e)||/invalid.*image/i.test(e)||/image.*too (large|big)/i.test(e)}function Mde(e){return/\b(401|403|404|405|410|422)\b/.test(e)||/unauthorized|forbidden|authentication.*failed|invalid.*api.?key/i.test(e)||/session expired|log in again|re-?authenticate/i.test(e)||/model.*not.*found|invalid.*model|unknown.*model|does.*not.*exist/i.test(e)||/decommissioned|no longer supported|deprecated.*model|model.*deprecated|model.*retired/i.test(e)||/insufficient.*quota|billing|payment.*required|account.*suspended/i.test(e)||/invalid.*request|malformed|bad.*request/i.test(e)}function I9(e){return/\b429\b|rate.*limit|too.*many.*requests|quota.*exceeded/i.test(e)||/\b(500|502|503|504)\b|internal.*server|bad.*gateway|service.*unavailable|gateway.*timeout/i.test(e)||/network.*error|failed to fetch|connection.*refused|timeout|econnreset|socket.*hang.*up/i.test(e)||/overloaded|temporarily.*unavailable|try.*again/i.test(e)}function L9(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var Nde=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await BD(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await hO(),i=this.buildSudoWiring(),a=i?Ot(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new Lue({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),P9.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await ID(n,this.skillsDir)}}async buildTools(e){let t=Ade({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...Uue(e),Hue(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:k()};return this.processManager?ae(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):ae(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=E(e.messages);return this.sessionCreatedAt=e.createdAt,P9.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){P9.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Rt(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?pt(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):pt(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:oe()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:te({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>oe()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);P9.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!oe()){P9.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?T(this.scoop.config.modelId):A(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=F9(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new Bne({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>oe()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),P9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);P9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=se()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(P9.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return Mde(e)?(P9.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),cr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return tr(e)?(P9.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),ir(this.scoop.isCone),cr(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!I9(e)||t>=n)return!1;let a=r*2**(t-1);return P9.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await L9(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;P9.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),cr(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(P9.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:I9(a)}),!!(t<n&&(await L9(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?T(this.scoop.config.modelId):A();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=A();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=F9(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,P9.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await ID(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,P9.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=F9(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(oE.includes(e))return e;P9.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8681
8681
|
`);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
|
|
8682
|
-
`);cr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&
|
|
8682
|
+
`);cr(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&jde(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&d_(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,cr(`llm`,n),this.callbacks.onError(n)}else this.isRecovering=!1}let t=this.agent?.state?.messages??e;this.sessionStore&&t.length>0&&this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{P9.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}handleAgentEvent(e){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e);break;case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages);break}}trimOversizedMessages(e){let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,P9.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}return{trimmed:t,replaced:n}}recoverFromOverflow(e){if(this.agent){P9.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let{trimmed:t,replaced:n}=this.trimOversizedMessages(e);this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{P9.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){P9.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){P9.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{P9.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){P9.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
8683
8683
|
|
|
8684
8684
|
${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
|
|
8685
8685
|
Folder: ${this.scoop.folder}
|
|
@@ -8760,14 +8760,14 @@ ${e}
|
|
|
8760
8760
|
---
|
|
8761
8761
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
8762
8762
|
${t}
|
|
8763
|
-
---`);let a=zD(n);return a&&(i+=a),i}};const R9=r(`scoop-lifecycle-manager`);var Nde=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){R9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){R9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new _t(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new Mde(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),R9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),R9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return R9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){R9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),R9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||dr(`spawn`,e.folder)}catch(n){R9.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){R9.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=>{R9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{R9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{R9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),dr(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),dr(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=r(`scoop-message-router`);var Pde=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;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.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(z9.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){z9.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}`);dr(`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),z9.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);z9.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){z9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){z9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){z9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{z9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){z9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){z9.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);if(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){z9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${Wne(e.content,e.attachments)}`).join(`
|
|
8764
|
-
`),c=o.flatMap(e=>Gne(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{z9.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=>{z9.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,[]),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.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.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),z9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const B9=r(`orchestrator`);var Fde=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new WD({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new dO({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new lO({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new aO({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;approvalRouter=new ZD({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Le(e),saveMessage:e=>ke(e)});lickRegistry=new qD({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Pde({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>ke(e),deleteMessage:e=>Me(e),clearMessagesForScoop:e=>Fe(e),clearAllMessages:()=>Re(),getMessagesSince:(e,t,n)=>Pe(e,t,n),setState:(e,t)=>Ve(e,t)},isExternalLickChannel:Rr});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Nde({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=>He(e),deleteScoop:e=>Oe(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>ot(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(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(){await Be(),this.sharedFs=await gt.create({dbName:`slicc-fs`}),this.sessionStore=new qne,this.fsWatcher=new ht,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new YE({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await Ne();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await je(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new YD({onTaskRun:async(e,t)=>{B9.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(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);B9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}St(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/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.setScoopExistenceResolver(e=>this.getScoops().some(t=>rt(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)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await gt.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await BD(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new YE({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.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 Le(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}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(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}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&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,B9.info(`Orchestrator shutdown`)}};function Ide(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Lde=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=H9(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=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new P(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new P(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new P(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new P(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new P(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new P(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new P(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new P(`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 P(`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 Ude(t);let n=this.pm.get(e);switch(t){case`status`:return Rde(n);case`cmdline`:return zde(n);case`cwd`:return Bde(n);case`stat`:return Vde(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Rde(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${Hde(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(`
|
|
8763
|
+
---`);let a=zD(n);return a&&(i+=a),i}};const R9=r(`scoop-lifecycle-manager`);var Pde=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){R9.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){R9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)R9.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{R9.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new _t(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new Nde(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),R9.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),R9.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return R9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(R9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){R9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){R9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),R9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),R9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||dr(`spawn`,e.folder)}catch(n){R9.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){R9.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=>{R9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{R9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{R9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&R9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),R9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){R9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();R9.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{R9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),R9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){R9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),dr(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);R9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),dr(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){R9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{R9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const z9=r(`scoop-message-router`);var Fde=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;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.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(z9.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){z9.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}`);dr(`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),z9.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);z9.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){z9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){z9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(z9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){z9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{z9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){z9.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){z9.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);if(z9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){z9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${Wne(e.content,e.attachments)}`).join(`
|
|
8764
|
+
`),c=o.flatMap(e=>Gne(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);z9.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{z9.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=>{z9.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,[]),z9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{z9.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.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),z9.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const B9=r(`orchestrator`);var Ide=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new WD({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new dO({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new lO({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new aO({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;approvalRouter=new ZD({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Le(e),saveMessage:e=>ke(e)});lickRegistry=new qD({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Fde({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>ke(e),deleteMessage:e=>Me(e),clearMessagesForScoop:e=>Fe(e),clearAllMessages:()=>Re(),getMessagesSince:(e,t,n)=>Pe(e,t,n),setState:(e,t)=>Ve(e,t)},isExternalLickChannel:Rr});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Pde({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=>He(e),deleteScoop:e=>Oe(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>ot(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(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(){await Be(),this.sharedFs=await gt.create({dbName:`slicc-fs`}),this.sessionStore=new qne,this.fsWatcher=new ht,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new YE({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await Ne();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await je(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new YD({onTaskRun:async(e,t)=>{B9.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(),B9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);B9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}St(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/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.setScoopExistenceResolver(e=>this.getScoops().some(t=>rt(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)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await gt.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await BD(this.sharedFs).catch(e=>{B9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new YE({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),B9.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 Le(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}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(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}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&&B9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,B9.info(`Orchestrator shutdown`)}};function Lde(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Rde=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=H9(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=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);return V9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new P(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=H9(e);if(t.length!==2)throw new P(`EISDIR`,`is a directory`,e);let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new P(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new P(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=H9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=U9(t[0]);if(n===null||!this.pidExists(n))throw new P(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!V9.includes(r))throw new P(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new P(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new P(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new P(`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 P(`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 Wde(t);let n=this.pm.get(e);switch(t){case`status`:return zde(n);case`cmdline`:return Bde(n);case`cwd`:return Vde(n);case`stat`:return Hde(n)}}};const V9=[`status`,`cmdline`,`cwd`,`stat`];function H9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function U9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function zde(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${W9(e.status)} (${e.status})`,`Owner:\t${Ude(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(`
|
|
8765
8765
|
`)+`
|
|
8766
|
-
`}function
|
|
8767
|
-
`}function
|
|
8768
|
-
`}function W9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function
|
|
8766
|
+
`}function Bde(e){return e.argv.join(`\0`)+`\0`}function Vde(e){return e.cwd+`
|
|
8767
|
+
`}function Hde(e){return[e.pid,`(${e.kind})`,W9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
8768
|
+
`}function W9(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function Ude(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function Wde(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
|
|
8769
8769
|
`)+`
|
|
8770
8770
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
8771
8771
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
8772
|
-
`}}function
|
|
8773
|
-
`,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 nfe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CW-Xewtf.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 rfe(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 Ci(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})},ife(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function ife(e){let t=g();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,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:()=>Ide()}}function afe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-_mFoJDg1.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 ofe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Dy4tXX0j.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 sfe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.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 cfe(){return D()}async function lfe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await Zde(t,n,r,i);if(d?rre(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Lde(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await Qde(c,e,o);d&&efe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await tfe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;cfe()&&(h=await nfe(f,o,e.localLickWsUrl??null));let g=rfe(n,f,o);d&&afe(d,f,o),a||await $de(c),d&&ofe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await sfe(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=Kde({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await ufe({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function ufe(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)}dfe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function dfe(e){let t=globalThis;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[u9]}const G9=`x-bypass-llm-proxy`;function ffe(e,t,n){return t?(r,i)=>{if(!pfe(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 pfe(e,t,n){if(hfe(e,t))return!0;let r=n?.()??null;return r?mfe(e,r,t):!1}function mfe(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 hfe(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 gfe(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 _fe=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(!vfe(e)||e.source!==`panel`)return;let t=e.payload;yfe(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;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 vfe(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 yfe(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 bfe=class extends w9{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 xfe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new _fe({transport:t,processManager:i,createShell:(e,a)=>new bfe(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Sfe(e){let t=new Cfe(e);return t.start(),{stop:()=>t.dispose()}}var Cfe=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(!wfe(e)||e.source!==`panel`)return;let t=e.payload;if(Tfe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Efe(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 P(`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 P(`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(Dfe(e.type),e.requestId,new P(`EACCES`,`vfs-rpc-host has no writable backend wired`),Ofe(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 P(`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 P(`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 P(`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 wfe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Tfe(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 Efe(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 Dfe(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 Ofe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof P?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function kfe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ffe(e.bind(globalThis),t,Afe)}function Afe(){let e=p();if(!e)return null;try{return new URL(e).origin}catch{return null}}function jfe(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 Mfe=gfe(e=>Nfe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Mfe.handle(e.data)});async function Nfe(e){rr(e.instanceId);try{kfe(),x(e.localApiBaseUrl??null),l(e.bridgeToken??null),$X(e.syncFsBridgeEnabled??!1),m(e.extensionDelegateId??null),jfe(e.localStorageSeed??{}),Cr().catch(()=>{}),await s();let t=Fr(e.kernelPort),n=new mi(t),r=mi.createCallbacks(n),a=new Ir(e.cdpPort);await a.connect();let o=new qn(a);Y9=await lfe({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),u=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let d=Y9.sharedFs?.getWatcher();if(d){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)d.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)u.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider($n(i));let p=await Pfe({host:Y9,transport:t,browser:o,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw ar(e),e}}async function Pfe(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=xfe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Sfe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Ffe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Ffe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-Wr0NmhbD.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-ldIfAeIb.js`).then(e=>e.o),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())});
|
|
8772
|
+
`}}function Gde(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 Kde(e){let t=aX(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,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 Gde(e)}}function qde(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(mq(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(!aX(n.token))return;let a=i.get(n.id);if(a){r({type:hq,id:n.id}),a.result&&r({type:gq,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:hq,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),3e4),r({type:gq,id:n.id,...e})};Kde(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 Jde(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`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Yde(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`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function Xde(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Zde(e,t)}function Zde(e,{orchestrator:t,log:n}){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));let r=Jr(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=Jde(e),a=Yde(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function Qde(e,t,n,r){let i=new an,a=new Ide(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Xe(()=>n.emitTrayRuntimeStatus()),s=ti(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function $de(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Cpg2Em0Q.js`).then(e=>e.t);r(()=>e.getSessionCosts());let{getLickManager:i}=await import(`./lick-manager-Ct3WOtut.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??Xde,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function efe(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function tfe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Jle({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>oZ(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p9().slice(10,22),splitResult:(e,t)=>m9(e,t)})}async function nfe(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-Dzuxa2F7.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))+`
|
|
8773
|
+
`,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 rfe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CW-Xewtf.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 ife(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 Ci(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})},afe(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function afe(e){let t=g();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,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:()=>Lde()}}function ofe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-2ElXrqlr.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 sfe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BIhXOe-Q.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 cfe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.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 lfe(){return D()}async function ufe(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await Qde(t,n,r,i);if(d?rre(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new Rde(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await $de(c,e,o);d&&tfe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await nfe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;lfe()&&(h=await rfe(f,o,e.localLickWsUrl??null));let g=ife(n,f,o);d&&ofe(d,f,o),a||await efe(c),d&&sfe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await cfe(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=qde({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await dfe({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function dfe(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)}ffe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function ffe(e){let t=globalThis;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[u9]}const G9=`x-bypass-llm-proxy`;function pfe(e,t,n){return t?(r,i)=>{if(!mfe(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 mfe(e,t,n){if(gfe(e,t))return!0;let r=n?.()??null;return r?hfe(e,r,t):!1}function hfe(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 gfe(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 _fe(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 vfe=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(!yfe(e)||e.source!==`panel`)return;let t=e.payload;bfe(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;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 yfe(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 bfe(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 xfe=class extends w9{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 Sfe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new vfe({transport:t,processManager:i,createShell:(e,a)=>new xfe(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function Cfe(e){let t=new wfe(e);return t.start(),{stop:()=>t.dispose()}}var wfe=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(!Tfe(e)||e.source!==`panel`)return;let t=e.payload;if(Efe(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(Dfe(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 P(`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 P(`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(Ofe(e.type),e.requestId,new P(`EACCES`,`vfs-rpc-host has no writable backend wired`),kfe(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 P(`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 P(`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 P(`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 Tfe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Efe(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 Dfe(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 Ofe(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 kfe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof P?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function Afe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=pfe(e.bind(globalThis),t,jfe)}function jfe(){let e=p();if(!e)return null;try{return new URL(e).origin}catch{return null}}function Mfe(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 Nfe=_fe(e=>Pfe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&Nfe.handle(e.data)});async function Pfe(e){rr(e.instanceId);try{Afe(),x(e.localApiBaseUrl??null),l(e.bridgeToken??null),eZ(e.syncFsBridgeEnabled??!1),m(e.extensionDelegateId??null),Mfe(e.localStorageSeed??{}),Cr().catch(()=>{}),await s();let t=Fr(e.kernelPort),n=new mi(t),r=mi.createCallbacks(n),a=new Ir(e.cdpPort);await a.connect();let o=new qn(a);Y9=await ufe({container:{},browser:o,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),u=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=u;let d=Y9.sharedFs?.getWatcher();if(d){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)d.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)u.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:f}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=f({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,o.setTrayTargetProvider($n(i));let p=await Ffe({host:Y9,transport:t,browser:o,instanceId:e.instanceId});p&&(X9=p.stopTerminalHost,Z9=p.stopVfsRpcHost,Q9=p.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw ar(e),e}}async function Ffe(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=Sfe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=Cfe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await Ife(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function Ife(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-8cWrra0n.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-ldIfAeIb.js`).then(e=>e.o),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())});
|