sliccy 6.90.0 → 6.91.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ui/.vite/manifest.json +140 -139
- package/dist/ui/assets/{account-store-C0557OZq.js → account-store-C1yfzSh8.js} +1 -1
- package/dist/ui/assets/{account-store-PMxICYyx.js → account-store-WnXgLTc8.js} +1 -1
- package/dist/ui/assets/{adobe-DAuLlgQc.js → adobe-CI_mfh6W.js} +1 -1
- package/dist/ui/assets/{adobe-CzH6yOxV.js → adobe-CyU_4QFp.js} +1 -1
- package/dist/ui/assets/{apply-layout-X2nR3SmW.js → apply-layout-Ch4rpOGr.js} +1 -1
- package/dist/ui/assets/{apps-D0EROxlb.js → apps-pxc-GoM0.js} +1 -1
- package/dist/ui/assets/{azure-openai-DdJdskUw.js → azure-openai-Ct81BkzM.js} +1 -1
- package/dist/ui/assets/{azure-openai-BnxQgugl.js → azure-openai-HfNUqh5T.js} +1 -1
- package/dist/ui/assets/{cerebras-LeyGqFrv.js → cerebras-C0stC2m8.js} +1 -1
- package/dist/ui/assets/{cerebras-DjKGCT-u.js → cerebras-C650XqL5.js} +1 -1
- package/dist/ui/assets/{connect-surface-y5RhfeOY.js → connect-surface-BQZqnOMC.js} +1 -1
- package/dist/ui/assets/{fs-DqUrxf8W.js → fs-B4qf4l57.js} +2 -2
- package/dist/ui/assets/{fs-BICIkoMH.js → fs-Dnva5HZ3.js} +1 -1
- package/dist/ui/assets/{github-BU4BM_mA.js → github-BGwttSIP.js} +1 -1
- package/dist/ui/assets/{github-CxmTJiwD.js → github-BZFgkPO1.js} +2 -2
- package/dist/ui/assets/{github-copilot-DB7kI7G4.js → github-copilot-BxH2PYuM.js} +1 -1
- package/dist/ui/assets/{github-copilot-CjE3YS5h.js → github-copilot-Ch0RZpCi.js} +1 -1
- package/dist/ui/assets/{github-install-_pz2_TW3.js → github-install-DpekDVQj.js} +1 -1
- package/dist/ui/assets/{github-zip-Dev1qXQs.js → github-zip-0POubY9i.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-MogyAk2b.js → js-realm-worker-DrcpR5sl.js} +1 -1
- package/dist/ui/assets/{kernel-worker-DCpDkfwW.js → kernel-worker-CC5u39mz.js} +71 -71
- package/dist/ui/assets/{local-llm-Bii-oztV.js → local-llm-C1Or3Y52.js} +1 -1
- package/dist/ui/assets/{local-llm-7H47gAKU.js → local-llm-djwmLEi-.js} +1 -1
- package/dist/ui/assets/{main-B-rf7nsZ.js → main-CjaIZrJd.js} +3 -3
- package/dist/ui/assets/{mount-97E0oPUS.js → mount-BNyT2nnD.js} +1 -1
- package/dist/ui/assets/{mount-5eRulG33.js → mount-BRdDn52A.js} +2 -2
- package/dist/ui/assets/{mount-recovery-DjDqX7zc.js → mount-recovery-BsWQfSkJ.js} +1 -1
- package/dist/ui/assets/{new-session-kzjIi7tJ.js → new-session-362b6Pml.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-BeDaFO5d.js → oauth-bootstrap-C5IBUZ3l.js} +2 -2
- package/dist/ui/assets/{openai-codex-D77i7eaz.js → openai-codex-BKMbZQZc.js} +1 -1
- package/dist/ui/assets/{openai-codex-Bj4H6Y4Q.js → openai-codex-YDtg8ur-.js} +1 -1
- package/dist/ui/assets/{openrouter-DM3DwSgH.js → openrouter-C931t0hQ.js} +1 -1
- package/dist/ui/assets/{openrouter-qmIJwunN.js → openrouter-DkuBgJvP.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-xxsMaOdo.js → openrouter-oauth-CMiNl7hg.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-HQk7kVMZ.js → openrouter-oauth-D7kC0-6w.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-l6KgBriL.js → panel-rpc-handlers-Dz6tHtwK.js} +2 -2
- package/dist/ui/assets/{panelize-shell-DG3fFAS4.js → panelize-shell-Sersv_GI.js} +1 -1
- package/dist/ui/assets/{provider-BOspbE22.js → provider-DePb9O4W.js} +1 -1
- package/dist/ui/assets/{provider--weJQZjQ.js → provider-Qy7QIkOc.js} +2 -2
- package/dist/ui/assets/{provider-settings-BU08XwTy.js → provider-settings-DiEr5ZRx.js} +1 -1
- package/dist/ui/assets/{provider-settings-Vm_1bkhK.js → provider-settings-wn9tOS6g.js} +1 -1
- package/dist/ui/assets/provider-store-access-CW8iwqLX.js +1 -0
- package/dist/ui/assets/{provider-store-access-BBrYHDNA.js → provider-store-access-CjMqlHh9.js} +2 -2
- package/dist/ui/assets/{providers-eZOi3DQE.js → providers-CdbrXnHp.js} +1 -1
- package/dist/ui/assets/{providers-JkvpV0qf.js → providers-DWSKNmmF.js} +2 -2
- package/dist/ui/assets/{quick-llm-BNkmhi7C.js → quick-llm-CJjhx9Bw.js} +1 -1
- package/dist/ui/assets/{recovery-screen-B6NCKqh7.js → recovery-screen-B6XY3sMT.js} +1 -1
- package/dist/ui/assets/{redirect-uri-Zt0BHOq0.js → redirect-uri-Bo2sC4P3.js} +1 -1
- package/dist/ui/assets/{session-freezer-D0nn8NJ9.js → session-freezer-Dp9JZe-A.js} +3 -3
- package/dist/ui/assets/{setup-feature-flags-remote-CKTwOF5q.js → setup-feature-flags-remote-z12X6D4v.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-DDPe34xp.js → setup-standalone-prelude-BTj3azbf.js} +1 -1
- package/dist/ui/assets/{setup-sudo-BGA2TxYL.js → setup-sudo-CErVw53c.js} +2 -2
- package/dist/ui/assets/{skills-DouPtBm7.js → skills-BeciHeJd.js} +1 -1
- package/dist/ui/assets/slicc-version-CdTEe-7X.js +1 -0
- package/dist/ui/assets/{src-DXdqCrdV.js → src-CUFrGOpV.js} +1 -1
- package/dist/ui/assets/{store-7GNy6fws.js → store-DGOhX8_w.js} +1 -1
- package/dist/ui/assets/{store-CT9PIY7t.js → store-_EfBoYjW.js} +1 -1
- package/dist/ui/assets/{sudo-DJ1TETfV.js → sudo-C8vnwjt-.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-BmshpeMo.js → upgrade-detection-CW8nHgbA.js} +1 -1
- package/dist/ui/assets/{wc-attach-CPoS-Z-g.js → wc-attach-Dg3dkg8N.js} +2 -2
- package/dist/ui/assets/{wc-extension-CFrmWj3I.js → wc-extension-DKIN3f-l.js} +2 -2
- package/dist/ui/assets/wc-follower-B9fAW5o_.js +17 -0
- package/dist/ui/assets/wc-live-Djx7vpPK.js +8 -0
- package/dist/ui/assets/{wc-nav-CrGQ7Lmp.js → wc-nav-Bo-m8RiK.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CfUD68Hu.js → wc-onboarding-DFFKlypy.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-Br3qouFN.js → wc-placeholder-CHx_pcKq.js} +2 -2
- package/dist/ui/assets/{wc-settings-DTWW0msa.js → wc-settings-CB2nUyx1.js} +2 -2
- package/dist/ui/assets/{wc-shell-BKm-20hU.js → wc-shell-hfLGwN7O.js} +3 -3
- package/dist/ui/assets/{wc-sprinkles-BtcNcqLV.js → wc-sprinkles-yYuetahF.js} +2 -2
- package/dist/ui/assets/{wc-tray-BJ-fM1CT.js → wc-tray-osj-XVdy.js} +2 -2
- package/dist/ui/assets/wc-tray-scoops-Bv6lSzxH.js +5 -0
- package/dist/ui/assets/{wc-unit-context-C0EqsYUD.js → wc-unit-context-Da9Dpd9y.js} +1 -1
- package/dist/ui/assets/{xai-grok-Bx16eK-G.js → xai-grok-1GJSyFOo.js} +1 -1
- package/dist/ui/assets/{xai-grok-BUsy5MUy.js → xai-grok-BTxvDdNy.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +1 -1
- package/dist/ui/assets/provider-store-access-BQLowwe5.js +0 -1
- package/dist/ui/assets/slicc-version-Bq9HbVVE.js +0 -1
- package/dist/ui/assets/wc-follower-BpI8jQE9.js +0 -17
- package/dist/ui/assets/wc-live-Bdenu4Zs.js +0 -8
- package/dist/ui/assets/wc-tray-scoops-B7RY-1VN.js +0 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import"./logger-DQgFbfwx.js";import{n as i,r as a,t as o}from"./panel-rpc-BPwAqRch.js";import{a as s,t as c}from"./providers-eZOi3DQE.js";import{a as l,i as u,o as d,r as f,t as p}from"./proxied-fetch-Co-pb0x0.js";import{a as m,i as h,n as g,r as _,s as v,t as y}from"./src-CcFD5QfS.js";import{$t as b,An as x,At as S,Bt as C,Cn as w,Ct as T,D as E,Dn as D,Dt as ee,E as te,En as ne,Et as re,Fn as O,Ft as ie,Gt as ae,Ht as oe,In as se,It as ce,Jt as le,Kt as ue,L as de,Ln as k,Lt as fe,M as A,Mn as j,Mt as pe,Nn as me,Nt as he,On as ge,Ot as _e,Pn as ve,Pt as ye,Q as be,Qt as M,R as N,Rn as xe,Rt as Se,Sn as P,St as Ce,Tn as F,Tt as we,Ut as I,V as L,Vt as Te,Wt as Ee,X as De,Xt as Oe,Y as R,Yt as ke,Z as Ae,Zt as je,_n as Me,_t as Ne,an as Pe,at as Fe,bn as Ie,bt as Le,cn as Re,ct as ze,dn as Be,dt as Ve,en as He,et as Ue,fn as z,ft as We,gn as eee,gt as Ge,h as Ke,hn as qe,ht as Je,in as Ye,it as Xe,jn as Ze,jt as Qe,kn as $e,kt as et,ln as tt,lt as nt,m as rt,mn as it,mt as at,nn as tee,nt as ot,on as st,ot as ct,pn as lt,pt as ut,qt as dt,rn as ft,rt as pt,sn as nee,st as ree,tn as iee,tt as mt,un as ht,ut as gt,vn as B,vt as _t,w as vt,wn as yt,wt as bt,xn as xt,xt as aee,yn as St,yt as Ct,zt as wt}from"./account-store-PMxICYyx.js";import{t as Tt}from"./runtime-env-DadgceZk.js";import{r as Et}from"./binary-cache-bSOhqXB1.js";import{n as Dt,r as Ot,t as kt}from"./fetch-body-DDu_AU5I.js";import{a as oee,i as At,n as see,o as cee,r as lee,s as uee,t as jt}from"./api-endpoint-C00IT5T9.js";import{a as Mt,i as Nt,n as Pt,t as Ft}from"./path-utils-DNJG-zQf.js";import{a as dee}from"./models-4WTk3EBD.js";import{d as It,o as Lt}from"./claude-model-version-Csn7RPVg.js";import{t as Rt}from"./__vite-browser-external-5eBdwsFd.js";import{n as zt,t as Bt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Vt}from"./image-markers-CdcIBWOf.js";import{a as Ht,i as Ut,r as Wt}from"./tool-ui-DRnUkp2g.js";import{a as Gt,i as Kt,o as qt,r as Jt,t as fee}from"./agent-message-to-chat-ChAiEgvC.js";import{a as Yt,i as Xt,n as pee,o as Zt,r as mee,t as Qt}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as $t}from"./types-idfTVsM8.js";import{a as hee,i as en,n as tn,o as nn,r as rn,s as an}from"./mount-97E0oPUS.js";import{o as on}from"./mount-table-store-DrF_Ifaz.js";import{t as sn}from"./remote-cache-JAv9sQH_.js";import{r as cn,t as gee}from"./mount-recovery-DjDqX7zc.js";import{a as _ee,c as vee,i as ln,n as un,o as dn,r as fn,s as pn}from"./lick-urls-DcXOqXGm.js";import{C as mn,D as hn,E as gn,S as _n,_ as vn,a as yn,b as bn,d as xn,g as Sn,h as Cn,m as wn,n as Tn,o as En,r as Dn,s as On,t as kn,u as An,w as jn,y as Mn}from"./db-DSIYsBgP.js";import{a as Nn,i as Pn,n as Fn,r as In}from"./tray-runtime-config-CVoPQrT2.js";import{n as Ln,r as Rn,t as zn}from"./slicc-version-Bq9HbVVE.js";import{a as Bn,c as Vn,d as Hn,i as yee,l as Un,n as bee,o as Wn,s as xee,t as See,u as Cee}from"./lick-manager-DFmMezV-.js";import{a as wee,n as Gn,r as Kn}from"./fs-BICIkoMH.js";import{a as Tee,c as Eee,i as Dee,l as qn,n as Oee,o as V,r as kee,s as Jn}from"./cost-command-Be2VSQE-.js";import{_ as Yn,a as Xn,b as Zn,c as Qn,d as Aee,f as jee,g as Mee,h as Nee,i as Pee,l as $n,m as er,n as Fee,o as Iee,p as Lee,r as tr,s as Ree,u as zee,v as Bee,y as nr}from"./skills-DouPtBm7.js";import{n as Vee,t as Hee}from"./llm-session-id-BZyXP_j2.js";import{n as Uee,r as Wee}from"./frozen-archive-format-CLzdz05B.js";import{i as Gee,r as Kee}from"./browser-2rCVqcqy.js";import{a as rr,i as ir,n as qee,r as Jee,t as Yee}from"./telemetry-BwapcULJ.js";import{n as ar,t as or}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as sr,i as cr,r as lr,t as ur}from"./git-config-DA8M5e8O.js";import{a as dr,c as fr,i as pr,o as mr,r as hr,s as gr,t as _r}from"./script-catalog-Bt94D0RP.js";import{t as vr}from"./process-manager-unCzdHp3.js";import{A as yr,C as br,O as xr,_ as Sr,a as Cr,b as wr,c as Tr,d as Er,f as Dr,g as Or,h as kr,i as Ar,k as jr,l as Mr,m as Nr,n as Pr,o as Fr,p as Ir,r as Lr,s as Rr,t as zr,u as Br,v as Vr,x as Hr,y as Ur}from"./shared-DqziuFis.js";import{n as Wr,t as Gr}from"./esbuild-wasm-C_e51T2J.js";import{n as Kr,t as qr}from"./wasm-compiler-Ct7QZURL.js";import{_ as Xee,a as Jr,c as Yr,f as Zee,g as Xr,h as Zr,l as Qr,m as Qee,n as $ee,p as ete,r as $r,u as ei,v as ti,y as ni}from"./github-zip-Dev1qXQs.js";import{a as ri,c as ii,d as ai,f as oi,i as si,l as ci,n as li,o as ui,p as di,r as fi,s as pi,u as mi}from"./github-install-_pz2_TW3.js";import{n as hi,t as gi}from"./magick-wasm-DVJe3sB9.js";import{a as _i,c as vi,i as yi,l as bi,n as xi,o as Si,r as Ci,s as wi,t as Ti,u as Ei}from"./installer-DW4F27JY.js";import{t as Di}from"./local-llm-7H47gAKU.js";import{t as Oi}from"./client-DVC0x03n.js";import{t as ki}from"./redirect-uri-Zt0BHOq0.js";var Ai=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function ji(e,t,n){return new Promise((r,i)=>{let a=null,o=!1,s=setTimeout(()=>{o=!0,a?.(),i(Error(n))},t);a=e(e=>{clearTimeout(s),o=!0,a?.(),r(e)}),o&&a()})}const Mi=r(`cdp`);var Ni=class{ws=null;nextId=1;_superseded=!1;pending=new Ai;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,Mi.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mi.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(),Mi.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};t&&(a.params=t),n&&(a.sessionId=n),Mi.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return ji(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mi.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mi.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,Mi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Mi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}};const Pi=r(`har-recorder`);var Fi=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}`),Pi.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=>{Pi.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 Ii(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Pi.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 Pi.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)),Pi.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 Pi.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 Ii(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){Pi.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Pi.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Li=`(function() {
|
|
1
|
+
import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}from"./logger-LESFN7Hj.js";import"./logger-DQgFbfwx.js";import{n as i,r as a,t as o}from"./panel-rpc-BPwAqRch.js";import{a as s,t as c}from"./providers-CdbrXnHp.js";import{a as l,i as u,o as d,r as f,t as p}from"./proxied-fetch-Co-pb0x0.js";import{a as m,i as h,n as g,r as _,s as v,t as y}from"./src-CcFD5QfS.js";import{$t as b,An as x,At as S,Bt as C,Cn as w,Ct as T,D as E,Dn as D,Dt as ee,E as te,En as ne,Et as re,Fn as O,Ft as ie,Gt as ae,Ht as oe,In as se,It as ce,Jt as le,Kt as ue,L as de,Ln as k,Lt as fe,M as A,Mn as j,Mt as pe,Nn as me,Nt as he,On as ge,Ot as _e,Pn as ve,Pt as ye,Q as be,Qt as M,R as N,Rn as xe,Rt as Se,Sn as P,St as Ce,Tn as F,Tt as we,Ut as I,V as L,Vt as Te,Wt as Ee,X as De,Xt as Oe,Y as R,Yt as ke,Z as Ae,Zt as je,_n as Me,_t as Ne,an as Pe,at as Fe,bn as Ie,bt as Le,cn as Re,ct as ze,dn as Be,dt as Ve,en as He,et as Ue,fn as z,ft as We,gn as eee,gt as Ge,h as Ke,hn as qe,ht as Je,in as Ye,it as Xe,jn as Ze,jt as Qe,kn as $e,kt as et,ln as tt,lt as nt,m as rt,mn as it,mt as at,nn as tee,nt as ot,on as st,ot as ct,pn as lt,pt as ut,qt as dt,rn as ft,rt as pt,sn as nee,st as ree,tn as iee,tt as mt,un as ht,ut as gt,vn as B,vt as _t,w as vt,wn as yt,wt as bt,xn as xt,xt as aee,yn as St,yt as Ct,zt as wt}from"./account-store-WnXgLTc8.js";import{t as Tt}from"./runtime-env-DadgceZk.js";import{r as Et}from"./binary-cache-bSOhqXB1.js";import{n as Dt,r as Ot,t as kt}from"./fetch-body-DDu_AU5I.js";import{a as oee,i as At,n as see,o as cee,r as lee,s as uee,t as jt}from"./api-endpoint-C00IT5T9.js";import{a as Mt,i as Nt,n as Pt,t as Ft}from"./path-utils-DNJG-zQf.js";import{a as dee}from"./models-4WTk3EBD.js";import{d as It,o as Lt}from"./claude-model-version-Csn7RPVg.js";import{t as Rt}from"./__vite-browser-external-5eBdwsFd.js";import{n as zt,t as Bt}from"./mime-types-D7IV6i7k.js";import"./runtime-env-Dtj99aNH.js";import{t as Vt}from"./image-markers-CdcIBWOf.js";import{a as Ht,i as Ut,r as Wt}from"./tool-ui-DRnUkp2g.js";import{a as Gt,i as Kt,o as qt,r as Jt,t as fee}from"./agent-message-to-chat-ChAiEgvC.js";import{a as Yt,i as Xt,n as pee,o as Zt,r as mee,t as Qt}from"./backend-local-B6kc_FvN.js";import"./runtime-env-DVGQx9p3.js";import{t as $t}from"./types-idfTVsM8.js";import{a as en,i as tn,n as nn,o as rn,r as an,s as on}from"./mount-BNyT2nnD.js";import{o as sn}from"./mount-table-store-DrF_Ifaz.js";import{t as cn}from"./remote-cache-JAv9sQH_.js";import{r as ln,t as hee}from"./mount-recovery-BsWQfSkJ.js";import{a as gee,c as _ee,i as un,n as dn,o as fn,r as pn,s as mn}from"./lick-urls-DcXOqXGm.js";import{C as hn,D as gn,E as _n,S as vn,_ as yn,a as bn,b as xn,d as Sn,g as Cn,h as wn,m as Tn,n as En,o as Dn,r as On,s as kn,t as An,u as jn,w as Mn,y as Nn}from"./db-DSIYsBgP.js";import{a as Pn,i as Fn,n as In,r as Ln}from"./tray-runtime-config-CVoPQrT2.js";import{n as Rn,r as zn,t as Bn}from"./slicc-version-CdTEe-7X.js";import{a as Vn,c as Hn,d as Un,i as vee,l as Wn,n as yee,o as Gn,s as bee,t as xee,u as See}from"./lick-manager-DFmMezV-.js";import{a as Cee,n as Kn,r as qn}from"./fs-Dnva5HZ3.js";import{a as wee,c as Tee,i as Eee,l as Jn,n as Dee,o as V,r as Oee,s as Yn}from"./cost-command-Be2VSQE-.js";import{_ as Xn,a as Zn,b as Qn,c as $n,d as kee,f as Aee,g as jee,h as Mee,i as Nee,l as er,m as tr,n as Pee,o as Fee,p as Iee,r as nr,s as Lee,u as Ree,v as zee,y as rr}from"./skills-BeciHeJd.js";import{n as Bee,t as Vee}from"./llm-session-id-BZyXP_j2.js";import{n as Hee,r as Uee}from"./frozen-archive-format-CLzdz05B.js";import{i as Wee,r as Gee}from"./browser-2rCVqcqy.js";import{a as ir,i as ar,n as Kee,r as qee,t as Jee}from"./telemetry-BwapcULJ.js";import{n as or,t as sr}from"./safe-buffer-B2wnAhUx.js";import"./global-db-DJXlpNui.js";import{a as Yee,i as cr,r as lr,t as ur}from"./git-config-DA8M5e8O.js";import{a as dr,c as fr,i as pr,o as mr,r as hr,s as gr,t as _r}from"./script-catalog-Bt94D0RP.js";import{t as vr}from"./process-manager-unCzdHp3.js";import{A as yr,C as br,O as xr,_ as Sr,a as Cr,b as wr,c as Tr,d as Er,f as Dr,g as Or,h as kr,i as Ar,k as jr,l as Mr,m as Nr,n as Pr,o as Fr,p as Ir,r as Lr,s as Rr,t as zr,u as Br,v as Vr,x as Hr,y as Ur}from"./shared-DqziuFis.js";import{n as Wr,t as Gr}from"./esbuild-wasm-C_e51T2J.js";import{n as Kr,t as qr}from"./wasm-compiler-Ct7QZURL.js";import{_ as Xee,a as Jr,c as Yr,f as Zee,g as Xr,h as Zr,l as Qr,m as Qee,n as $ee,p as ete,r as $r,u as ei,v as ti,y as ni}from"./github-zip-0POubY9i.js";import{a as ri,c as ii,d as ai,f as oi,i as si,l as ci,n as li,o as ui,p as di,r as fi,s as pi,u as mi}from"./github-install-DpekDVQj.js";import{n as hi,t as gi}from"./magick-wasm-DVJe3sB9.js";import{a as _i,c as vi,i as yi,l as bi,n as xi,o as Si,r as Ci,s as wi,t as Ti,u as Ei}from"./installer-DW4F27JY.js";import{t as Di}from"./local-llm-djwmLEi-.js";import{t as Oi}from"./client-DVC0x03n.js";import{t as ki}from"./redirect-uri-Bo2sC4P3.js";var Ai=class{pending=new Map;issue(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{this.pending.delete(e),i(Error(n))},t);this.pending.set(e,{resolve:r,reject:i,timer:a})})}has(e){return this.pending.has(e)}resolve(e,t){this.take(e)?.resolve(t)}reject(e,t){this.take(e)?.reject(t)}rejectAll(e){for(let[,t]of this.pending)clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}get size(){return this.pending.size}take(e){let t=this.pending.get(e);if(t)return this.pending.delete(e),clearTimeout(t.timer),t}};function ji(e,t,n){return new Promise((r,i)=>{let a=null,o=!1,s=setTimeout(()=>{o=!0,a?.(),i(Error(n))},t);a=e(e=>{clearTimeout(s),o=!0,a?.(),r(e)}),o&&a()})}const Mi=r(`cdp`);var Ni=class{ws=null;nextId=1;_superseded=!1;pending=new Ai;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,Mi.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Mi.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(),Mi.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};t&&(a.params=t),n&&(a.sessionId=n),Mi.debug(`Send`,{method:e,id:i,sessionId:n});let o=this.pending.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.ws.send(JSON.stringify(a)),o}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return ji(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Mi.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(Mi.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;Mi.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,Mi.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Mi.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;this.pending.rejectAll(n),this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(`CDP client disconnected`)}};const Pi=r(`har-recorder`);var Fi=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}`),Pi.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=>{Pi.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 Ii(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return Pi.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 Pi.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)),Pi.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 Pi.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 Ii(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){Pi.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return Pi.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const Li=`(function() {
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
4
|
// ===== DOM Utilities =====
|
|
@@ -868,28 +868,28 @@ import{i as e,n as t,t as n}from"./rolldown-runtime-Dd_uD5pT.js";import{t as r}f
|
|
|
868
868
|
} catch(e) {
|
|
869
869
|
return { role: 'RootWebArea', name: '', description: 'Error: ' + (e.message || String(e)) };
|
|
870
870
|
}
|
|
871
|
-
})()`;function Ri(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}function tte(e){try{let t=atob(e.slice(0,48));return(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0}catch{return 0}}const zi=r(`browser-api`);function Bi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var nte=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_mainWorldContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),zi.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){zi.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this._mainWorldContextCache.set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.executionContextId;if(typeof n==`number`)for(let[e,t]of this._mainWorldContextCache)t===n&&this._mainWorldContextCache.delete(e)};handleExecutionContextsCleared=e=>{let t=e.sessionId;(typeof t!=`string`||t===this.sessionId)&&this._mainWorldContextCache.clear()};constructor(e){this.client=e??new Ni,this.localClient=this.client,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client)}getTransport(){return this.client}createHarRecorder(e,t=this.client){return new Fi(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??Bi(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this._mainWorldContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async bringToFront(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.bringToFront`,{},this.sessionId??void 0)}async wakeCaptureAndRestoreFocus(e){let t=this.getAttachedTargetId(),n=await this.findFocusedLocalPage(t).catch(()=>null);t&&await this.attachToPage(t);try{return await this.client.send(`Page.bringToFront`,{},this.sessionId),await this.client.send(`Page.captureScreenshot`,e,this.sessionId)}finally{if(n&&t)try{await this.attachToPage(n),await this.client.send(`Page.bringToFront`,{},this.sessionId),await this.attachToPage(t)}catch{}}}async findFocusedLocalPage(e){let t=await this.listPages();for(let n of t)if(!(!n.targetId||n.targetId===e)&&!n.targetId.includes(`:`))try{if(await this.attachToPage(n.targetId),await this.evaluate(`document.hasFocus()`)===!0)return n.targetId}catch{}return null}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};if(e?.quality!==void 0&&(t.quality=e.quality),e?.clip||e?.fullPage){let n=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),t=JSON.parse(e.result?.value??`{}`);n=t.w??0,r=t.h??0}catch(e){zi.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}t.clip=e?.clip?{...e.clip,scale:e.clip.scale??1}:{x:0,y:0,width:n||1280,height:r||800,scale:1}}let n;try{n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}catch(r){if(e?.foregroundFallback===!1)throw r;n=await this.wakeCaptureAndRestoreFocus(t)}let r=n.data;return e?.maxWidth&&(r=await this._applyMaxWidth(r,e.maxWidth,t)),r}finally{}}async _applyMaxWidth(e,t,n){let r=tte(e);if(!r||r<=t)return e;let i=t/r,a=n.clip;if(a)a.scale=i;else{let e=1280,t=800;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight})`,returnByValue:!0},this.sessionId),r=JSON.parse(n.result?.value??`{}`);e=r.w||1280,t=r.h||800}catch{}n.clip={x:0,y:0,width:e,height:t,scale:i}}n.captureBeyondViewport=!0;try{return(await this.client.send(`Page.captureScreenshot`,n,this.sessionId)).data}catch(t){return zi.warn(`maxWidth re-capture failed, returning original`,t),e}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e,t=0){await this.ensureConnected(),this.ensureAttached();let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);let r=n.x+n.width/2,i=n.y+n.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async insertText(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Input.insertText`,{text:e},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(Li,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=Hi(e);try{let e=(await this.client.send(`Accessibility.getFullAXTree`,{},this.sessionId)).nodes;Array.isArray(e)&&Vi(t,rte(e))}catch{}return t}async clickByBackendNodeId(e,t=0){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!n?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let r=(await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() {
|
|
871
|
+
})()`;function Ri(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}function zi(e){try{let t=atob(e.slice(0,48));return(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0}catch{return 0}}const Bi=r(`browser-api`);function Vi(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:`ws://localhost:5710/cdp`}var tte=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_mainWorldContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;handleJavaScriptDialogOpening=e=>{this.dismissJavaScriptDialog(e)};async dismissJavaScriptDialog(e){let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),Bi.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){Bi.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}handleExecutionContextCreated=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this._mainWorldContextCache.set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.executionContextId;if(typeof n==`number`)for(let[e,t]of this._mainWorldContextCache)t===n&&this._mainWorldContextCache.delete(e)};handleExecutionContextsCleared=e=>{let t=e.sessionId;(typeof t!=`string`||t===this.sessionId)&&this._mainWorldContextCache.clear()};constructor(e){this.client=e??new Ni,this.localClient=this.client,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client)}getTransport(){return this.client}createHarRecorder(e,t=this.client){return new Fi(t,e)}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??Vi(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this._mainWorldContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async bringToFront(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.bringToFront`,{},this.sessionId??void 0)}async wakeCaptureAndRestoreFocus(e){let t=this.getAttachedTargetId(),n=await this.findFocusedLocalPage(t).catch(()=>null);t&&await this.attachToPage(t);try{return await this.client.send(`Page.bringToFront`,{},this.sessionId),await this.client.send(`Page.captureScreenshot`,e,this.sessionId)}finally{if(n&&t)try{await this.attachToPage(n),await this.client.send(`Page.bringToFront`,{},this.sessionId),await this.attachToPage(t)}catch{}}}async findFocusedLocalPage(e){let t=await this.listPages();for(let n of t)if(!(!n.targetId||n.targetId===e)&&!n.targetId.includes(`:`))try{if(await this.attachToPage(n.targetId),await this.evaluate(`document.hasFocus()`)===!0)return n.targetId}catch{}return null}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};if(e?.quality!==void 0&&(t.quality=e.quality),e?.clip||e?.fullPage){let n=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),t=JSON.parse(e.result?.value??`{}`);n=t.w??0,r=t.h??0}catch(e){Bi.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}t.clip=e?.clip?{...e.clip,scale:e.clip.scale??1}:{x:0,y:0,width:n||1280,height:r||800,scale:1}}let n;try{n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}catch(r){if(e?.foregroundFallback===!1)throw r;n=await this.wakeCaptureAndRestoreFocus(t)}let r=n.data;return e?.maxWidth&&(r=await this._applyMaxWidth(r,e.maxWidth,t)),r}finally{}}async _applyMaxWidth(e,t,n){let r=zi(e);if(!r||r<=t)return e;let i=t/r,a=n.clip;if(a)a.scale=i;else{let e=1280,t=800;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight})`,returnByValue:!0},this.sessionId),r=JSON.parse(n.result?.value??`{}`);e=r.w||1280,t=r.h||800}catch{}n.clip={x:0,y:0,width:e,height:t,scale:i}}n.captureBeyondViewport=!0;try{return(await this.client.send(`Page.captureScreenshot`,n,this.sessionId)).data}catch(t){return Bi.warn(`maxWidth re-capture failed, returning original`,t),e}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e,t=0){await this.ensureConnected(),this.ensureAttached();let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);let r=n.x+n.width/2,i=n.y+n.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async insertText(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Input.insertText`,{text:e},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(Li,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=Ui(e);try{let e=(await this.client.send(`Accessibility.getFullAXTree`,{},this.sessionId)).nodes;Array.isArray(e)&&Hi(t,nte(e))}catch{}return t}async clickByBackendNodeId(e,t=0){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!n?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let r=(await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() {
|
|
872
872
|
this.scrollIntoView({ block: 'center', inline: 'center' });
|
|
873
873
|
const r = this.getBoundingClientRect();
|
|
874
874
|
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
875
|
-
}`,returnByValue:!0},this.sessionId)).result?.value;if(!r||r.width===0||r.height===0){await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() { this.click(); }`},this.sessionId);return}let i=r.x+r.width/2,a=r.y+r.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async dblclickByBackendNodeId(e,t=`left`,n=0){await this.ensureConnected(),this.ensureAttached();let{x:r,y:i}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId)}async hoverByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached();let{x:t,y:n}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n},this.sessionId)}async selectByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0},this.sessionId)}async setCheckedByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);return(await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0},this.sessionId)).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1},this.sessionId)}async getFrameTree(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let e=(await this.client.send(`Page.getFrameTree`,{},this.sessionId)).frameTree,t=[],n=e=>{if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let t of e.childFrames)n(t)};return n(e),t}async evaluateInFrame(e,t,n){await this.ensureConnected(),this.ensureAttached();let r=e=>{let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)},i=async()=>{let t=(await this.client.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`},this.sessionId)).executionContextId;return this._frameContextCache.set(e,t),t},a=async()=>{if(n?.world!==`main`)return this._frameContextCache.get(e)??i();await this.client.send(`Runtime.enable`,{},this.sessionId);let t=this._mainWorldContextCache.get(e);if(t===void 0&&(await this.client.send(`Runtime.disable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId),t=this._mainWorldContextCache.get(e)),t===void 0)throw Error(`Failed to find main world execution context for frame ${e}`);return t},o=()=>{n?.world===`main`?this._mainWorldContextCache.delete(e):this._frameContextCache.delete(e)},s;try{s=await a()}catch(t){let r=n?.world===`main`?`main world`:`isolated world`;throw Error(`Failed to resolve ${r} for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}n?.world!==`main`&&await this.client.send(`Runtime.enable`,{},this.sessionId);let c={expression:t,contextId:s,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},l;try{l=await this.client.send(`Runtime.evaluate`,c,this.sessionId)}catch(e){if(r(e))o(),s=await a(),l=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId);else throw e}let u=l.exceptionDetails;if(u){let t=u.exception?.description??u.text;if(r(Error(t))){o(),s=await a();let t=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId),n=t.exceptionDetails;if(n){let t=n.exception?.description??n.text;throw Error(`Evaluation in frame ${e} failed: ${t}`)}return t.result.value}throw o(),Error(`Evaluation in frame ${e} failed: ${t}`)}return l.result.value}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();await this.ensureConnected(),this.ensureAttached();let t=await this.evaluateInFrame(e,Li,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:
|
|
875
|
+
}`,returnByValue:!0},this.sessionId)).result?.value;if(!r||r.width===0||r.height===0){await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() { this.click(); }`},this.sessionId);return}let i=r.x+r.width/2,a=r.y+r.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async dblclickByBackendNodeId(e,t=`left`,n=0){await this.ensureConnected(),this.ensureAttached();let{x:r,y:i}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId)}async hoverByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached();let{x:t,y:n}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n},this.sessionId)}async selectByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0},this.sessionId)}async setCheckedByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);return(await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0},this.sessionId)).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1},this.sessionId)}async getFrameTree(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let e=(await this.client.send(`Page.getFrameTree`,{},this.sessionId)).frameTree,t=[],n=e=>{if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let t of e.childFrames)n(t)};return n(e),t}async evaluateInFrame(e,t,n){await this.ensureConnected(),this.ensureAttached();let r=e=>{let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)},i=async()=>{let t=(await this.client.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`},this.sessionId)).executionContextId;return this._frameContextCache.set(e,t),t},a=async()=>{if(n?.world!==`main`)return this._frameContextCache.get(e)??i();await this.client.send(`Runtime.enable`,{},this.sessionId);let t=this._mainWorldContextCache.get(e);if(t===void 0&&(await this.client.send(`Runtime.disable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId),t=this._mainWorldContextCache.get(e)),t===void 0)throw Error(`Failed to find main world execution context for frame ${e}`);return t},o=()=>{n?.world===`main`?this._mainWorldContextCache.delete(e):this._frameContextCache.delete(e)},s;try{s=await a()}catch(t){let r=n?.world===`main`?`main world`:`isolated world`;throw Error(`Failed to resolve ${r} for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}n?.world!==`main`&&await this.client.send(`Runtime.enable`,{},this.sessionId);let c={expression:t,contextId:s,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},l;try{l=await this.client.send(`Runtime.evaluate`,c,this.sessionId)}catch(e){if(r(e))o(),s=await a(),l=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId);else throw e}let u=l.exceptionDetails;if(u){let t=u.exception?.description??u.text;if(r(Error(t))){o(),s=await a();let t=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId),n=t.exceptionDetails;if(n){let t=n.exception?.description??n.text;throw Error(`Evaluation in frame ${e} failed: ${t}`)}return t.result.value}throw o(),Error(`Evaluation in frame ${e} failed: ${t}`)}return l.result.value}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();await this.ensureConnected(),this.ensureAttached();let t=await this.evaluateInFrame(e,Li,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:Ui(t)}async sendCDP(e,t={}){return await this.ensureConnected(),this.ensureAttached(),await this.client.send(e,t,this.sessionId)}async resolveNodeObjectId(e){await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);return t.objectId}async resolveNodeCenter(e){let t=await this.resolveNodeObjectId(e),n=(await this.client.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:`function() {
|
|
876
876
|
this.scrollIntoView({ block: 'center', inline: 'center' });
|
|
877
877
|
const r = this.getBoundingClientRect();
|
|
878
878
|
return { x: r.x, y: r.y, width: r.width, height: r.height };
|
|
879
|
-
}`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??Bi(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0))}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}addExecutionContextListeners(e){e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeExecutionContextListeners(e){e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.removeExecutionContextListeners(this.client),this.client=e,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function rte(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function Vi(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)Vi(n,t)}function Hi(e){let t={role:Ri(e.role,`unknown`),name:Ri(e.name)},n=Ri(e.value);n!==``&&(t.value=n);let r=Ri(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Hi(e)).filter(e=>e.role!==`unknown`)),t}const Ui=r(`panel-rpc-cdp`);var ite=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=new Map;pendingOnce=new Set;key;_state=`connected`;pushRegistered=!1;constructor(e,t,n,r=3e4){this.getPanelRpc=e,this.runtimeId=t,this.localTargetId=n,this.timeoutMs=r,this.key=`${t}:${n}`}get state(){return this._state}async connect(){}disconnect(){this._state=`disconnected`;for(let e of this.pendingOnce)clearTimeout(e.timer),e.reject(Error(`Transport disconnected`));this.pendingOnce.clear();let e=this.getPanelRpc();e&&(this.pushRegistered&&=(e.unregisterPushTarget(this.key),!1),e.call(`remote-cdp-detach`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId}).catch(e=>{Ui.error(`remote-cdp detach failed (page-side session may leak)`,{key:this.key,error:e instanceof Error?e.message:String(e)})})),this.eventListeners.clear()}async send(e,t,n,r){if(this._state===`disconnected`)throw Error(`Transport disconnected`);let i=this.getPanelRpc();if(!i)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let a=r??this.timeoutMs,s=Math.max(a,o)+5e3;return i.call(`remote-cdp-send`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,method:e,params:t,sessionId:n,timeout:a},{timeoutMs:s})}on(e,t){let n=this.eventListeners.get(e),r=!n||n.size===0;n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),r&&this.subscribe(e)}off(e,t){let n=this.eventListeners.get(e);n&&(n.delete(t),n.size===0&&(this.eventListeners.delete(e),this.unsubscribe(e)))}once(e,t){return new Promise((n,r)=>{let i=t??this.timeoutMs,a={reject:r,timer:void 0},o=()=>{clearTimeout(a.timer),this.pendingOnce.delete(a),this.off(e,s)};a.timer=setTimeout(()=>{o(),r(Error(`Remote CDP event timed out: ${e}`))},i);let s=e=>{o(),n(e)};this.pendingOnce.add(a),this.on(e,s)})}handleEvent(e,t){let n=this.eventListeners.get(e);if(n)for(let e of[...n])e(t)}ensurePushRegistered(e){this.pushRegistered||=(e.registerPushTarget(this.key,e=>this.handleEvent(e.method,e.params??{})),!0)}subscribe(e){let t=this.getPanelRpc();if(!t){Ui.error(`remote-cdp subscribe skipped: no panel-RPC client`,{key:this.key,event:e});return}this.ensurePushRegistered(t),t.call(`remote-cdp-subscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ui.error(`remote-cdp subscribe failed; events for this transport will not arrive`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}unsubscribe(e){let t=this.getPanelRpc();t&&t.call(`remote-cdp-unsubscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Ui.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function ate(e){let t=new Map,n=(e,t)=>`${e}:${t}`;return{getTargets(){return[]},createRemoteTransport(r,i){let a=n(r,i),o=t.get(a);return o||(o=new ite(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}const Wi=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`off`,userToggleable:!0})]);new Map(Wi.map(e=>[e.id,e]));const Gi=new Set([`1`,`on`,`true`]);let Ki=`standalone`,qi={},Ji={};function Yi(e,t={},n=Xi()){let r={};for(let i of Wi){let a=n[i.id];if(typeof a==`string`&&na(i,e)){r[i.id]=a;continue}let o=Ji[i.id];if(typeof o==`string`&&na(i,e)){r[i.id]=o;continue}let s=t[i.id];r[i.id]=typeof s==`string`?s:ta(i,e)}return r}function Xi(){try{let e=ia()?.getItem(`slicc_feature_flags`);return e?ra(JSON.parse(e)):{}}catch{return{}}}function Zi(e,t={}){Ki=e,qi=ra(t),Ji={}}function Qi(e){return Yi(Ki,qi)[e]}function $i(e){return typeof e==`string`&&Gi.has(e.trim().toLowerCase())}function ea(e){return $i(Qi(e))}function ta(e,t){return e.floatDefaults?.[t]??e.defaultValue}function na(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function ra(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=e,n={};for(let e of Wi){let r=t[e.id];typeof r==`string`&&(n[e.id]=r)}return n}function ia(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function aa(e){return`slicc_feature_flags_remote:${e}`}function oa(e,t){Zi(e,ca(sa(t),e)??{})}function sa(e){if(e!==void 0)return e;try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function ca(e,t){try{let n=e?.getItem(aa(t));return n?la(JSON.parse(n)):null}catch{return null}}function la(e){return!ua(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const da=r(`stale-asset`),fa=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function pa(e){return fa.test(e)}let ma=null;function ha(e){if(!e){ma=null;return}ma=e}function ga(e=!1){if(!ma||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:ma,replayTurn:e})}finally{t.close()}}function _a(e){pa(e instanceof Error?e.message:String(e))&&ga()}function va(e,t){return!e||e===t?!1:(da.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),ga(),!0)}var ya=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ai;unsubscribe=null;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`}disconnect(){this.unsubscribe?.(),this.unsubscribe=null,this.pendingCommands.rejectAll(`${this.label} disconnected`),this.listeners.clear(),this._state=`disconnected`}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n),o=this.pendingCommands.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.opts.sendEnvelope(a).catch(e=>{this.pendingCommands.reject(i,Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`))}),o}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return ji(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleIncoming(e){let t=this.opts.parseResponse(e);if(t){this.handleResponse(t);return}let n=this.opts.parseEvent(e);n&&this.handleEvent(n)}handleResponse(e){if(!this.pendingCommands.has(e.id)){this.opts.onUnknownResponseId?.(e.id);return}e.error?this.pendingCommands.reject(e.id,Error(e.error)):this.pendingCommands.resolve(e.id,e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function ba(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function xa(e){let t=ba(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Sa=class extends ya{constructor(e){let t=ba(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};function Ca(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const wa=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function Ta(e){return wa.test(e)}function Ea(e,t){return`(${e} && ${t})`}function Da(e,t){return`(${e} || ${t})`}function Oa(e){return`!(${e})`}function ka(e){return`Array.isArray(${e})`}function Aa(e){return`typeof ${e} === "bigint"`}function ja(e){return`typeof ${e} === "boolean"`}function Ma(e){return`Number.isInteger(${e})`}function Na(e){return`${e} === null`}function Pa(e){return`Number.isFinite(${e})`}function Fa(e){return Ea(Ia(e),Oa(ka(e)))}function Ia(e){return`typeof ${e} === "object" && ${e} !== null`}function La(e){return`typeof ${e} === "string"`}function Ra(e){return`typeof ${e} === "symbol"`}function za(e){return`${e} === undefined`}function Ba(e){return`typeof ${e} === "function"`}function Va(e){return`Guard.IsConstructor(${e})`}function Ha(e,t){return`${e} === ${t}`}function Ua(e,t){return`${e} > ${t}`}function Wa(e,t){return`${e} < ${t}`}function Ga(e,t){return`${e} <= ${t}`}function Ka(e,t){return`${e} >= ${t}`}function qa(e,t){return`Guard.IsMinLength(${e}, ${t})`}function Ja(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Ya(e,t,n,r){return B(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function Xa(e){return`Object.entries(${e})`}function Za(e){return`Object.getOwnPropertyNames(${e})`}function Qa(e,t){return B(t,`"__proto__"`)||B(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function $a(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function eo(e){return`[${e.join(`, `)}]`}function to(e,t){return`((${e.join(`, `)}) => ${t})`}function no(e,t){return`${e}(${t.join(`, `)})`}function ro(e,t){return`new ${e}(${t.join(`, `)})`}function H(e,t){return`${e}${Ta(t)?`.${t}`:`[${U(t)}]`}`}function U(e){return j(e)?JSON.stringify(e):`${e}`}function io(e,t,n){return`(${e} ? ${t} : ${n})`}function ao(e){return`{ ${e.join(`; `)}; }`}function oo(e,t){return`const ${e} = ${t}`}function so(e,t){return`if(${e}) { ${t} }`}function co(e){return`return ${e}`}function lo(e){return B(e.length,0)?`true`:e.reduce((e,t)=>Ea(e,t))}function uo(e){return B(e.length,0)?`false`:e.reduce((e,t)=>Da(e,t))}function fo(e){return`++${e}`}function po(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var mo=xe;function ho(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let go;function _o(){try{return yo(`null`)(),!0}catch{return!1}}function vo(){return ve(go)&&(go=_o()),go&&st().useAcceleration}function yo(...e){return new globalThis.Function(...e)}function bo(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let xo=bo;function So(){return xo}const Co=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],wo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function To(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!wo.some(t=>t.test(e.errorMessage))&&Co.some(t=>t.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function Eo(e){return z(e,`~refine`)&<(e[`~refine`])&&ht(e[`~refine`],0,e=>x(e)&&z(e,`check`)&&z(e,`error`)&&St(e.check)&&St(e.error))}function Do(e){return x(e)&&!lt(e)}function Oo(e){return qe(e)}function ko(e){return Do(e)||Oo(e)}function Ao(e){return z(e,`additionalItems`)&&ko(e.additionalItems)}function jo(e){return z(e,`additionalProperties`)&&ko(e.additionalProperties)}function Mo(e){return z(e,`allOf`)&<(e.allOf)&&e.allOf.every(e=>ko(e))}function No(e){return z(e,`$anchor`)&&j(e.$anchor)}function Po(e){return z(e,`anyOf`)&<(e.anyOf)&&e.anyOf.every(e=>ko(e))}function Fo(e){return z(e,`const`)}function Io(e){return z(e,`contains`)&&ko(e.contains)}function Lo(e){return z(e,`default`)}function Ro(e){return z(e,`dependencies`)&&x(e.dependencies)&&Object.values(e.dependencies).every(e=>ko(e)||lt(e)&&e.every(e=>j(e)))}function zo(e){return z(e,`dependentRequired`)&&x(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>lt(e)&&e.every(e=>j(e)))}function Bo(e){return z(e,`dependentSchemas`)&&x(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>ko(e))}function Vo(e){return z(e,`$dynamicAnchor`)&&j(e.$dynamicAnchor)}function Ho(e){return z(e,`$dynamicRef`)&&j(e.$dynamicRef)}function Uo(e){return z(e,`else`)&&ko(e.else)}function Wo(e){return z(e,`enum`)&<(e.enum)}function Go(e){return z(e,`exclusiveMaximum`)&&($e(e.exclusiveMaximum)||it(e.exclusiveMaximum))}function Ko(e){return z(e,`exclusiveMinimum`)&&($e(e.exclusiveMinimum)||it(e.exclusiveMinimum))}function qo(e){return z(e,`format`)&&j(e.format)}function Jo(e){return z(e,`$id`)&&j(e.$id)}function Yo(e){return z(e,`if`)&&ko(e.if)}function Xo(e){return z(e,`items`)&&(ko(e.items)||lt(e.items)&&e.items.every(e=>ko(e)))}function Zo(e){return Xo(e)&<(e.items)}function Qo(e){return z(e,`maximum`)&&($e(e.maximum)||it(e.maximum))}function $o(e){return z(e,`maxContains`)&&$e(e.maxContains)}function es(e){return z(e,`maxItems`)&&$e(e.maxItems)}function ts(e){return z(e,`maxLength`)&&$e(e.maxLength)}function ns(e){return z(e,`maxProperties`)&&$e(e.maxProperties)}function rs(e){return z(e,`minimum`)&&($e(e.minimum)||it(e.minimum))}function is(e){return z(e,`minContains`)&&$e(e.minContains)}function as(e){return z(e,`minItems`)&&$e(e.minItems)}function os(e){return z(e,`minLength`)&&$e(e.minLength)}function ss(e){return z(e,`minProperties`)&&$e(e.minProperties)}function cs(e){return z(e,`multipleOf`)&&($e(e.multipleOf)||it(e.multipleOf))}function ls(e){return z(e,`not`)&&ko(e.not)}function us(e){return z(e,`oneOf`)&<(e.oneOf)&&e.oneOf.every(e=>ko(e))}function ds(e){return z(e,`pattern`)&&(j(e.pattern)||e.pattern instanceof RegExp)}function fs(e){return z(e,`patternProperties`)&&x(e.patternProperties)&&Object.values(e.patternProperties).every(e=>ko(e))}function ps(e){return z(e,`prefixItems`)&<(e.prefixItems)&&e.prefixItems.every(e=>ko(e))}function ms(e){return z(e,`properties`)&&x(e.properties)&&Object.values(e.properties).every(e=>ko(e))}function hs(e){return z(e,`propertyNames`)&&(x(e.propertyNames)||ko(e.propertyNames))}function ote(e){return z(e,`$recursiveAnchor`)&&qe(e.$recursiveAnchor)}function gs(e){return ote(e)&&B(e.$recursiveAnchor,!0)}function _s(e){return z(e,`$recursiveRef`)&&j(e.$recursiveRef)}function vs(e){return z(e,`$ref`)&&j(e.$ref)}function ys(e){return z(e,`required`)&<(e.required)&&e.required.every(e=>j(e))}function bs(e){return z(e,`then`)&&ko(e.then)}function xs(e){return z(e,`type`)&&(j(e.type)||lt(e.type)&&e.type.every(e=>j(e)))}function Ss(e){return z(e,`uniqueItems`)&&qe(e.uniqueItems)}function Cs(e){return z(e,`unevaluatedItems`)&&ko(e.unevaluatedItems)}function ws(e){return z(e,`unevaluatedProperties`)&&ko(e.unevaluatedProperties)}function ste(e){return Cs(e)||ws(e)||k(e).some(t=>Ts(e[t]))}function cte(e){return e.some(e=>Ts(e))}function Ts(e){return lt(e)?cte(e):x(e)?ste(e):!1}function lte(e,t){return Ts(t)||k(e).some(t=>Ts(e[t]))}var ute=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return no(H(`context`,`Push`),[])}Pop(){return no(H(`context`,`Pop`),[])}AddIndex(e){return no(H(`context`,`AddIndex`),[e])}AddKey(e){return no(H(`context`,`AddKey`),[e])}Merge(e){return no(H(`context`,`Merge`),[e])}},Es=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},Ds=class extends Es{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Os=class extends Ds{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const ks={identifier:`External`,variables:[]};function As(e){let t=`External[${ks.variables.length}]`;return ks.variables.push(e),t}function js(){ks.variables=[]}function Ms(){return{...ks}}function Ns(e,t,n,r){return Ya(As(n[`~refine`].map(e=>e)),U(0),[`refinement`,`_`],no(H(`refinement`,`check`),[r]))}function Ps(e,t,n,r){return ht(n[`~refine`],0,(e,t)=>e.check(r))}function Fs(e,t,n,r,i,a){return Be(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let Is=0;function Ls(){return`var_${Is++}`}function Rs(e){return Xo(e)&<(e.items)}function zs(e,t,n,r){if(!Rs(n))return U(!0);let[i,a]=[Ls(),Ls()],o=mf(e,t,n.additionalItems,i),s=Wa(a,U(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?Da(s,Ea(o,c)):Da(s,o);return no(H(r,`every`),[to([i,a],l)])}function Bs(e,t,n,r){return!Rs(n)||r.every((r,i)=>yt(i,n.items.length)||gf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function Vs(e,t,n,r,i,a){return!Rs(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return yt(o,i.items.length)||vf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function Hs(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function Us(e){let t=[];return fs(e)&&t.push(...k(e.patternProperties)),ms(e)&&t.push(...k(e.properties).map(Hs)),B(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function Ws(e,t,n){return ys(t)&&ms(t)&&!fs(t)&&B(t.additionalProperties,!1)&&B(k(t.properties).length,t.required.length)}function Gs(e,t,n){return Ha(H(no(H(`Object`,`getOwnPropertyNames`),[n]),`length`),U(t.required.length))}function Ks(e,t,n,r){let[i,a]=[Ls(),Ls()],o=As(new RegExp(Us(n))),s=mf(e,t,n.additionalProperties,`${r}[${i}]`),c=no(H(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?Da(c,Ea(s,l)):Da(c,s);return Ya(Za(r),U(0),[i,a],u)}function qs(e,t,n,r){return Ws(t,n,r)?Gs(t,n,r):Ks(e,t,n,r)}function Js(e,t,n,r){let i=new RegExp(Us(n));return ht(k(r),0,(a,o)=>i.test(a)||gf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Ys(e,t,n,r,i,a){let o=new RegExp(Us(i)),s=[];return Be(k(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Os,p=o.test(c)||vf(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function Xs(e,t,n,r,i){let a=oo(`results`,`[]`),o=n.map((e,t)=>oo(`context_${t}`,ro(`CheckContext`,[]))),s=n.map((n,i)=>oo(`condition_${i}`,no(to([`context`],hf(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>so(`condition_${t}`,no(H(`results`,`push`),[`context_${t}`]))),l=co(Ea(i,t.Merge(`results`)));return no(to([],ao([a,...o,...s,...c,l])),[])}function Zs(e,t,n,r){return Xs(e,t,n.allOf,r,Ha(H(`results`,`length`),U(n.allOf.length)))}function Qs(e,t,n,r){return lo(n.allOf.map(n=>hf(e,t,n,r)))}function $s(e,t,n,r){return t.UseUnevaluated()?Zs(e,t,n,r):Qs(e,t,n,r)}function ec(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return B(i.length,n.allOf.length)&&t.Merge(i)}function tc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Os,u=yf(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=B(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function nc(e,t,n,r){return Xs(e,t,n.anyOf,r,Ua(H(`results`,`length`),U(0)))}function rc(e,t,n,r){return uo(n.anyOf.map(n=>hf(e,t,n,r)))}function ic(e,t,n,r){return t.UseUnevaluated()?nc(e,t,n,r):rc(e,t,n,r)}function ac(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return xt(i.length,0)&&t.Merge(i)}function oc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Os,l=yf(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=xt(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function sc(e,t,n,r){return U(!!n)}function cc(e,t,n,r){return n}function lc(e,t,n,r,i,a){return cc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function uc(e,t,n,r){return se(n.const)?Ha(r,U(n.const)):$a(r,As(n.const))}function dc(e,t,n,r){return se(n.const)?B(r,n.const):Me(r,n.const)}function fc(e,t,n,r,i,a){return dc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function pc(e){return!(is(e)&&B(e.minContains,0))}function mc(e,t,n,r){if(!pc(n))return U(!0);let i=Ls();return Ea(Oa(Ha(H(r,`length`),U(0))),no(H(r,`some`),[to([i],hf(e,t,n.contains,i))]))}function hc(e,t,n,r){return!pc(n)||!B(r.length,0)&&r.some(r=>_f(e,t,n.contains,r))}function gc(e,t,n,r,i,a){return hc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function _c(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependencies).map(([n,i])=>{let a=Oa(Qa(r,U(n))),o=hf(e,t,i,r);return Da(a,lt(i)?(e=>lo(e.map(e=>Qa(r,U(e)))))(i):o)})))}function vc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependencies),0,([n,i])=>!z(r,n)||(lt(i)?i.every(e=>z(r,e)):_f(e,t,i,r)));return i||a}function yc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!z(a,i)||(lt(o)?o.every(e=>z(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):yf(e,t,s,r,o,a))});return o||s}function bc(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependentRequired).map(([e,t])=>Da(Oa(Qa(r,U(e))),lo(t.map(e=>Qa(r,U(e))))))))}function xc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependentRequired),0,([e,t])=>!z(r,e)||t.every(e=>z(r,e)));return i||a}function Sc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependentRequired),0,([e,i])=>!z(a,e)||Be(i,0,o=>z(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Cc(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependentSchemas).map(([n,i])=>Da(Oa(Qa(r,U(n))),hf(e,t,i,r)))))}function wc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependentSchemas),0,([n,i])=>!z(r,n)||_f(e,t,i,r));return i||a}function Tc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!z(a,i)||yf(e,t,s,r,o,a)});return o||s}function Ec(e,t,n,r){return kf(e,t,e.DynamicRef(n)??!1,r)}function Dc(e,t,n,r){let i=e.DynamicRef(n)??!1;return ko(i)&&_f(e,t,i,r)}function Oc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return ko(o)&&yf(e,t,`#`,r,o,a)}function kc(e,t,n,r){return uo(n.enum.map(e=>se(e)?Ha(r,U(e)):$a(r,As(e))))}function Ac(e,t,n,r){return n.enum.some(e=>se(e)?B(r,e):Me(r,e))}function jc(e,t,n,r,i,a){return Ac(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function Mc(e,t,n,r){return Wa(r,U(n.exclusiveMaximum))}function Nc(e,t,n,r){return yt(r,n.exclusiveMaximum)}function Pc(e,t,n,r,i,a){return Nc(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function Fc(e,t,n,r){return Ua(r,U(n.exclusiveMinimum))}function Ic(e,t,n,r){return xt(r,n.exclusiveMinimum)}function Lc(e,t,n,r,i,a){return Ic(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const Rc=[0,31,28,31,30,31,30,31,31,30,31,30,31],zc=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Bc(e){return e%4==0&&(e%100!=0||e%400==0)}function Vc(e){let t=zc.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&Bc(n)?29:Rc[r])}const Hc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function Uc(e,t=!0){let n=Hc.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function Wc(e,t=!0){let n=e.split(/T/i);return n.length===2&&Vc(n[0])&&Uc(n[1],t)}const Gc=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Kc(e){return Gc.test(e)}const qc=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function Jc(e){return qc.test(e)}function Yc(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function Xc(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n<a;n++){let r=e.charCodeAt(n);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)oe();else throw Error(`Invalid punycode: bad digit character`);r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n<a)break;s*=36-a,c+=36}let l=t.length+1;i=Yc(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function Zc(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function Qc(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function $c(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function el(e){return Zc(e)||Qc(e)||$c(e)}const tl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),nl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function rl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function il(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function al(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function ol(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function sl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function cl(e){return e>=1632&&e<=1641}function ll(e){return e>=1776&&e<=1785}function ul(e){return nl.has(e)}function dl(e){if(e.length===0)return oe();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||el(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(tl.has(n))return!1;(al(n)||ol(n)||sl(n))&&(r=!0),cl(n)&&(i=!0),ll(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!rl(s))return!1;break;case 1523:case 1524:if(o===void 0||!il(o))return!1;break;case 8204:if(o===void 0||o<128&&!ul(o))return!1;break;case 8205:if(o===void 0||!ul(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function fl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function pl(e){return e.toLowerCase().startsWith(`xn--`)}function ml(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=Xc(t);return n?dl(n):!1}catch{return!1}}function hl(e){return e.length===0||e.length>63?!1:pl(e)?ml(e):dl(e)}function gl(e){return e.length===0||e.length>63?!1:pl(e)?ml(e):fl(e)}function _l(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!gl(t))return!1;return!0}const vl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function yl(e){return vl.test(e)}function bl(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!hl(e))return!1;return!0}function xl(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Sl(e){return xl(e,0,e.length)}function Cl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function wl(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&Cl(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!xl(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Tl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function El(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Tl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Tl(e)}function Dl(e){try{return new URL(e),!0}catch{return!1}}const Ol=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function kl(e){return Ol.test(e)}const Al=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function jl(e){return Al.test(e)}function Ml(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const Nl=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Pl(e){return Nl.test(e)}const Fl=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function Il(e){return Fl.test(e)}const Ll=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function Rl(e){return Ll.test(e)}function zl(e){return e>=97&&e<=122||e>=65&&e<=90}function Bl(e){return zl(e)||e>=48&&e<=57}function Vl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Hl(e){return Bl(e)||e===43||e===45||e===46}function Ul(e){return Bl(e)||e===45||e===46||e===95||e===126}function Wl(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function Gl(e){return Ul(e)||Wl(e)||e===58||e===64}function Kl(e){let t=e.length;if(t===0||!zl(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!Hl(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!Vl(e.charCodeAt(t+1))||!Vl(e.charCodeAt(t+2)))return!1;t+=2}else if(!Ul(n)&&!Wl(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!Ul(t)&&!Wl(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!Vl(e.charCodeAt(n+1))||!Vl(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Gl(r)||r===47||r===63||r===35))return!1;n++}return!0}const ql=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function Jl(e){return ql.test(e)}const Yl=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Xl(e){return Yl.test(e)}const Zl=new Map;function Ql(){Zl.clear()}function $l(){return[...Zl.entries()]}function eu(e,t){Zl.set(e,t)}function tu(e){return Zl.has(e)}function nu(e){return Zl.get(e)}function ru(e,t){return Zl.get(e)?.(t)??!0}function iu(){Ql(),Zl.set(`date-time`,Wc),Zl.set(`date`,Vc),Zl.set(`duration`,Kc),Zl.set(`email`,Jc),Zl.set(`hostname`,_l),Zl.set(`idn-email`,yl),Zl.set(`idn-hostname`,bl),Zl.set(`ipv4`,Sl),Zl.set(`ipv6`,wl),Zl.set(`iri-reference`,El),Zl.set(`iri`,Dl),Zl.set(`json-pointer-uri-fragment`,kl),Zl.set(`json-pointer`,jl),Zl.set(`regex`,Ml),Zl.set(`relative-json-pointer`,Pl),Zl.set(`time`,Uc),Zl.set(`uri-reference`,Il),Zl.set(`uri-template`,Rl),Zl.set(`uri`,Kl),Zl.set(`url`,Jl),Zl.set(`uuid`,Xl)}iu();var au=t({Clear:()=>Ql,Entries:()=>$l,Get:()=>nu,Has:()=>tu,IsDate:()=>Vc,IsDateTime:()=>Wc,IsDuration:()=>Kc,IsEmail:()=>Jc,IsHostname:()=>_l,IsIPv4:()=>Sl,IsIPv6:()=>wl,IsIdnEmail:()=>yl,IsIdnHostname:()=>bl,IsIri:()=>Dl,IsIriReference:()=>El,IsJsonPointer:()=>jl,IsJsonPointerUriFragment:()=>kl,IsRegex:()=>Ml,IsRelativeJsonPointer:()=>Pl,IsTime:()=>Uc,IsUri:()=>Kl,IsUriReference:()=>Il,IsUriTemplate:()=>Rl,IsUrl:()=>Jl,IsUuid:()=>Xl,Reset:()=>iu,Set:()=>eu,Test:()=>ru});function ou(e,t,n,r){return no(H(`Format`,`Test`),[U(n.format),r])}function su(e,t,n,r){return ru(n.format,r)}function cu(e,t,n,r,i,a){return su(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function lu(e,t,n,r){let i=!bs(n)||n.then,a=!Uo(n)||n.else;return io(hf(e,t,n.if,r),hf(e,t,i,r),hf(e,t,a,r))}function uu(e,t,n,r){let i=!bs(n)||n.then,a=!Uo(n)||n.else;return _f(e,t,n.if,r)?_f(e,t,i,r):_f(e,t,a,r)}function du(e,t,n,r,i,a){let o=!bs(i)||i.then,s=!Uo(i)||i.else,c=new Os,l=yf(e,c,`${n}/if`,r,i.if,a)?yf(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):yf(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function fu(e,t,n,r){return lo(n.items.map((n,i)=>{let a=Ga(H(r,`length`),U(i)),o=mf(e,t,n,`${r}[${i}]`),s=t.AddIndex(U(i));return Da(a,t.UseUnevaluated()?Ea(o,s):o)}))}function pu(e,t,n,r){return ht(n.items,0,(n,i)=>w(r.length,i)||gf(e,t,n,r[i])&&t.AddIndex(i))}function mu(e,t,n,r,i,a){return Be(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return w(a.length,o)||vf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function hu(e,t,n,r){let i=ps(n)?n.prefixItems.length:0,a=mf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ea(a,o):a;return Ya(r,U(i),[`element`,`index`],s)}function gu(e,t,n,r){let i=ps(n)?n.prefixItems.length:0;return ht(r,i,(r,i)=>gf(e,t,n.items,r)&&t.AddIndex(i))}function _u(e,t,n,r,i,a){let o=ps(i)?i.prefixItems.length:0;return Be(a,o,(a,o)=>vf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function vu(e,t,n,r){return Zo(n)?fu(e,t,n,r):hu(e,t,n,r)}function yu(e,t,n,r){return Zo(n)?pu(e,t,n,r):gu(e,t,n,r)}function bu(e,t,n,r,i,a){return Zo(i)?mu(e,t,n,r,i,a):_u(e,t,n,r,i,a)}function xu(e){return Io(e)}function Su(e,t,n,r){if(!xu(n))return U(!0);let[i,a]=[Ls(),Ls()];return Ga(no(H(r,`reduce`),[to([i,a],io(hf(e,t,n.contains,a),fo(i),i)),U(0)]),U(n.maxContains))}function Cu(e,t,n,r){if(!xu(n))return!0;let i=r.reduce((r,i)=>_f(e,t,n.contains,i)?++r:r,0);return w(i,n.maxContains)}function wu(e,t,n,r,i,a){let o=is(i)?i.minContains:1;return Cu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Tu(e,t,n,r){return Ga(r,U(n.maximum))}function Eu(e,t,n,r){return w(r,n.maximum)}function Du(e,t,n,r,i,a){return Eu(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Ou(e,t,n,r){return Ga(H(r,`length`),U(n.maxItems))}function ku(e,t,n,r){return w(r.length,n.maxItems)}function Au(e,t,n,r,i,a){return ku(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function ju(e,t,n,r){return Ja(r,U(n.maxLength))}function Mu(e,t,n,r){return F(r,n.maxLength)}function Nu(e,t,n,r,i,a){return Mu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function Pu(e,t,n,r){return Ga(H(Za(r),`length`),U(n.maxProperties))}function Fu(e,t,n,r){return w(k(r).length,n.maxProperties)}function Iu(e,t,n,r,i,a){return Fu(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function Lu(e){return Io(e)}function Ru(e,t,n,r){if(!Lu(n))return U(!0);let[i,a]=[Ls(),Ls()];return Ka(no(H(r,`reduce`),[to([i,a],io(hf(e,t,n.contains,a),fo(i),i)),U(0)]),U(n.minContains))}function zu(e,t,n,r){if(!Lu(n))return!0;let i=r.reduce((r,i)=>_f(e,t,n.contains,i)?++r:r,0);return Ie(i,n.minContains)}function Bu(e,t,n,r,i,a){return zu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function Vu(e,t,n,r){return Ka(r,U(n.minimum))}function Hu(e,t,n,r){return Ie(r,n.minimum)}function Uu(e,t,n,r,i,a){return Hu(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function Wu(e,t,n,r){return Ka(H(r,`length`),U(n.minItems))}function Gu(e,t,n,r){return Ie(r.length,n.minItems)}function Ku(e,t,n,r,i,a){return Gu(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function qu(e,t,n,r){return qa(r,U(n.minLength))}function Ju(e,t,n,r){return ne(r,n.minLength)}function Yu(e,t,n,r,i,a){return Ju(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Xu(e,t,n,r){return Ka(H(Za(r),`length`),U(n.minProperties))}function Zu(e,t,n,r){return Ie(k(r).length,n.minProperties)}function Qu(e,t,n,r,i,a){return Zu(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function $u(e,t,n,r){return po(r,U(n.multipleOf))}function ed(e,t,n,r){return D(r,n.multipleOf)}function td(e,t,n,r,i,a){return ed(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function nd(e,t,n,r){return Xs(e,t,[n.not],r,Oa(Ha(H(`results`,`length`),U(1))))}function rd(e,t,n,r){return Oa(hf(e,t,n.not,r))}function id(e,t,n,r){return t.UseUnevaluated()?nd(e,t,n,r):rd(e,t,n,r)}function ad(e,t,n,r){let i=new Es;return!_f(e,i,n.not,r)&&t.Merge([i])}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function sd(e,t,n,r){return Xs(e,t,n.oneOf,r,Ha(H(`results`,`length`),U(1)))}function cd(e,t,n,r){return Ha(no(H(eo(n.oneOf.map(n=>hf(e,t,n,r))),`reduce`),[to([`count`,`result`],io(Ha(`result`,U(!0)),fo(`count`),`count`)),U(0)]),U(1))}function ld(e,t,n,r){return t.UseUnevaluated()?sd(e,t,n,r):cd(e,t,n,r)}function ud(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return B(i.length,1)&&t.Merge(i)}function dd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Os,u=yf(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=B(c.length,1)&&t.Merge(c);return!l&&B(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function fd(e,t,n,r){return no(H(As(j(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function pd(e,t,n,r){return(j(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function md(e,t,n,r,i,a){return pd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function hd(e,t,n,r){return lo(Re(n.patternProperties).map(([n,i])=>{let[a,o]=[Ls(),Ls()],s=Oa(no(H(As(new RegExp(n,`u`)),`test`),[a])),c=mf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?Da(s,Ea(c,l)):Da(s,c);return Ya(Xa(r),U(0),[`[${a}, ${o}]`,`_`],u)}))}function gd(e,t,n,r){return ht(Re(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return ht(Re(r),0,([n,r])=>!a.test(n)||gf(e,t,i,r)&&t.AddKey(n))})}function _d(e,t,n,r,i,a){return Be(Re(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Be(Re(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||vf(e,t,s,a,o,i)&&t.AddKey(n)})})}function vd(e,t,n,r){return lo(n.prefixItems.map((n,i)=>{let a=Ga(H(r,`length`),U(i)),o=mf(e,t,n,`${r}[${i}]`),s=t.AddIndex(U(i));return Da(a,t.UseUnevaluated()?Ea(o,s):o)}))}function yd(e,t,n,r){return B(r.length,0)||ht(n.prefixItems,0,(n,i)=>w(r.length,i)||gf(e,t,n,r[i])&&t.AddIndex(i))}function bd(e,t,n,r,i,a){return B(a.length,0)||Be(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return w(a.length,o)||vf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function xd(e,t){return e.includes(t)||st().exactOptionalPropertyTypes}function Sd(e,t){return za(H(e,t))}function Cd(e,t){return ve(e[t])}function wd(e,t,n,r){let i=ys(n)?n.required:[];return lo(Re(n.properties).map(([n,a])=>{let o=Oa(Qa(r,U(n))),s=mf(e,t,a,H(r,n)),c=t.AddKey(U(n)),l=t.UseUnevaluated()?Ea(s,c):s,u=i.includes(n)?l:Da(o,l);return xd(i,n)?u:Da(Sd(r,n),u)}))}function Td(e,t,n,r){let i=ys(n)?n.required:[];return ht(Re(n.properties),0,([n,a])=>{let o=!z(r,n)||gf(e,t,a,r[n])&&t.AddKey(n);return xd(i,n)?o:Cd(r,n)||o})}function Ed(e,t,n,r,i,a){let o=ys(i)?i.required:[];return Be(Re(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!z(a,i)||vf(e,t,c,l,s,a[i])&&t.AddKey(i);return xd(o,i)?u():Cd(a,i)||u()})}function Dd(e,t,n,r){let[i,a]=[Ls(),Ls()];return Ya(Za(r),U(0),[i,a],hf(e,t,n.propertyNames,i))}function Od(e,t,n,r){return ht(k(r),0,(r,i)=>_f(e,t,n.propertyNames,r))}function kd(e,t,n,r,i,a){let o=[];return Be(k(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=yf(e,new Os,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Ad(e,t,n,r){return kf(e,t,e.RecursiveRef(n)??!1,r)}function jd(e,t,n,r){let i=e.RecursiveRef(n)??!1;return ko(i)&&_f(e,t,i,r)}function Md(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return ko(o)&&yf(e,t,`#`,r,o,a)}function Nd(e,t,n,r){let i=to([`context`,`value`],kf(e,t,n,`value`));return no(to([`context`,`value`],ao([oo(`nextContext`,ro(`CheckContext`,[])),oo(`result`,no(i,[`nextContext`,`value`])),so(`result`,t.Merge(`[nextContext]`)),co(`result`)])),[`context`,r])}function Pd(e,t,n,r){return kf(e,t,n,r)}function Fd(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?Nd(e,t,i,r):Pd(e,t,i,r)}function Id(e,t,n,r){let i=e.Ref(n)??!1,a=new Es,o=ko(i)&&_f(e,a,i,r);return o&&t.Merge([a]),o}function Ld(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Os,c=ko(o)&&yf(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function Rd(e,t,n,r){return lo(n.required.map(e=>Qa(r,U(e))))}function zd(e,t,n,r){return ht(n.required,0,e=>z(r,e))}function Bd(e,t,n,r,i,a){let o=[];return Be(i.required,0,e=>{let t=z(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function Vd(e,t,n,r){return B(n,`object`)?Fa(r):B(n,`array`)?ka(r):B(n,`boolean`)?ja(r):B(n,`integer`)?Ma(r):B(n,`number`)?Pa(r):B(n,`null`)?Na(r):B(n,`string`)?La(r):B(n,`bigint`)?Aa(r):B(n,`constructor`)?Va(r):B(n,`function`)?Ba(r):B(n,`symbol`)?Ra(r):B(n,`undefined`)||B(n,`void`)?za(r):U(!0)}function Hd(e,t,n,r,i){return B(n,`object`)?Ze(i):B(n,`array`)?lt(i):B(n,`boolean`)?qe(i):B(n,`integer`)?P(i):B(n,`number`)?$e(i):B(n,`null`)?ge(i):B(n,`string`)?j(i):B(n,`bigint`)?it(i):B(n,`constructor`)?eee(i):B(n,`function`)?St(i):B(n,`symbol`)?me(i):B(n,`undefined`)?ve(i):!B(n,`void`)||ve(i)}function Ud(e,t,n,r){return uo(n.map(n=>Vd(e,t,n,r)))}function Wd(e,t,n,r,i){return n.some(n=>Hd(e,t,n,r,i))}function Gd(e,t,n,r){return lt(n.type)?Ud(e,t,n.type,r):Vd(e,t,n.type,r)}function Kd(e,t,n,r){return lt(n.type)?Wd(e,t,n.type,n,r):Hd(e,t,n.type,n,r)}function qd(e,t,n,r,i,a){return(lt(i.type)?Wd(e,t,i.type,i,a):Hd(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function Jd(e,t,n,r){let[i,a]=[Ls(),Ls()],o=no(H(`context`,`GetIndices`),[]),s=no(H(`indices`,`has`),[i]),c=hf(e,t,n.unevaluatedItems,a),l=no(H(`context`,`AddIndex`),[i]),u=Ya(r,U(0),[a,i],Ea(Da(s,c),l));return no(to([`context`],ao([oo(`indices`,o),co(u)])),[`context`])}function Yd(e,t,n,r){let i=t.GetIndices();return ht(r,0,(r,a)=>(i.has(a)||_f(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function Xd(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Be(a,0,(a,c)=>{let l=new Os,u=(o.has(c)||yf(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function Zd(e,t,n,r){let[i,a]=[Ls(),Ls()],o=no(H(`context`,`GetKeys`),[]),s=no(H(`keys`,`has`),[i]),c=no(H(`context`,`AddKey`),[i]),l=hf(e,t,n.unevaluatedProperties,a),u=Ya(Xa(r),U(0),[`[${i}, ${a}]`,`_`],Da(s,Ea(l,c)));return no(to([`context`],ao([oo(`keys`,o),co(u)])),[`context`])}function Qd(e,t,n,r){let i=t.GetKeys();return ht(Re(r),0,([r,a])=>i.has(r)||_f(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function $d(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Be(Re(a),0,([a,c])=>{let l=new Os,u=o.has(a)||yf(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function ef(e){return!B(e.uniqueItems,!1)}function tf(e,t,n,r){return ef(n)?Ha(H(ro(`Set`,[no(H(r,`map`),[H(`Hashing`,`Hash`)])]),`size`),H(r,`length`)):U(!0)}function nf(e,t,n,r){if(!ef(n))return!0;let i=new Set(r.map(C)).size,a=r.length;return B(i,a)}function rf(e,t,n,r,i,a){if(!ef(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=C(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return B(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function af(e,t){return xs(e)&&(lt(e.type)&&xt(e.type.length,0)&&ht(e.type,0,e=>B(e,t))||B(e.type,t))}function of(e){return af(e,`object`)}function sf(e){return Do(e)&&(jo(e)||Ro(e)||zo(e)||Bo(e)||ms(e)||fs(e)||hs(e)||ss(e)||ns(e)||ys(e)||ws(e))}function cf(e){return af(e,`array`)}function lf(e){return Do(e)&&(Ao(e)||Xo(e)||Io(e)||$o(e)||es(e)||is(e)||as(e)||ps(e)||Cs(e)||Ss(e))}function uf(e){return af(e,`string`)}function df(e){return Do(e)&&(os(e)||ts(e)||qo(e)||ds(e))}function ff(e){return af(e,`number`)||af(e,`bigint`)}function pf(e){return Do(e)&&(rs(e)||Qo(e)||Go(e)||Ko(e)||cs(e))}function mf(e,t,n,r){return t.UseUnevaluated()?Ea(Ea(t.Push(),hf(e,t,n,r)),t.Pop()):hf(e,t,n,r)}function hf(e,t,n,r){e.Push(n);let i=[];if(Oo(n))return sc(e,t,n,r);if(xs(n)&&i.push(Gd(e,t,n,r)),sf(n)){let a=[];ys(n)&&a.push(Rd(e,t,n,r)),jo(n)&&a.push(qs(e,t,n,r)),Ro(n)&&a.push(_c(e,t,n,r)),zo(n)&&a.push(bc(e,t,n,r)),Bo(n)&&a.push(Cc(e,t,n,r)),fs(n)&&a.push(hd(e,t,n,r)),ms(n)&&a.push(wd(e,t,n,r)),hs(n)&&a.push(Dd(e,t,n,r)),ss(n)&&a.push(Xu(e,t,n,r)),ns(n)&&a.push(Pu(e,t,n,r));let o=lo(a),s=Da(Oa(Fa(r)),o);i.push(of(n)?o:s)}if(lf(n)){let a=[];Ao(n)&&a.push(zs(e,t,n,r)),Io(n)&&a.push(mc(e,t,n,r)),Xo(n)&&a.push(vu(e,t,n,r)),$o(n)&&a.push(Su(e,t,n,r)),es(n)&&a.push(Ou(e,t,n,r)),is(n)&&a.push(Ru(e,t,n,r)),as(n)&&a.push(Wu(e,t,n,r)),ps(n)&&a.push(vd(e,t,n,r)),Ss(n)&&a.push(tf(e,t,n,r));let o=lo(a),s=Da(Oa(ka(r)),o);i.push(cf(n)?o:s)}if(df(n)){let a=[];ts(n)&&a.push(ju(e,t,n,r)),os(n)&&a.push(qu(e,t,n,r)),qo(n)&&a.push(ou(e,t,n,r)),ds(n)&&a.push(fd(e,t,n,r));let o=lo(a),s=Da(Oa(La(r)),o);i.push(uf(n)?o:s)}if(pf(n)){let a=[];Go(n)&&a.push(Mc(e,t,n,r)),Ko(n)&&a.push(Fc(e,t,n,r)),Qo(n)&&a.push(Tu(e,t,n,r)),rs(n)&&a.push(Vu(e,t,n,r)),cs(n)&&a.push($u(e,t,n,r));let o=lo(a),s=Da(Oa(Da(Pa(r),Aa(r))),o);i.push(ff(n)?o:s)}vs(n)&&i.push(Fd(e,t,n,r)),_s(n)&&i.push(Ad(e,t,n,r)),Ho(n)&&i.push(Ec(e,t,n,r)),Fo(n)&&i.push(uc(e,t,n,r)),Wo(n)&&i.push(kc(e,t,n,r)),Yo(n)&&i.push(lu(e,t,n,r)),ls(n)&&i.push(id(e,t,n,r)),Mo(n)&&i.push($s(e,t,n,r)),Po(n)&&i.push(ic(e,t,n,r)),us(n)&&i.push(ld(e,t,n,r)),Cs(n)&&i.push(Da(Oa(ka(r)),Jd(e,t,n,r))),ws(n)&&i.push(Da(Oa(Ia(r)),Zd(e,t,n,r))),Eo(n)&&i.push(Ns(e,t,n,r));let a=lo(i);return e.Pop(n),a}function gf(e,t,n,r){return t.Push()&&_f(e,t,n,r)&&t.Pop()}function _f(e,t,n,r){e.Push(n);let i=Oo(n)?cc(e,t,n,r):(!xs(n)||Kd(e,t,n,r))&&(!(x(r)&&!lt(r))||(!ys(n)||zd(e,t,n,r))&&(!jo(n)||Js(e,t,n,r))&&(!Ro(n)||vc(e,t,n,r))&&(!zo(n)||xc(e,t,n,r))&&(!Bo(n)||wc(e,t,n,r))&&(!fs(n)||gd(e,t,n,r))&&(!ms(n)||Td(e,t,n,r))&&(!hs(n)||Od(e,t,n,r))&&(!ss(n)||Zu(e,t,n,r))&&(!ns(n)||Fu(e,t,n,r)))&&(!lt(r)||(!Ao(n)||Bs(e,t,n,r))&&(!Io(n)||hc(e,t,n,r))&&(!Xo(n)||yu(e,t,n,r))&&(!$o(n)||Cu(e,t,n,r))&&(!es(n)||ku(e,t,n,r))&&(!is(n)||zu(e,t,n,r))&&(!as(n)||Gu(e,t,n,r))&&(!ps(n)||yd(e,t,n,r))&&(!Ss(n)||nf(e,t,n,r)))&&(!j(r)||(!ts(n)||Mu(e,t,n,r))&&(!os(n)||Ju(e,t,n,r))&&(!qo(n)||su(e,t,n,r))&&(!ds(n)||pd(e,t,n,r)))&&(!($e(r)||it(r))||(!Go(n)||Nc(e,t,n,r))&&(!Ko(n)||Ic(e,t,n,r))&&(!Qo(n)||Eu(e,t,n,r))&&(!rs(n)||Hu(e,t,n,r))&&(!cs(n)||ed(e,t,n,r)))&&(!vs(n)||Id(e,t,n,r))&&(!_s(n)||jd(e,t,n,r))&&(!Ho(n)||Dc(e,t,n,r))&&(!Fo(n)||dc(e,t,n,r))&&(!Wo(n)||Ac(e,t,n,r))&&(!Yo(n)||uu(e,t,n,r))&&(!ls(n)||ad(e,t,n,r))&&(!Mo(n)||ec(e,t,n,r))&&(!Po(n)||ac(e,t,n,r))&&(!us(n)||ud(e,t,n,r))&&(!Cs(n)||!lt(r)||Yd(e,t,n,r))&&(!ws(n)||!x(r)||Qd(e,t,n,r))&&(!Eo(n)||Ps(e,t,n,r));return e.Pop(n),i}function vf(e,t,n,r,i,a){return t.Push()&&yf(e,t,n,r,i,a)&&t.Pop()}function yf(e,t,n,r,i,a){e.Push(i);let o=Oo(i)?lc(e,t,n,r,i,a):!!((!xs(i)||qd(e,t,n,r,i,a))&+(!(x(a)&&!lt(a))||!!((!ys(i)||Bd(e,t,n,r,i,a))&+(!jo(i)||Ys(e,t,n,r,i,a))&(!Ro(i)||yc(e,t,n,r,i,a))&(!zo(i)||Sc(e,t,n,r,i,a))&(!Bo(i)||Tc(e,t,n,r,i,a))&(!fs(i)||_d(e,t,n,r,i,a))&(!ms(i)||Ed(e,t,n,r,i,a))&(!hs(i)||kd(e,t,n,r,i,a))&(!ss(i)||Qu(e,t,n,r,i,a))&(!ns(i)||Iu(e,t,n,r,i,a))))&(!lt(a)||!!((!Ao(i)||Vs(e,t,n,r,i,a))&+(!Io(i)||gc(e,t,n,r,i,a))&(!Xo(i)||bu(e,t,n,r,i,a))&(!$o(i)||wu(e,t,n,r,i,a))&(!es(i)||Au(e,t,n,r,i,a))&(!is(i)||Bu(e,t,n,r,i,a))&(!as(i)||Ku(e,t,n,r,i,a))&(!ps(i)||bd(e,t,n,r,i,a))&(!Ss(i)||rf(e,t,n,r,i,a))))&(!j(a)||!!((!ts(i)||Nu(e,t,n,r,i,a))&+(!os(i)||Yu(e,t,n,r,i,a))&(!qo(i)||cu(e,t,n,r,i,a))&(!ds(i)||md(e,t,n,r,i,a))))&(!($e(a)||it(a))||!!((!Go(i)||Pc(e,t,n,r,i,a))&+(!Ko(i)||Lc(e,t,n,r,i,a))&(!Qo(i)||Du(e,t,n,r,i,a))&(!rs(i)||Uu(e,t,n,r,i,a))&(!cs(i)||td(e,t,n,r,i,a))))&(!vs(i)||Ld(e,t,n,r,i,a))&(!_s(i)||Md(e,t,n,r,i,a))&(!Ho(i)||Oc(e,t,n,r,i,a))&(!Fo(i)||fc(e,t,n,r,i,a))&(!Wo(i)||jc(e,t,n,r,i,a))&(!Yo(i)||du(e,t,n,r,i,a))&(!ls(i)||od(e,t,n,r,i,a))&(!Mo(i)||tc(e,t,n,r,i,a))&(!Po(i)||oc(e,t,n,r,i,a))&(!us(i)||dd(e,t,n,r,i,a))&(!Cs(i)||!lt(a)||Xd(e,t,n,r,i,a))&(!ws(i)||!x(a)||$d(e,t,n,r,i,a)))&&(!Eo(i)||Fs(e,t,n,r,i,a));return e.Pop(i),o}const bf=[0],xf=new Map,Sf=new Map;function Cf(){return C(bf[0]++)}function wf(e,t){xf.has(e)||xf.set(e,new Map);let n=xf.get(e);if(n.has(t))return n.get(t);let r=Cf();return n.set(t,r),r}function Tf(e,t,n,r){return e.UseUnevaluated()?no(`check_${n}`,[`context`,r]):no(`check_${n}`,[r])}function Ef(e,t,n,r){let i=hf(e,t,n,`value`);return t.UseUnevaluated()?oo(`check_${r}`,to([`context`,`value`],i)):oo(`check_${r}`,to([`value`],i))}function Df(){bf[0]=0,xf.clear(),Sf.clear()}function Of(){return[...Sf.values()]}function kf(e,t,n,r){let i=wf(n,e.BaseURL().href),a=Tf(t,n,i,r);return Sf.has(i)?a:(Sf.set(i,``),Sf.set(i,Ef(e,t,n,i)),a)}function Af(e,t){return x(t)&&!O(e)?t[e]:void 0}function jf(e,t){return e.reduce((e,t)=>Af(t,e),t)}function Mf(e){if(B(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function Nf(e,t){return jf(Mf(t),e)}function Pf(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(B(r.pathname,i.pathname))return n.hash.startsWith(`#`)?Lf(e,t,n):e}function Ff(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return B(r.href,i.href)?e:void 0}function If(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return B(r.href,i.href)?e:void 0}function Lf(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Nf(e,r)}function Rf(e,t,n){if(Jo(e)){let r=Pf(e,t,n);if(!ve(r))return r}if(No(e)){let r=Ff(e,t,n);if(!ve(r))return r}if(Vo(e)){let r=If(e,t,n);if(!ve(r))return r}return Lf(e,t,n)}function zf(e,t,n){return e.reduce((e,r)=>{let i=Vf(r,t,n);return ve(i)?e:i},void 0)}function Bf(e,t,n){return k(e).reduce((r,i)=>{let a=Vf(e[i],t,n);return ve(a)?r:a},void 0)}function Vf(e,t,n){let r=Do(e)&&Jo(e)?new URL(e.$id,t.href):t;if(Do(e)){let t=Rf(e,r,n);if(!ve(t))return t}if(lt(e))return zf(e,r,n);if(x(e))return Bf(e,r,n)}function Hf(e,t){let n=new URL(`http://unknown/`),r=Jo(e)?new URL(e.$id,n.href):n;return Vf(e,r,new URL(t,r.href))}function Uf(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?Hf(t,n.$dynamicRef):Hf(e,n.$dynamicRef);if(!ve(i))return!Do(i)||!Vo(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var Wf=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Gf,Kf,qf,Jf,Yf,Xf=class{constructor(e,t){Gf.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Do(e)&&(Jo(e)&&(this.ids.push(e),Wf(this,Gf,`m`,Kf).call(this,e)),No(e)&&this.anchors.push(e),gs(e)&&this.recursiveAnchors.push(e),Vo(e)&&this.dynamicAnchors.push(e))}Pop(e){Do(e)&&(Jo(e)&&(this.ids.pop(),Wf(this,Gf,`m`,qf).call(this,e)),No(e)&&this.anchors.pop(),gs(e)&&this.recursiveAnchors.pop(),Vo(e)&&this.dynamicAnchors.pop())}Ref(e){return Wf(this,Gf,`m`,Jf).call(this,e)??Wf(this,Gf,`m`,Yf).call(this,e)}RecursiveRef(e){return gs(this.Base())?Hf(this.recursiveAnchors[0],e.$recursiveRef):Hf(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return Uf(t,this.Base(),e,this.dynamicAnchors)}};Gf=new WeakSet,Kf=function e(t,n=!0){if(!Do(t))return;let r=t;if(!(!n&&Jo(r))){!n&&Vo(r)&&this.dynamicAnchors.push(r);for(let t of k(r))Wf(this,Gf,`m`,e).call(this,r[t],!1)}},qf=function e(t,n=!0){if(!Do(t))return;let r=t;if(!(!n&&Jo(r))){!n&&Vo(r)&&this.dynamicAnchors.pop();for(let t of k(r))Wf(this,Gf,`m`,e).call(this,r[t],!1)}},Jf=function(e){return z(this.context,e.$ref)?this.context[e.$ref]:void 0},Yf=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?Hf(this.Base(),e.$ref):Hf(t,e.$ref)};function Zf(e){return`${e.Functions().join(`;
|
|
880
|
-
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function Qf(e,t){return yo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Es,xe,au,Te,e.External().variables)}function $f(e){let t=new Xf(e.Context(),e.Schema()),n=new Es;return r=>_f(t,n,e.Schema(),r)}function ep(e,t){return vo()?Qf(e,t):$f(e)}var tp=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},np=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=Zf(this),t=ep(this,e);return new tp(vo(),e,t)}};function rp(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});js(),Df();let r=new Xf(t,n),i=new ute(lte(t,n)),a=kf(r,i,n,`value`),o=Of();return new np(t,n,Ms(),o,a,i.UseUnevaluated())}function ip(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=st(),a=So(),o=[];return[yf(new Xf(t,n),new Ds(e=>{if(!Ie(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function ap(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return _f(new Xf(t,n),new Es,n,r)}function op(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ap(t,n,r)}function sp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=ip(t,n,r);return a}var cp=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function lp(e,t,n){return lt(n)?n.map(n=>bp(e,t.items,n)):n}function up(e,t,n){return bp({...e,...t.$defs},b(t.$ref),n)}function dp(e,t){let n=z(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=gt(e,t),i=nt(r);return le(i)?Ve(i,n):i}function fp(e,t,n){return bp(e,dp(e,t),n)}function pp(e){return z(e,`additionalProperties`)?e.additionalProperties:void 0}function mp(e,t,n){if(!x(n)||lt(n))return n;let r=pp(t);for(let i of k(n)){if(z(t.properties,i)){n[i]=bp(e,t.properties[i],n[i]);continue}if(qe(r)&&B(r,!0)||Pe(r)&&op(e,r,n[i])){n[i]=bp(e,r,n[i]);continue}delete n[i]}return n}function hp(e,t,n){if(!x(n))return n;let r=pp(t),[i,a]=[new RegExp(_t(t)),Ct(t)];for(let t of k(n)){if(i.test(t)){n[t]=bp(e,a,n[t]);continue}if(qe(r)&&B(r,!0)||Pe(r)&&op(e,r,n[t])){n[t]=bp(e,r,n[t]);continue}delete n[t]}return n}function gp(e,t,n){return z(e,t.$ref)?bp(e,e[t.$ref],n):n}function _p(e,t,n){if(!lt(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=bp(e,t.items[i],n[i]);return xt(n.length,r)?n.slice(0,r):n}function vp(e){return nee(e)}function yp(e,t,n){for(let r of t.anyOf){let t=bp(e,r,vp(n));if(op(e,r,t))return t}return n}function bp(e,t,n){return ft(t)?lp(e,t,n):ue(t)?up(e,t,n):Ee(t)?fp(e,t,n):le(t)?mp(e,t,n):Je(t)?hp(e,t,n):M(t)?gp(e,t,n):Le(t)?_p(e,t,n):T(t)?yp(e,t,n):n}function xp(e,t){for(let n of mo.Keys(e))mo.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Sp(e){let t={};for(let n of mo.Keys(e))t[n]=Tp(e[n]);return t}function Cp(e){return wp(ze(e))}function wp(e){return e.map(e=>Tp(e))}function Tp(e){return xp(e,ft(e)?Ye(Tp(e.items),tee(e)):Ee(e)?I(wp(e.allOf)):T(e)?bt(Cp(e.anyOf)):le(e)?ke(Sp(e.properties)):Je(e)?Ge(Ne(e),Tp(Ct(e))):Le(e)?aee(wp(e.items)):e)}function Ep(e){return Tp(e)}function Dp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return bp(t,st().unionPrioritySort?Ep(n):n,r)}function Op(e){return x(e)&&z(e,`value`)}function W(e){return{value:e}}function kp(e){return lt(e)?W(e):W([e])}function dte(e){return B(e,!0)?W(BigInt(1)):W(BigInt(0))}const fte=/^-?(0|[1-9]\d*)n$/,pte=/^-?(0|[1-9]\d*)\.\d+$/,mte=/^-?(0|[1-9]\d*)$/;function hte(e){return fte.test(e)}function gte(e){return pte.test(e)}function _te(e){return mte.test(e)}function vte(e){let t=e.toLowerCase();return hte(e)?W(BigInt(e.slice(0,e.length-1))):gte(e)?W(BigInt(e.split(`.`)[0])):_te(e)?W(BigInt(e)):B(t,`false`)?W(BigInt(0)):B(t,`true`)?W(BigInt(1)):void 0}function Ap(e){return it(e)?W(e):qe(e)?dte(e):$e(e)?W(BigInt(Math.trunc(e))):ge(e)?W(BigInt(0)):j(e)?vte(e):ve(e)?W(BigInt(0)):void 0}function yte(e){return B(e,BigInt(0))?W(!1):B(e,BigInt(1))?W(!0):void 0}function bte(e){return B(e,0)?W(!1):B(e,1)?W(!0):void 0}function xte(e){return B(e.toLowerCase(),`false`)?W(!1):B(e.toLowerCase(),`true`)?W(!0):B(e,`0`)?W(!1):B(e,`1`)?W(!0):void 0}function jp(e){return it(e)?yte(e):qe(e)?W(e):$e(e)?bte(e):ge(e)?W(!1):j(e)?xte(e):ve(e)?W(!1):void 0}function Ste(e){return B(e,BigInt(0))?W(null):void 0}function Cte(e){return B(e,!1)?W(null):void 0}function wte(e){return B(e,0)?W(null):void 0}function Tte(e){let t=e.toLowerCase();return B(t,`undefined`)||B(t,`null`)||B(e,``)||B(e,`0`)?W(null):void 0}function Ete(e){return it(e)?Ste(e):qe(e)?Cte(e):$e(e)?wte(e):ge(e)?W(null):j(e)?Tte(e):ve(e)?W(null):void 0}const Mp=BigInt(2**53-1),Np=BigInt(-(2**53-1));function Dte(e){return e<=Mp&&e>=Np?W(Number(e)):void 0}function Ote(e){return W(+!!e)}function kte(e){let t=+e;if($e(t))return W(t);let n=e.toLowerCase();if(B(n,`false`))return W(0);if(B(n,`true`))return W(1);let r=Ap(e);if(Op(r))return r.value<=Mp&&r.value>=Np?W(Number(r.value)):void 0}function Pp(e){return it(e)?Dte(e):qe(e)?Ote(e):$e(e)?W(e):ge(e)?W(0):j(e)?kte(e):ve(e)?W(0):void 0}function Fp(e){return it(e)||qe(e)||$e(e)?W(e.toString()):ge(e)?W(`null`):j(e)?W(e):ve(e)?W(``):void 0}function Ate(e){return B(e,BigInt(0))?W(void 0):void 0}function jte(e){return B(e,!1)?W(void 0):void 0}function Mte(e){return B(e,0)?W(void 0):void 0}function Nte(e){let t=e.toLowerCase();return B(t,`undefined`)||B(t,`null`)||B(e,``)||B(e,`0`)?W(void 0):void 0}function Ip(e){return it(e)?Ate(e):qe(e)?jte(e):$e(e)?Mte(e):ge(e)?W(void 0):j(e)?Nte(e):ve(e)?W(e):void 0}function Pte(e,t,n){return kp(n).value.map(n=>zp(e,t.items,n))}function Fte(e,t,n){let r=Ap(n);return Op(r)?r.value:n}function Ite(e,t,n){let r=jp(n);return Op(r)?r.value:n}function Lte(e,t,n){return zp({...e,...t.$defs},b(t.$ref),n)}function Rte(e,t,n){return zp(e,nt(t),n)}function zte(e,t,n){let r=Pp(n);return Op(r)?Math.trunc(r.value):n}function Bte(e,t,n){let r=gt(e,t);return zp(e,nt(r),n)}function Vte(e,t,n){let r=Ap(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Hte(e,t,n){let r=jp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Ute(e,t,n){let r=Pp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Wte(e,t,n){let r=Fp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Gte(e,t,n){return B(t.const,n)?n:Qe(t)?Vte(e,t,n):pe(t)?Hte(e,t,n):he(t)?Ute(e,t,n):ye(t)?Wte(e,t,n):oe()}function Kte(e,t,n){let r=Ete(n);return Op(r)?r.value:n}function qte(e,t,n){let r=Pp(n);return Op(r)?r.value:n}function Lp(e,t,n,r){let i=k(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=zp(e,n,r[t]));return r}function Rp(e,t,n){return Oe(e)&&ve(n[t])}function Jte(e,t,n){let r=tt(t.properties),i=k(n);for(let[t,a]of r)for(let r of i)!t.test(r)||Rp(a,r,n)||(n[r]=zp(e,a,n[r]));return z(t,`additionalProperties`)&&x(t.additionalProperties)?Lp(e,r,t.additionalProperties,n):n}function Yte(e,t,n){return Ze(n)?Jte(e,t,n):n}function Xte(e,t,n){let r=tt(t.patternProperties),i=k(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=zp(e,a,n[r]));return z(t,`additionalProperties`)&&x(t.additionalProperties)?Lp(e,r,t.additionalProperties,n):n}function Zte(e,t,n){return Ze(n)?Xte(e,t,n):n}function Qte(e,t,n){return z(e,t.$ref)?zp(e,e[t.$ref],n):n}function $te(e,t,n){let r=Fp(n);return Op(r)?r.value:n}function ene(e,t,n){return zp(e,nt(t),n)}function tne(e,t,n){if(!lt(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=zp(e,t.items[r],n[r]);return n}function nne(e,t,n){let r=Ip(n);return Op(r)?r.value:n}function rne(e,t,n){if(t.anyOf.some(t=>op(e,t,n)))return n;let r=t.anyOf.map(t=>zp(e,t,vp(n))).find(n=>op(e,t,n));return ve(r)?n:r}function ine(e,t,n){return Op(Ip(n))?void 0:n}function zp(e,t,n){return ft(t)?Pte(e,t,n):Se(t)?Fte(e,t,n):fe(t)?Ite(e,t,n):ue(t)?Lte(e,t,n):ae(t)?Rte(e,t,n):ce(t)?zte(e,t,n):Ee(t)?Bte(e,t,n):S(t)?Gte(e,t,n):et(t)?Kte(e,t,n):_e(t)?qte(e,t,n):le(t)?Yte(e,t,n):Je(t)?Zte(e,t,n):M(t)?Qte(e,t,n):we(t)?$te(e,t,n):We(t)?ene(e,t,n):Le(t)?tne(e,t,n):at(t)?nne(e,t,n):T(t)?rne(e,t,n):ut(t)?ine(e,t,n):n}function Bp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return zp(t,n,r)}function ane(e,t,n){if(!lt(n))return n;for(let r=0;r<n.length;r++)n[r]=Vp(e,t.items,n[r]);return n}function one(e,t,n){return Vp({...e,...t.$defs},b(t.$ref),n)}function sne(e,t){return ve(t)?St(e.default)?e.default():vp(e.default):t}function cne(e,t,n){let r=gt(e,t);return Vp(e,nt(r),n)}function lne(e,t,n){if(!x(n))return n;let r=k(t.properties);for(let i of r){let r=Vp(e,t.properties[i],n[i]);ve(r)&&(Oe(t.properties[i])||!z(t.properties[i],`default`))||(n[i]=r)}if(!jo(t)||qe(t.additionalProperties))return n;for(let i of k(n))r.includes(i)||(n[i]=Vp(e,t.additionalProperties,n[i]));return n}function une(e,t,n){if(!x(n))return n;let[r,i]=[new RegExp(_t(t)),Ct(t)];for(let t of k(n))r.test(t)&&Lo(i)&&(n[t]=Vp(e,i,n[t]));if(!jo(t))return n;for(let i of k(n))r.test(i)||(n[i]=Vp(e,t.additionalProperties,n[i]));return n}function dne(e,t,n){return z(e,t.$ref)?Vp(e,e[t.$ref],n):n}function fne(e,t,n){if(!lt(n))return n;let[r,i]=[t.items,Math.max(t.items.length,n.length)];for(let t=0;t<i;t++)t<r.length&&(n[t]=Vp(e,r[t],n[t]));return n}function pne(e,t,n){for(let r of t.anyOf){let t=Vp(e,r,vp(n));if(op(e,r,t))return t}return n}function Vp(e,t,n){let r=Lo(t)?sne(t,n):n;return ft(t)?ane(e,t,r):ue(t)?one(e,t,r):Ee(t)?cne(e,t,r):le(t)?lne(e,t,r):Je(t)?une(e,t,r):M(t)?dne(e,t,r):Le(t)?fne(e,t,r):T(t)?pne(e,t,r):r}function Hp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Vp(t,n,r)}function Up(e){return(...t)=>{let[n,r,i]=ho(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function mne(e,t,n){return t[`~codec`].decode(n)}function hne(e,t,n){return t[`~codec`].encode(n)}function Wp(e,t,n,r){return wt(n)?B(e,`Decode`)?mne(t,n,r):hne(t,n,r):r}function gne(e,t,n,r){if(!lt(r))return r;for(let i=0;i<r.length;i++)r[i]=Jp(e,t,n.items,r[i]);return Wp(e,t,n,r)}function _ne(e,t,n,r){let i=Wp(e,t,n,r);if(!lt(i))return i;for(let r=0;r<i.length;r++)i[r]=Jp(e,t,n.items,i[r]);return i}function vne(e,t,n,r){return B(e,`Decode`)?gne(e,t,n,r):_ne(e,t,n,r)}function yne(e,t,n,r){return r=Jp(e,{...t,...n.$defs},b(n.$ref),r),Wp(e,t,n,r)}function Gp(e){return e.reduce((e,t)=>({...e,...t}),{})}function Kp(e,t){for(let n of t)if(!Me(e,n))return n;return e}function bne(e,t,n,r){if(B(n.allOf.length,0))return Wp(e,t,n,r);let i=n.allOf.map(n=>Jp(e,t,n,Dp(n,vp(r))));return Wp(e,t,n,i.every(e=>x(e))?Gp(i):Kp(r,i))}function xne(e,t,n,r){if(B(n.allOf.length,0))return Wp(e,t,n,r);let i=Wp(e,t,n,r),a=n.allOf.map(n=>Jp(e,t,n,Dp(n,vp(i))));return a.every(e=>x(e))?Gp(a):Kp(i,a)}function Sne(e,t,n,r){return B(e,`Decode`)?bne(e,t,n,r):xne(e,t,n,r)}function Cne(e,t,n,r){if(!Ze(r))return r;for(let i of k(n.properties))!z(r,i)||Rp(n.properties[i],i,r)||(r[i]=Jp(e,t,n.properties[i],r[i]));return Wp(e,t,n,r)}function wne(e,t,n,r){let i=Wp(e,t,n,r);if(!Ze(i))return i;for(let r of k(n.properties))!z(i,r)||Rp(n.properties[r],r,i)||(i[r]=Jp(e,t,n.properties[r],i[r]));return i}function Tne(e,t,n,r){return B(e,`Decode`)?Cne(e,t,n,r):wne(e,t,n,r)}function Ene(e,t,n,r){if(!Ze(r))return r;let i=new RegExp(_t(n));for(let a of k(r))i.test(a)&&(r[a]=Jp(e,t,Ct(n),r[a]));return Wp(e,t,n,r)}function Dne(e,t,n,r){let i=Wp(e,t,n,r);if(!Ze(i))return i;let a=new RegExp(_t(n));for(let r of k(i))a.test(r)&&(i[r]=Jp(e,t,Ct(n),i[r]));return i}function One(e,t,n,r){return B(e,`Decode`)?Ene(e,t,n,r):Dne(e,t,n,r)}function qp(e,t,n,r){return z(t,n.$ref)?Jp(e,t,t[n.$ref],r):r}function kne(e,t,n,r){return B(e,`Decode`)?Wp(e,t,n,qp(e,t,n,r)):qp(e,t,n,Wp(e,t,n,r))}function Ane(e,t,n,r){if(!lt(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=Jp(e,t,n.items[i],r[i]);return Wp(e,t,n,r)}function jne(e,t,n,r){let i=Wp(e,t,n,r);if(!lt(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=Jp(e,t,n.items[r],i[r]);return i}function Mne(e,t,n,r){return B(e,`Decode`)?Ane(e,t,n,r):jne(e,t,n,r)}function Nne(e,t,n,r){for(let i of n.anyOf)if(op(t,i,r))return Wp(e,t,n,Jp(e,t,i,r));return r}function Pne(e,t,n,r){let i=Wp(e,t,n,r);for(let r of n.anyOf){let n=Jp(e,t,r,vp(i));if(op(t,r,n))return n}return i}function Fne(e,t,n,r){return B(e,`Decode`)?Nne(e,t,n,r):Pne(e,t,n,r)}function Jp(e,t,n,r){return ft(n)?vne(e,t,n,r):ue(n)?yne(e,t,n,r):Ee(n)?Sne(e,t,n,r):le(n)?Tne(e,t,n,r):Je(n)?One(e,t,n,r):M(n)?kne(e,t,n,r):Le(n)?Mne(e,t,n,r):T(n)?Fne(e,t,n,r):Wp(e,t,n,r)}var Ine=class extends cp{constructor(e,t){super(`Decode`,e,t)}};function Lne(e,t,n){if(!op(e,t,n))throw new Ine(n,sp(e,t,n));return n}function Rne(e,t,n){return Jp(`Decode`,e,st().unionPrioritySort?Ep(t):t,n)}const zne=Up([(e,t,n)=>vp(n),(e,t,n)=>Hp(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>Lne(e,t,n),(e,t,n)=>Rne(e,t,n)]);function Bne(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return zne(t,n,r)}var Vne=class extends cp{constructor(e,t){super(`Encode`,e,t)}};function Hne(e,t,n){if(!op(e,t,n))throw new Vne(n,sp(e,t,n));return n}function Une(e,t,n){return Jp(`Encode`,e,st().unionPrioritySort?Ep(t):t,n)}const Wne=Up([(e,t,n)=>vp(n),(e,t,n)=>Une(e,t,n),(e,t,n)=>Hp(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>Hne(e,t,n)]);function Gne(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Wne(t,n,r)}function Kne(e,t){return wt(t)||Xp(e,t.items)}function qne(e,t){return wt(t)||Yp({...e,...t.$defs},b(t.$ref))}function Jne(e,t){return wt(t)||t.allOf.some(t=>Xp(e,t))}function Yne(e,t){return wt(t)||k(t.properties).some(n=>Xp(e,t.properties[n]))}function Xne(e,t){return wt(t)||Xp(e,Ct(t))}function Yp(e,t){return!Zp.has(t.$ref)&&(Zp.add(t.$ref),wt(t)||z(e,t.$ref)&&Xp(e,e[t.$ref]))}function Zne(e,t){return wt(t)||t.items.some(t=>Xp(e,t))}function Qne(e,t){return wt(t)||t.anyOf.some(t=>Xp(e,t))}function Xp(e,t){return ft(t)?Kne(e,t):ue(t)?qne(e,t):Ee(t)?Jne(e,t):le(t)?Yne(e,t):Je(t)?Xne(e,t):M(t)?Yp(e,t):Le(t)?Zne(e,t):T(t)?Qne(e,t):wt(t)}const Zp=new Set;function $ne(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Zp.clear(),Xp(t,n)}var Qp=class extends Error{constructor(e,t){super(t),this.type=e}};function ere(e,t){return St(t.default)?t.default(t):x(t.default)?vp(t.default):t.default}function tre(e,t){if(Ss(t)&&!Lo(t))throw new Qp(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=as(t)?t.minItems:0;return Array.from({length:n},()=>dm(e,t.items))}function nre(e,t){return Ko(t)?BigInt(t.exclusiveMinimum)+BigInt(1):rs(t)?BigInt(t.minimum):BigInt(0)}function rre(e,t){return!1}function ire(e,t){let n=dm(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function $p(e,t){return dm({...e,...t.$defs},b(t.$ref))}function em(e,t){return dm(e,nt(t))}function tm(e,t){let n=dm(e,t.returnType);return()=>n}function nm(e,t){return Ko(t)&&$e(t.exclusiveMinimum)?t.exclusiveMinimum+1:rs(t)?t.minimum:0}function rm(e,t){let n=gt(e,t);return dm(e,nt(n))}function im(e,t){return t.const}function am(e,t){throw new Qp(t,`Cannot create TNever types`)}function are(e,t){return null}function ore(e,t){return Ko(t)&&$e(t.exclusiveMinimum)?t.exclusiveMinimum+1:rs(t)?t.minimum:0}function sre(e,t){return(ve(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:dm(e,t.properties[r])}),{})}function cre(e,t){if(ss(t)&&!Lo(t))throw new Qp(t,`Record with the minProperties constraint must have a default annotation`);return{}}function lre(e,t){return z(e,t.$ref)?dm(e,e[t.$ref]):(()=>{throw new Qp(t,`Unable to deref Ref`)})()}function om(e,t){if((ds(t)||qo(t))&&!Lo(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=os(t)?t.minLength:0;return``.padEnd(n)}function sm(e,t){return Symbol()}function cm(e,t){let n=Ce(t.pattern);if(we(n))throw new Qp(t,`Unable to create TemplateLiteral due to infinite type expansion`);return dm(e,n)}function lm(e,t){return Array.from({length:t.minItems},(n,r)=>dm(e,t.items[r]))}function um(e,t){if(B(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return dm(e,t.anyOf[0])}function dm(e,t){return Lo(t)?ere(e,t):ft(t)?tre(e,t):Se(t)?nre(e,t):fe(t)?rre(e,t):iee(t)?ire(e,t):ue(t)?$p(e,t):ae(t)?em(e,t):He(t)?tm(e,t):ce(t)?nm(e,t):Ee(t)?rm(e,t):S(t)?im(e,t):je(t)?am(e,t):et(t)?are(e,t):_e(t)?ore(e,t):le(t)?sre(e,t):Je(t)?cre(e,t):M(t)?lre(e,t):we(t)?om(e,t):ee(t)?sm(e,t):We(t)?cm(e,t):Le(t)?lm(e,t):at(t)?void 0:T(t)?um(e,t):(ut(t),void 0)}function fm(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return dm(t,n)}var pm=class extends cp{constructor(e,t){super(`Parse`,e,t)}};function mm(e,t,n){if(!op(e,t,n))throw new pm(n,sp(e,t,n));return n}const hm=Up([(e,t,n)=>vp(n),(e,t,n)=>Hp(e,t,n),(e,t,n)=>Bp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>mm(e,t,n)]),gm=ke({type:ie(`insert`),path:re(),value:dt()}),_m=Object({type:ie(`update`),path:re(),value:dt()}),vm=ke({type:ie(`delete`),path:re()});bt([gm,_m,vm]);var ym=class{constructor(e,t){this.hasCodec=$ne(e,t),this.buildResult=rp(e,t),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(st().correctiveParse)return hm(this.Context(),this.Type(),e);throw new pm(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:sp(this.Context(),this.Type(),e)}Clean(e){return Dp(this.Context(),this.Type(),e)}Convert(e){return Bp(this.Context(),this.Type(),e)}Create(){return fm(this.Context(),this.Type())}Default(e){return Hp(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?Bne(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Gne(this.Context(),this.Type(),e):this.Parse(e)}};function bm(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new ym(t,n)}const xm=new WeakMap,Sm=Symbol.for(`TypeBox.Kind`);function Cm(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function wm(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function Tm(e){try{return Mm(e)}catch{return}}function Em(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function Dm(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=Am(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Am(i,t.additionalProperties))}function Om(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Am(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Am(e[n],t.items)}function km(e,t){for(let n of t)if(Tm(n)?.Check(e))return e;for(let n of t){let t=Am(structuredClone(e),n);if(Tm(n)?.Check(t))return t}return e}function Am(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Am(n,e);Array.isArray(t.anyOf)&&(n=km(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=km(n,t.oneOf));let r=Cm(t),i=r.length>1&&r.some(e=>wm(n,e));if(r.length>0&&!i)for(let e of r){let t=Em(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Dm(n,t),r.includes(`array`)&&Array.isArray(n)&&Om(n,t),n}function jm(e,t){if(Array.isArray(e)){if(Array.isArray(t.items))for(let n=0;n<e.length;n++){let r=t.items[n];r&&jm(e[n],r)}else if(t.items)for(let n of e)jm(n,t.items);return}if(typeof e!=`object`||!e||!t.properties)return;let n=e,r=new Set(t.required??[]);for(let[e,i]of Object.entries(t.properties))e in n&&(n[e]===null&&!r.has(e)&&typeof i.$ref!=`string`&&Tm(i)?.Check(null)===!1?delete n[e]:jm(n[e],i))}function Mm(e){let t=e,n=xm.get(t);if(n)return n;let r=bm(e);return xm.set(t,r),r}function ure(e){if(e.keyword===`required`){let t=e.params.requiredProperties?.[0];if(t){let n=e.instancePath.replace(/^\//,``).replace(/\//g,`.`);return n?`${n}.${t}`:t}}return e.instancePath.replace(/^\//,``).replace(/\//g,`.`)||`root`}function dre(e,t){let n=structuredClone(t.arguments);jm(n,e.parameters),Bp(e.parameters,n);let r=Mm(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Sm)){let t=Am(n,e.parameters);if(t!==n)if(typeof n==`object`&&n&&typeof t==`object`&&t){for(let e of Object.keys(n))delete n[e];Object.assign(n,t)}else return r.Check(t)?t:n}if(r.Check(n))return n;let i=r.Errors(n).map(e=>` - ${ure(e)}: ${e.message}`).join(`
|
|
879
|
+
}`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??Vi(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0))}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}addExecutionContextListeners(e){e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeExecutionContextListeners(e){e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.removeExecutionContextListeners(this.client),this.client=e,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function nte(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function Hi(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)Hi(n,t)}function Ui(e){let t={role:Ri(e.role,`unknown`),name:Ri(e.name)},n=Ri(e.value);n!==``&&(t.value=n);let r=Ri(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>Ui(e)).filter(e=>e.role!==`unknown`)),t}const Wi=r(`panel-rpc-cdp`);var rte=class{getPanelRpc;runtimeId;localTargetId;timeoutMs;eventListeners=new Map;pendingOnce=new Set;key;_state=`connected`;pushRegistered=!1;constructor(e,t,n,r=3e4){this.getPanelRpc=e,this.runtimeId=t,this.localTargetId=n,this.timeoutMs=r,this.key=`${t}:${n}`}get state(){return this._state}async connect(){}disconnect(){this._state=`disconnected`;for(let e of this.pendingOnce)clearTimeout(e.timer),e.reject(Error(`Transport disconnected`));this.pendingOnce.clear();let e=this.getPanelRpc();e&&(this.pushRegistered&&=(e.unregisterPushTarget(this.key),!1),e.call(`remote-cdp-detach`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId}).catch(e=>{Wi.error(`remote-cdp detach failed (page-side session may leak)`,{key:this.key,error:e instanceof Error?e.message:String(e)})})),this.eventListeners.clear()}async send(e,t,n,r){if(this._state===`disconnected`)throw Error(`Transport disconnected`);let i=this.getPanelRpc();if(!i)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let a=r??this.timeoutMs,s=Math.max(a,o)+5e3;return i.call(`remote-cdp-send`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,method:e,params:t,sessionId:n,timeout:a},{timeoutMs:s})}on(e,t){let n=this.eventListeners.get(e),r=!n||n.size===0;n||(n=new Set,this.eventListeners.set(e,n)),n.add(t),r&&this.subscribe(e)}off(e,t){let n=this.eventListeners.get(e);n&&(n.delete(t),n.size===0&&(this.eventListeners.delete(e),this.unsubscribe(e)))}once(e,t){return new Promise((n,r)=>{let i=t??this.timeoutMs,a={reject:r,timer:void 0},o=()=>{clearTimeout(a.timer),this.pendingOnce.delete(a),this.off(e,s)};a.timer=setTimeout(()=>{o(),r(Error(`Remote CDP event timed out: ${e}`))},i);let s=e=>{o(),n(e)};this.pendingOnce.add(a),this.on(e,s)})}handleEvent(e,t){let n=this.eventListeners.get(e);if(n)for(let e of[...n])e(t)}ensurePushRegistered(e){this.pushRegistered||=(e.registerPushTarget(this.key,e=>this.handleEvent(e.method,e.params??{})),!0)}subscribe(e){let t=this.getPanelRpc();if(!t){Wi.error(`remote-cdp subscribe skipped: no panel-RPC client`,{key:this.key,event:e});return}this.ensurePushRegistered(t),t.call(`remote-cdp-subscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Wi.error(`remote-cdp subscribe failed; events for this transport will not arrive`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}unsubscribe(e){let t=this.getPanelRpc();t&&t.call(`remote-cdp-unsubscribe`,{runtimeId:this.runtimeId,localTargetId:this.localTargetId,event:e}).catch(t=>{Wi.error(`remote-cdp unsubscribe failed (page-side forwarder may leak)`,{key:this.key,event:e,error:t instanceof Error?t.message:String(t)})})}};function ite(e){let t=new Map,n=(e,t)=>`${e}:${t}`;return{getTargets(){return[]},createRemoteTransport(r,i){let a=n(r,i),o=t.get(a);return o||(o=new rte(e,r,i),t.set(a,o)),o},removeRemoteTransport(e,r){let i=n(e,r),a=t.get(i);a&&(a.disconnect(),t.delete(i))},async openRemoteTab(t,n){let r=e();if(!r)throw Error(`cdp: no page bridge to the leader tray (panel-RPC client)`);let{targetId:i}=await r.call(`remote-open-tab`,{runtimeId:t,url:n});return i}}}const Gi=Object.freeze([Object.freeze({id:`experimental-settings`,label:`Experimental settings`,description:`Show controls for experimental features.`,defaultValue:`on`,floatDefaults:Object.freeze({cherry:`off`}),userToggleable:!1}),Object.freeze({id:`panel-layouts`,label:`Panel layouts`,description:`Arrange the UI as movable, resizable panels instead of the fixed workbench.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`agentic-memory`,label:`Agentic memory`,description:`Curate session memory with a background agent instead of a one-shot extraction call.`,defaultValue:`off`,userToggleable:!0}),Object.freeze({id:`multiple-cones`,label:`Multiple cones`,description:`Add, switch between and remove cones from the freezer rail. Extra cones share the workspace.`,defaultValue:`off`,userToggleable:!0})]);new Map(Gi.map(e=>[e.id,e]));const ate=new Set([`1`,`on`,`true`]);let Ki=`standalone`,qi={},Ji={};function Yi(e,t={},n=Xi()){let r={};for(let i of Gi){let a=n[i.id];if(typeof a==`string`&&na(i,e)){r[i.id]=a;continue}let o=Ji[i.id];if(typeof o==`string`&&na(i,e)){r[i.id]=o;continue}let s=t[i.id];r[i.id]=typeof s==`string`?s:ta(i,e)}return r}function Xi(){try{let e=ia()?.getItem(`slicc_feature_flags`);return e?ra(JSON.parse(e)):{}}catch{return{}}}function Zi(e,t={}){Ki=e,qi=ra(t),Ji={}}function Qi(e){return Yi(Ki,qi)[e]}function $i(e){return typeof e==`string`&&ate.has(e.trim().toLowerCase())}function ea(e){return $i(Qi(e))}function ta(e,t){return e.floatDefaults?.[t]??e.defaultValue}function na(e,t){return e.userToggleable&&(e.overridableFloats===void 0||e.overridableFloats.includes(t))}function ra(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t=e,n={};for(let e of Gi){let r=t[e.id];typeof r==`string`&&(n[e.id]=r)}return n}function ia(){try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function aa(e){return`slicc_feature_flags_remote:${e}`}function oa(e,t){Zi(e,ca(sa(t),e)??{})}function sa(e){if(e!==void 0)return e;try{let e=globalThis.localStorage;return typeof e?.getItem!=`function`||typeof e.setItem!=`function`?void 0:e}catch{return}}function ca(e,t){try{let n=e?.getItem(aa(t));return n?la(JSON.parse(n)):null}catch{return null}}function la(e){return!ua(e)||Object.values(e).some(e=>typeof e!=`string`)?null:e}function ua(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const da=r(`stale-asset`),fa=/dynamically imported module|importing a module script failed|expected a javascript module|module script/i;function pa(e){return fa.test(e)}let ma=null;function ha(e){if(!e){ma=null;return}ma=e}function ga(e=!1){if(!ma||typeof BroadcastChannel!=`function`)return;let t=new BroadcastChannel(`slicc-stale-asset-reload`);try{t.postMessage({type:`stale-asset-reload`,instanceId:ma,replayTurn:e})}finally{t.close()}}function _a(e){pa(e instanceof Error?e.message:String(e))&&ga()}function va(e,t){return!e||e===t?!1:(da.warn(`mixed build graph: page ${e} vs worker ${t} — requesting reload`),ga(),!0)}var ya=class{_state=`disconnected`;nextCommandId=1;listeners=new Map;pendingCommands=new Ai;unsubscribe=null;opts;label;constructor(e){this.opts=e,this.label=e.label??`CDP transport`}get state(){return this._state}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);this.unsubscribe=this.opts.subscribeIncoming(e=>this.handleIncoming(e)),this._state=`connected`}disconnect(){this.unsubscribe?.(),this.unsubscribe=null,this.pendingCommands.rejectAll(`${this.label} disconnected`),this.listeners.clear(),this._state=`disconnected`}async send(e,t,n,r=3e4){if(this._state!==`connected`)throw Error(`${this.label} is not connected`);let i=this.nextCommandId++,a=this.opts.buildCommandEnvelope(i,e,t,n),o=this.pendingCommands.issue(i,r,`CDP command timed out after ${r}ms: ${e}`);return this.opts.sendEnvelope(a).catch(e=>{this.pendingCommands.reject(i,Error(`Failed to send CDP command: ${e instanceof Error?e.message:String(e)}`))}),o}on(e,t){let n=this.listeners.get(e),r=!n;n||(n=new Set,this.listeners.set(e,n)),n.add(t),r&&this.opts.onSubscribeEvent?.(e)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&(this.listeners.delete(e),this.opts.onUnsubscribeEvent?.(e)))}once(e,t=3e4){return ji(t=>(this.on(e,t),()=>this.off(e,t)),t,`Timed out waiting for event: ${e}`)}handleIncoming(e){let t=this.opts.parseResponse(e);if(t){this.handleResponse(t);return}let n=this.opts.parseEvent(e);n&&this.handleEvent(n)}handleResponse(e){if(!this.pendingCommands.has(e.id)){this.opts.onUnknownResponseId?.(e.id);return}e.error?this.pendingCommands.reject(e.id,Error(e.error)):this.pendingCommands.resolve(e.id,e.result??{})}handleEvent(e){let t=this.listeners.get(e.method);if(t)for(let n of t)try{n(e.params??{})}catch(t){this.opts.onListenerError?.(e.method,t)}}};function ba(e){let t=!1,n=()=>{t||(t=!0,typeof e.start==`function`&&e.start())};return{onMessage:t=>{let r=e=>{t(e.data)};return e.addEventListener(`message`,r),n(),()=>{e.removeEventListener(`message`,r)}},send:(t,n)=>{n&&n.length>0?e.postMessage(t,n):e.postMessage(t)}}}function xa(e){let t=ba(e);return{onMessage:e=>t.onMessage(e),send:(e,n)=>{t.send({source:`offscreen`,payload:e},n)}}}var Sa=class extends ya{constructor(e){let t=ba(e);super({label:`WorkerCdpProxy`,buildCommandEnvelope:(e,t,n,r)=>({type:`cdp-cmd`,id:e,method:t,params:n,sessionId:r}),sendEnvelope:e=>(t.send(e),Promise.resolve()),subscribeIncoming:e=>t.onMessage(e),parseResponse:e=>{let t=e;if(t?.type!==`cdp-response`)return null;if(typeof t.id!=`number`||!Number.isFinite(t.id))return console.warn(`[WorkerCdpProxy] dropping cdp-response with invalid id`,t),null;let n=e;return{id:n.id,result:n.result,error:n.error}},parseEvent:e=>{let t=e;if(t?.type!==`cdp-event`)return null;if(typeof t.method!=`string`)return console.warn(`[WorkerCdpProxy] dropping cdp-event with invalid method`,t),null;let n=e;return{method:n.method,params:n.params}},onSubscribeEvent:e=>{t.send({type:`cdp-subscribe`,event:e})},onUnsubscribeEvent:e=>{t.send({type:`cdp-unsubscribe`,event:e})}})}};function Ca(e,t){return e.find(e=>e.folder===t)??e.find(e=>e.folder===`${t}-scoop`)??e.find(e=>e.name===t)}const wa=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function Ta(e){return wa.test(e)}function Ea(e,t){return`(${e} && ${t})`}function Da(e,t){return`(${e} || ${t})`}function Oa(e){return`!(${e})`}function ka(e){return`Array.isArray(${e})`}function Aa(e){return`typeof ${e} === "bigint"`}function ja(e){return`typeof ${e} === "boolean"`}function Ma(e){return`Number.isInteger(${e})`}function Na(e){return`${e} === null`}function Pa(e){return`Number.isFinite(${e})`}function Fa(e){return Ea(Ia(e),Oa(ka(e)))}function Ia(e){return`typeof ${e} === "object" && ${e} !== null`}function La(e){return`typeof ${e} === "string"`}function Ra(e){return`typeof ${e} === "symbol"`}function za(e){return`${e} === undefined`}function Ba(e){return`typeof ${e} === "function"`}function Va(e){return`Guard.IsConstructor(${e})`}function Ha(e,t){return`${e} === ${t}`}function Ua(e,t){return`${e} > ${t}`}function Wa(e,t){return`${e} < ${t}`}function Ga(e,t){return`${e} <= ${t}`}function Ka(e,t){return`${e} >= ${t}`}function qa(e,t){return`Guard.IsMinLength(${e}, ${t})`}function Ja(e,t){return`Guard.IsMaxLength(${e}, ${t})`}function Ya(e,t,n,r){return B(t,`0`)?`${e}.every((${n[0]}, ${n[1]}) => ${r})`:`((value, callback) => { for(let index = ${t}; index < value.length; index++) if (!callback(value[index], index)) return false; return true })(${e}, (${n[0]}, ${n[1]}) => ${r})`}function Xa(e){return`Object.entries(${e})`}function Za(e){return`Object.getOwnPropertyNames(${e})`}function Qa(e,t){return B(t,`"__proto__"`)||B(t,`"constructor"`)?`Object.prototype.hasOwnProperty.call(${e}, ${t})`:`${t} in ${e}`}function $a(e,t){return`Guard.IsDeepEqual(${e}, ${t})`}function eo(e){return`[${e.join(`, `)}]`}function to(e,t){return`((${e.join(`, `)}) => ${t})`}function no(e,t){return`${e}(${t.join(`, `)})`}function ro(e,t){return`new ${e}(${t.join(`, `)})`}function H(e,t){return`${e}${Ta(t)?`.${t}`:`[${U(t)}]`}`}function U(e){return j(e)?JSON.stringify(e):`${e}`}function io(e,t,n){return`(${e} ? ${t} : ${n})`}function ao(e){return`{ ${e.join(`; `)}; }`}function oo(e,t){return`const ${e} = ${t}`}function so(e,t){return`if(${e}) { ${t} }`}function co(e){return`return ${e}`}function lo(e){return B(e.length,0)?`true`:e.reduce((e,t)=>Ea(e,t))}function uo(e){return B(e.length,0)?`false`:e.reduce((e,t)=>Da(e,t))}function fo(e){return`++${e}`}function po(e,t){return`Guard.IsMultipleOf(${e}, ${t})`}var mo=xe;function ho(e,t){return t[e.length]?.(...e)??(()=>{throw Error(`Invalid Arguments`)})()}let go;function _o(){try{return yo(`null`)(),!0}catch{return!1}}function vo(){return ve(go)&&(go=_o()),go&&st().useAcceleration}function yo(...e){return new globalThis.Function(...e)}function bo(e){switch(e.keyword){case`additionalProperties`:return`must not have additional properties`;case`anyOf`:return`must match a schema in anyOf`;case`boolean`:return`schema is false`;case`const`:return`must be equal to constant`;case`contains`:return`must contain at least 1 valid item`;case`dependencies`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`dependentRequired`:return`must have properties ${e.params.dependencies.join(`, `)} when property ${e.params.property} is present`;case`enum`:return`must be equal to one of the allowed values`;case`exclusiveMaximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`exclusiveMinimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`format`:return`must match format "${e.params.format}"`;case`if`:return`must match "${e.params.failingKeyword}" schema`;case`maxItems`:return`must not have more than ${e.params.limit} items`;case`maxLength`:return`must not have more than ${e.params.limit} characters`;case`maxProperties`:return`must not have more than ${e.params.limit} properties`;case`maximum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`minItems`:return`must not have fewer than ${e.params.limit} items`;case`minLength`:return`must not have fewer than ${e.params.limit} characters`;case`minProperties`:return`must not have fewer than ${e.params.limit} properties`;case`minimum`:return`must be ${e.params.comparison} ${e.params.limit}`;case`multipleOf`:return`must be multiple of ${e.params.multipleOf}`;case`not`:return`must not be valid`;case`oneOf`:return`must match exactly one schema in oneOf`;case`pattern`:return`must match pattern "${e.params.pattern}"`;case`propertyNames`:return`property names ${e.params.propertyNames.join(`, `)} are invalid`;case`required`:return`must have required properties ${e.params.requiredProperties.join(`, `)}`;case`type`:return typeof e.params.type==`string`?`must be ${e.params.type}`:`must be either ${e.params.type.join(` or `)}`;case`unevaluatedItems`:return`must not have unevaluated items`;case`unevaluatedProperties`:return`must not have unevaluated properties`;case`uniqueItems`:return`must not have duplicate items`;case`~refine`:return e.params.message;default:return`an unknown validation error occurred`}}let xo=bo;function So(){return xo}const Co=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i],wo=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function To(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!wo.some(t=>t.test(e.errorMessage))&&Co.some(t=>t.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function Eo(e){return z(e,`~refine`)&<(e[`~refine`])&&ht(e[`~refine`],0,e=>x(e)&&z(e,`check`)&&z(e,`error`)&&St(e.check)&&St(e.error))}function Do(e){return x(e)&&!lt(e)}function Oo(e){return qe(e)}function ko(e){return Do(e)||Oo(e)}function Ao(e){return z(e,`additionalItems`)&&ko(e.additionalItems)}function jo(e){return z(e,`additionalProperties`)&&ko(e.additionalProperties)}function Mo(e){return z(e,`allOf`)&<(e.allOf)&&e.allOf.every(e=>ko(e))}function No(e){return z(e,`$anchor`)&&j(e.$anchor)}function Po(e){return z(e,`anyOf`)&<(e.anyOf)&&e.anyOf.every(e=>ko(e))}function Fo(e){return z(e,`const`)}function Io(e){return z(e,`contains`)&&ko(e.contains)}function Lo(e){return z(e,`default`)}function Ro(e){return z(e,`dependencies`)&&x(e.dependencies)&&Object.values(e.dependencies).every(e=>ko(e)||lt(e)&&e.every(e=>j(e)))}function zo(e){return z(e,`dependentRequired`)&&x(e.dependentRequired)&&Object.values(e.dependentRequired).every(e=>lt(e)&&e.every(e=>j(e)))}function Bo(e){return z(e,`dependentSchemas`)&&x(e.dependentSchemas)&&Object.values(e.dependentSchemas).every(e=>ko(e))}function Vo(e){return z(e,`$dynamicAnchor`)&&j(e.$dynamicAnchor)}function Ho(e){return z(e,`$dynamicRef`)&&j(e.$dynamicRef)}function Uo(e){return z(e,`else`)&&ko(e.else)}function Wo(e){return z(e,`enum`)&<(e.enum)}function Go(e){return z(e,`exclusiveMaximum`)&&($e(e.exclusiveMaximum)||it(e.exclusiveMaximum))}function Ko(e){return z(e,`exclusiveMinimum`)&&($e(e.exclusiveMinimum)||it(e.exclusiveMinimum))}function qo(e){return z(e,`format`)&&j(e.format)}function Jo(e){return z(e,`$id`)&&j(e.$id)}function Yo(e){return z(e,`if`)&&ko(e.if)}function Xo(e){return z(e,`items`)&&(ko(e.items)||lt(e.items)&&e.items.every(e=>ko(e)))}function Zo(e){return Xo(e)&<(e.items)}function Qo(e){return z(e,`maximum`)&&($e(e.maximum)||it(e.maximum))}function $o(e){return z(e,`maxContains`)&&$e(e.maxContains)}function es(e){return z(e,`maxItems`)&&$e(e.maxItems)}function ts(e){return z(e,`maxLength`)&&$e(e.maxLength)}function ns(e){return z(e,`maxProperties`)&&$e(e.maxProperties)}function rs(e){return z(e,`minimum`)&&($e(e.minimum)||it(e.minimum))}function is(e){return z(e,`minContains`)&&$e(e.minContains)}function as(e){return z(e,`minItems`)&&$e(e.minItems)}function os(e){return z(e,`minLength`)&&$e(e.minLength)}function ss(e){return z(e,`minProperties`)&&$e(e.minProperties)}function cs(e){return z(e,`multipleOf`)&&($e(e.multipleOf)||it(e.multipleOf))}function ls(e){return z(e,`not`)&&ko(e.not)}function us(e){return z(e,`oneOf`)&<(e.oneOf)&&e.oneOf.every(e=>ko(e))}function ds(e){return z(e,`pattern`)&&(j(e.pattern)||e.pattern instanceof RegExp)}function fs(e){return z(e,`patternProperties`)&&x(e.patternProperties)&&Object.values(e.patternProperties).every(e=>ko(e))}function ps(e){return z(e,`prefixItems`)&<(e.prefixItems)&&e.prefixItems.every(e=>ko(e))}function ms(e){return z(e,`properties`)&&x(e.properties)&&Object.values(e.properties).every(e=>ko(e))}function hs(e){return z(e,`propertyNames`)&&(x(e.propertyNames)||ko(e.propertyNames))}function ote(e){return z(e,`$recursiveAnchor`)&&qe(e.$recursiveAnchor)}function gs(e){return ote(e)&&B(e.$recursiveAnchor,!0)}function _s(e){return z(e,`$recursiveRef`)&&j(e.$recursiveRef)}function vs(e){return z(e,`$ref`)&&j(e.$ref)}function ys(e){return z(e,`required`)&<(e.required)&&e.required.every(e=>j(e))}function bs(e){return z(e,`then`)&&ko(e.then)}function xs(e){return z(e,`type`)&&(j(e.type)||lt(e.type)&&e.type.every(e=>j(e)))}function Ss(e){return z(e,`uniqueItems`)&&qe(e.uniqueItems)}function Cs(e){return z(e,`unevaluatedItems`)&&ko(e.unevaluatedItems)}function ws(e){return z(e,`unevaluatedProperties`)&&ko(e.unevaluatedProperties)}function ste(e){return Cs(e)||ws(e)||k(e).some(t=>Ts(e[t]))}function cte(e){return e.some(e=>Ts(e))}function Ts(e){return lt(e)?cte(e):x(e)?ste(e):!1}function lte(e,t){return Ts(t)||k(e).some(t=>Ts(e[t]))}var ute=class{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return no(H(`context`,`Push`),[])}Pop(){return no(H(`context`,`Pop`),[])}AddIndex(e){return no(H(`context`,`AddIndex`),[e])}AddKey(e){return no(H(`context`,`AddKey`),[e])}Merge(e){return no(H(`context`,`Merge`),[e])}},Es=class{constructor(){let e=new Set,t=new Set;this.stack=[{indices:e,keys:t}]}Push(){let e=new Set,t=new Set;return this.stack.push({indices:e,keys:t}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let t of e)t.GetIndices().forEach(e=>this.GetIndices().add(e)),t.GetKeys().forEach(e=>this.GetKeys().add(e));return!0}},Ds=class extends Es{constructor(e){super(),this.callback=e}AddError(e){return this.callback(e),!1}},Os=class extends Ds{constructor(){super(e=>this.errors.push(e)),this.errors=[]}AddError(e){return this.errors.push(e),!1}GetErrors(){return this.errors}};const ks={identifier:`External`,variables:[]};function As(e){let t=`External[${ks.variables.length}]`;return ks.variables.push(e),t}function js(){ks.variables=[]}function Ms(){return{...ks}}function Ns(e,t,n,r){return Ya(As(n[`~refine`].map(e=>e)),U(0),[`refinement`,`_`],no(H(`refinement`,`check`),[r]))}function Ps(e,t,n,r){return ht(n[`~refine`],0,(e,t)=>e.check(r))}function Fs(e,t,n,r,i,a){return Be(i[`~refine`],0,(e,i)=>e.check(a)||t.AddError({keyword:`~refine`,schemaPath:n,instancePath:r,params:{index:i,message:e.error(a)}}))}let Is=0;function Ls(){return`var_${Is++}`}function Rs(e){return Xo(e)&<(e.items)}function zs(e,t,n,r){if(!Rs(n))return U(!0);let[i,a]=[Ls(),Ls()],o=mf(e,t,n.additionalItems,i),s=Wa(a,U(n.items.length)),c=t.AddIndex(a),l=t.UseUnevaluated()?Da(s,Ea(o,c)):Da(s,o);return no(H(r,`every`),[to([i,a],l)])}function Bs(e,t,n,r){return!Rs(n)||r.every((r,i)=>yt(i,n.items.length)||gf(e,t,n.additionalItems,r)&&t.AddIndex(i))}function Vs(e,t,n,r,i,a){return!Rs(i)||a.every((a,o)=>{let s=`${n}/additionalItems`,c=`${r}/${o}`;return yt(o,i.items.length)||vf(e,t,s,c,i.additionalItems,a)&&t.AddIndex(o)})}function Hs(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`}function Us(e){let t=[];return fs(e)&&t.push(...k(e.patternProperties)),ms(e)&&t.push(...k(e.properties).map(Hs)),B(t.length,0)?`(?!)`:`(${t.join(`|`)})`}function Ws(e,t,n){return ys(t)&&ms(t)&&!fs(t)&&B(t.additionalProperties,!1)&&B(k(t.properties).length,t.required.length)}function Gs(e,t,n){return Ha(H(no(H(`Object`,`getOwnPropertyNames`),[n]),`length`),U(t.required.length))}function Ks(e,t,n,r){let[i,a]=[Ls(),Ls()],o=As(new RegExp(Us(n))),s=mf(e,t,n.additionalProperties,`${r}[${i}]`),c=no(H(o,`test`),[i]),l=t.AddKey(i),u=t.UseUnevaluated()?Da(c,Ea(s,l)):Da(c,s);return Ya(Za(r),U(0),[i,a],u)}function qs(e,t,n,r){return Ws(t,n,r)?Gs(t,n,r):Ks(e,t,n,r)}function Js(e,t,n,r){let i=new RegExp(Us(n));return ht(k(r),0,(a,o)=>i.test(a)||gf(e,t,n.additionalProperties,r[a])&&t.AddKey(a))}function Ys(e,t,n,r,i,a){let o=new RegExp(Us(i)),s=[];return Be(k(a),0,(c,l)=>{let u=`${n}/additionalProperties`,d=`${r}/${c}`,f=new Os,p=o.test(c)||vf(e,f,u,d,i.additionalProperties,a[c])&&t.AddKey(c);return p||s.push(c),p})||t.AddError({keyword:`additionalProperties`,schemaPath:n,instancePath:r,params:{additionalProperties:s}})}function Xs(e,t,n,r,i){let a=oo(`results`,`[]`),o=n.map((e,t)=>oo(`context_${t}`,ro(`CheckContext`,[]))),s=n.map((n,i)=>oo(`condition_${i}`,no(to([`context`],hf(e,t,n,r)),[`context_${i}`]))),c=n.map((e,t)=>so(`condition_${t}`,no(H(`results`,`push`),[`context_${t}`]))),l=co(Ea(i,t.Merge(`results`)));return no(to([],ao([a,...o,...s,...c,l])),[])}function Zs(e,t,n,r){return Xs(e,t,n.allOf,r,Ha(H(`results`,`length`),U(n.allOf.length)))}function Qs(e,t,n,r){return lo(n.allOf.map(n=>hf(e,t,n,r)))}function $s(e,t,n,r){return t.UseUnevaluated()?Zs(e,t,n,r):Qs(e,t,n,r)}function ec(e,t,n,r){let i=n.allOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return B(i.length,n.allOf.length)&&t.Merge(i)}function tc(e,t,n,r,i,a){let o=[],s=i.allOf.reduce((t,i,s)=>{let c=`${n}/allOf/${s}`,l=new Os,u=yf(e,l,c,r,i,a);return u||o.push(l),u?[...t,l]:t},[]),c=B(s.length,i.allOf.length)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c}function nc(e,t,n,r){return Xs(e,t,n.anyOf,r,Ua(H(`results`,`length`),U(0)))}function rc(e,t,n,r){return uo(n.anyOf.map(n=>hf(e,t,n,r)))}function ic(e,t,n,r){return t.UseUnevaluated()?nc(e,t,n,r):rc(e,t,n,r)}function ac(e,t,n,r){let i=n.anyOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return xt(i.length,0)&&t.Merge(i)}function oc(e,t,n,r,i,a){let o=[],s=i.anyOf.reduce((t,i,s)=>{let c=new Os,l=yf(e,c,`${n}/anyOf/${s}`,r,i,a);return l||o.push(c),l?[...t,c]:t},[]),c=xt(s.length,0)&&t.Merge(s);return c||o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),c||t.AddError({keyword:`anyOf`,schemaPath:n,instancePath:r,params:{}})}function sc(e,t,n,r){return U(!!n)}function cc(e,t,n,r){return n}function lc(e,t,n,r,i,a){return cc(e,t,i,a)||t.AddError({keyword:`boolean`,schemaPath:n,instancePath:r,params:{}})}function uc(e,t,n,r){return se(n.const)?Ha(r,U(n.const)):$a(r,As(n.const))}function dc(e,t,n,r){return se(n.const)?B(r,n.const):Me(r,n.const)}function fc(e,t,n,r,i,a){return dc(e,t,i,a)||t.AddError({keyword:`const`,schemaPath:n,instancePath:r,params:{allowedValue:i.const}})}function pc(e){return!(is(e)&&B(e.minContains,0))}function mc(e,t,n,r){if(!pc(n))return U(!0);let i=Ls();return Ea(Oa(Ha(H(r,`length`),U(0))),no(H(r,`some`),[to([i],hf(e,t,n.contains,i))]))}function hc(e,t,n,r){return!pc(n)||!B(r.length,0)&&r.some(r=>_f(e,t,n.contains,r))}function gc(e,t,n,r,i,a){return hc(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:1}})}function _c(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependencies).map(([n,i])=>{let a=Oa(Qa(r,U(n))),o=hf(e,t,i,r);return Da(a,lt(i)?(e=>lo(e.map(e=>Qa(r,U(e)))))(i):o)})))}function vc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependencies),0,([n,i])=>!z(r,n)||(lt(i)?i.every(e=>z(r,e)):_f(e,t,i,r)));return i||a}function yc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependencies),0,([i,o])=>{let s=`${n}/dependencies/${i}`;return!z(a,i)||(lt(o)?o.every(e=>z(a,e)||t.AddError({keyword:`dependencies`,schemaPath:n,instancePath:r,params:{property:i,dependencies:o}})):yf(e,t,s,r,o,a))});return o||s}function bc(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependentRequired).map(([e,t])=>Da(Oa(Qa(r,U(e))),lo(t.map(e=>Qa(r,U(e))))))))}function xc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependentRequired),0,([e,t])=>!z(r,e)||t.every(e=>z(r,e)));return i||a}function Sc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependentRequired),0,([e,i])=>!z(a,e)||Be(i,0,o=>z(a,o)||t.AddError({keyword:`dependentRequired`,schemaPath:n,instancePath:r,params:{property:e,dependencies:i}})));return o||s}function Cc(e,t,n,r){return Da(Ha(H(Za(r),`length`),U(0)),lo(Re(n.dependentSchemas).map(([n,i])=>Da(Oa(Qa(r,U(n))),hf(e,t,i,r)))))}function wc(e,t,n,r){let i=B(k(r).length,0),a=ht(Re(n.dependentSchemas),0,([n,i])=>!z(r,n)||_f(e,t,i,r));return i||a}function Tc(e,t,n,r,i,a){let o=B(k(a).length,0),s=Be(Re(i.dependentSchemas),0,([i,o])=>{let s=`${n}/dependentSchemas/${i}`;return!z(a,i)||yf(e,t,s,r,o,a)});return o||s}function Ec(e,t,n,r){return kf(e,t,e.DynamicRef(n)??!1,r)}function Dc(e,t,n,r){let i=e.DynamicRef(n)??!1;return ko(i)&&_f(e,t,i,r)}function Oc(e,t,n,r,i,a){let o=e.DynamicRef(i)??!1;return ko(o)&&yf(e,t,`#`,r,o,a)}function kc(e,t,n,r){return uo(n.enum.map(e=>se(e)?Ha(r,U(e)):$a(r,As(e))))}function Ac(e,t,n,r){return n.enum.some(e=>se(e)?B(r,e):Me(r,e))}function jc(e,t,n,r,i,a){return Ac(e,t,i,a)||t.AddError({keyword:`enum`,schemaPath:n,instancePath:r,params:{allowedValues:i.enum}})}function Mc(e,t,n,r){return Wa(r,U(n.exclusiveMaximum))}function Nc(e,t,n,r){return yt(r,n.exclusiveMaximum)}function Pc(e,t,n,r,i,a){return Nc(e,t,i,a)||t.AddError({keyword:`exclusiveMaximum`,schemaPath:n,instancePath:r,params:{comparison:`<`,limit:i.exclusiveMaximum}})}function Fc(e,t,n,r){return Ua(r,U(n.exclusiveMinimum))}function Ic(e,t,n,r){return xt(r,n.exclusiveMinimum)}function Lc(e,t,n,r,i,a){return Ic(e,t,i,a)||t.AddError({keyword:`exclusiveMinimum`,schemaPath:n,instancePath:r,params:{comparison:`>`,limit:i.exclusiveMinimum}})}const Rc=[0,31,28,31,30,31,30,31,31,30,31,30,31],zc=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function Bc(e){return e%4==0&&(e%100!=0||e%400==0)}function Vc(e){let t=zc.exec(e);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r===2&&Bc(n)?29:Rc[r])}const Hc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(?:Z|([+-])(\d\d):(\d\d))?$/i;function Uc(e,t=!0){let n=Hc.exec(e);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4]===`-`?-1:1,s=+(n[5]||0),c=+(n[6]||0);if(s>23||c>59||t&&!n[4]&&e.toLowerCase().indexOf(`z`)===-1)return!1;if(r<=23&&i<=59&&a<60)return!0;let l=i-c*o,u=r-s*o-+(l<0);return(u===23||u===-1)&&(l===59||l===-1)&&a<61}function Wc(e,t=!0){let n=e.split(/T/i);return n.length===2&&Vc(n[0])&&Uc(n[1],t)}const Gc=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function Kc(e){return Gc.test(e)}const qc=/^(?!.*\.\.)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i;function Jc(e){return qc.test(e)}function Yc(e,t,n){e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))}function Xc(e){let t=[],n=128,r=0,i=72,a=e.lastIndexOf(`-`);if(a>0)for(let n=0;n<a;n++){let r=e.charCodeAt(n);if(r>=128)throw Error(`Invalid punycode: non-basic before delimiter`);t.push(r)}let o=a<0?0:a+1;for(;o<e.length;){let a=r,s=1,c=36;for(;;){if(o>=e.length)throw Error(`Invalid punycode: unexpected end of input`);let t=e.charCodeAt(o++),n;if(t>=97&&t<=122)n=t-97;else if(t>=48&&t<=57)n=t-48+26;else if(t>=65&&t<=90)oe();else throw Error(`Invalid punycode: bad digit character`);r+=n*s;let a=c<=i?1:c>=i+26?26:c-i;if(n<a)break;s*=36-a,c+=36}let l=t.length+1;i=Yc(r-a,l,a===0),n+=Math.floor(r/l),r%=l,t.splice(r,0,n),r++}return globalThis.String.fromCodePoint(...t)}function Zc(e){return/\p{Mn}/u.test(String.fromCodePoint(e))}function Qc(e){return/\p{Mc}/u.test(String.fromCodePoint(e))}function $c(e){return/\p{Me}/u.test(String.fromCodePoint(e))}function el(e){return Zc(e)||Qc(e)||$c(e)}const tl=new Set([1600,2042,12334,12335,12337,12338,12339,12340,12341,12347]),nl=new Set([2381,2509,2637,2765,2893,3021,3149,3277,3387,3388,3405,3530,6980,7082,7083,43456,69702,69759,69817,69939,69940,70080,70197,70477,70722,70850,71103,71231,71350,72767,73028,73029]);function rl(e){return/\p{Script=Greek}/u.test(String.fromCodePoint(e))}function il(e){return/\p{Script=Hebrew}/u.test(String.fromCodePoint(e))}function al(e){return/\p{Script=Hiragana}/u.test(String.fromCodePoint(e))}function ol(e){return/\p{Script=Katakana}/u.test(String.fromCodePoint(e))}function sl(e){return/\p{Script=Han}/u.test(String.fromCodePoint(e))}function cl(e){return e>=1632&&e<=1641}function ll(e){return e>=1776&&e<=1785}function ul(e){return nl.has(e)}function dl(e){if(e.length===0)return oe();let t=[...e].map(e=>e.codePointAt(0)),n=t.length;if(t[0]===45||t[n-1]===45||n>=4&&t[2]===45&&t[3]===45||el(t[0]))return!1;let r=!1,i=!1,a=!1;for(let e=0;e<n;e++){let n=t[e];if(tl.has(n))return!1;(al(n)||ol(n)||sl(n))&&(r=!0),cl(n)&&(i=!0),ll(n)&&(a=!0);let o=t[e-1],s=t[e+1];switch(n){case 183:if(o!==108||s!==108)return!1;break;case 885:if(s===void 0||!rl(s))return!1;break;case 1523:case 1524:if(o===void 0||!il(o))return!1;break;case 8204:if(o===void 0||o<128&&!ul(o))return!1;break;case 8205:if(o===void 0||!ul(o))return!1}}return!(e.includes(`・`)&&!r||i&&a)}function fl(e){if(e.charCodeAt(0)===45||e.charCodeAt(e.length-1)===45||e.length>=4&&e.charCodeAt(2)===45&&e.charCodeAt(3)===45)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n>=97&&n<=122||n>=65&&n<=90||n>=48&&n<=57||n===45))return!1}return!0}function pl(e){return e.toLowerCase().startsWith(`xn--`)}function ml(e){try{let t=e.slice(4).toLowerCase();if(t.lastIndexOf(`-`)===0)return!1;let n=Xc(t);return n?dl(n):!1}catch{return!1}}function hl(e){return e.length===0||e.length>63?!1:pl(e)?ml(e):dl(e)}function gl(e){return e.length===0||e.length>63?!1:pl(e)?ml(e):fl(e)}function _l(e){if(e.length===0||e.length>253||e.charCodeAt(e.length-1)===46)return!1;for(let t of e.split(`.`))if(!gl(t))return!1;return!0}const vl=/^(?!.*\.\.)[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+(?:\.[\p{L}\p{N}!#$%&'*+/=?^_`{|}~-]+)*@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?)*$/iu;function yl(e){return vl.test(e)}function bl(e){if(e.length===0||e.includes(` `))return!1;let t=e.normalize(`NFC`).replace(/[\u002E\u3002\uFF0E\uFF61]/g,`.`);if(t.length>253)return!1;for(let e of t.split(`.`))if(!hl(e))return!1;return!0}function xl(e,t,n){let r=0,i=0,a=0,o=0;for(let s=t;s<n;s++){let t=e.charCodeAt(s);if(t===46){if(a===0||i>255||o===48&&a>1)return!1;r++,i=0,a=0,o=0}else if(t>=48&&t<=57)a===0&&(o=t),i=i*10+(t-48),a++;else return!1}return r===3&&a>0&&i<=255&&!(o===48&&a>1)}function Sl(e){return xl(e,0,e.length)}function Cl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function wl(e){let t=e.length;if(t===0)return!1;let n=0,r=!1,i=0;if(e.charCodeAt(0)===58&&e.charCodeAt(1)===58){if(t===2)return!0;r=!0,i=2}for(;i<t;){let a=0,o=i;for(;i<t&&Cl(e.charCodeAt(i));)i++,a++;if(a===0)return!1;let s=e.charCodeAt(i);if(s===46){if(!xl(e,o,t))return!1;n+=2,i=t;break}if(a>4)return!1;if(n++,i===t)break;if(s!==58)return!1;if(i++,e.charCodeAt(i)===58){if(r||e.charCodeAt(i+1)===58)return!1;if(r=!0,i++,i===t)break}}return r?n<=7:n===8}function Tl(e){try{return new URL(e,`http://example.com`),!0}catch{return!1}}function El(e){if(e.includes(` `)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e)||/%(?![0-9a-fA-F]{2})/.test(e))return!1;if(e===``)return!0;let t=e.indexOf(`:`);return t>0&&/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e.substring(0,t))?Tl(e):e.match(/^([a-zA-Z][a-zA-Z0-9+\-.]*)(\/\/)/)&&t===-1?!1:Tl(e)}function Dl(e){try{return new URL(e),!0}catch{return!1}}const Ol=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function kl(e){return Ol.test(e)}const Al=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function jl(e){return Al.test(e)}function Ml(e){if(e.length===0)return!1;try{return new RegExp(e),!0}catch{return!1}}const Nl=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function Pl(e){return Nl.test(e)}const Fl=/^(?!.*[^\x00-\x7F])(?!.*\\)(?:(?:[a-z][a-z0-9+\-.]*:)?(?:\/\/[^\s[\]{}<>^`|]*)?|[^\s[\]{}<>^`|]*)(?:\?[^\s[\]{}<>^`|]*)?(?:#[^\s[\]{}<>^`|]*)?$/i;function Il(e){return Fl.test(e)}const Ll=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;function Rl(e){return Ll.test(e)}function zl(e){return e>=97&&e<=122||e>=65&&e<=90}function Bl(e){return zl(e)||e>=48&&e<=57}function Vl(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Hl(e){return Bl(e)||e===43||e===45||e===46}function Ul(e){return Bl(e)||e===45||e===46||e===95||e===126}function Wl(e){return e===33||e===36||e===38||e===39||e===40||e===41||e===42||e===43||e===44||e===59||e===61}function Gl(e){return Ul(e)||Wl(e)||e===58||e===64}function Kl(e){let t=e.length;if(t===0||!zl(e.charCodeAt(0)))return!1;let n=1;for(;n<t;){let t=e.charCodeAt(n);if(t===58)break;if(!Hl(t))return!1;n++}if(e.charCodeAt(n)!==58)return!1;if(n++,e.charCodeAt(n)===47&&e.charCodeAt(n+1)===47){n+=2;let r=n,i=-1;for(let r=n;r<t;r++){let t=e.charCodeAt(r);if(t===64){i=r;break}if(t===47||t===63||t===35)break}if(i!==-1){for(let t=r;t<i;t++){let n=e.charCodeAt(t);if(n===91||n===93)return!1;if(n===37){if(t+2>=i||!Vl(e.charCodeAt(t+1))||!Vl(e.charCodeAt(t+2)))return!1;t+=2}else if(!Ul(n)&&!Wl(n)&&n!==58)return!1}n=i+1}if(e.charCodeAt(n)===91){for(n++;n<t&&e.charCodeAt(n)!==93;)n++;if(e.charCodeAt(n)!==93)return!1;n++}else for(;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35||t===58)break;if(t<128&&!Ul(t)&&!Wl(t))return!1;n++}if(e.charCodeAt(n)===58)for(n++;n<t;){let t=e.charCodeAt(n);if(t===47||t===63||t===35)break;if(t<48||t>57)return!1;n++}}for(;n<t;){let r=e.charCodeAt(n);if(r===37){if(n+2>=t||!Vl(e.charCodeAt(n+1))||!Vl(e.charCodeAt(n+2)))return!1;n+=2}else if(r>127)return!1;else if(!(Gl(r)||r===47||r===63||r===35))return!1;n++}return!0}const ql=/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;function Jl(e){return ql.test(e)}const Yl=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Xl(e){return Yl.test(e)}const Zl=new Map;function Ql(){Zl.clear()}function $l(){return[...Zl.entries()]}function eu(e,t){Zl.set(e,t)}function tu(e){return Zl.has(e)}function nu(e){return Zl.get(e)}function ru(e,t){return Zl.get(e)?.(t)??!0}function iu(){Ql(),Zl.set(`date-time`,Wc),Zl.set(`date`,Vc),Zl.set(`duration`,Kc),Zl.set(`email`,Jc),Zl.set(`hostname`,_l),Zl.set(`idn-email`,yl),Zl.set(`idn-hostname`,bl),Zl.set(`ipv4`,Sl),Zl.set(`ipv6`,wl),Zl.set(`iri-reference`,El),Zl.set(`iri`,Dl),Zl.set(`json-pointer-uri-fragment`,kl),Zl.set(`json-pointer`,jl),Zl.set(`regex`,Ml),Zl.set(`relative-json-pointer`,Pl),Zl.set(`time`,Uc),Zl.set(`uri-reference`,Il),Zl.set(`uri-template`,Rl),Zl.set(`uri`,Kl),Zl.set(`url`,Jl),Zl.set(`uuid`,Xl)}iu();var au=t({Clear:()=>Ql,Entries:()=>$l,Get:()=>nu,Has:()=>tu,IsDate:()=>Vc,IsDateTime:()=>Wc,IsDuration:()=>Kc,IsEmail:()=>Jc,IsHostname:()=>_l,IsIPv4:()=>Sl,IsIPv6:()=>wl,IsIdnEmail:()=>yl,IsIdnHostname:()=>bl,IsIri:()=>Dl,IsIriReference:()=>El,IsJsonPointer:()=>jl,IsJsonPointerUriFragment:()=>kl,IsRegex:()=>Ml,IsRelativeJsonPointer:()=>Pl,IsTime:()=>Uc,IsUri:()=>Kl,IsUriReference:()=>Il,IsUriTemplate:()=>Rl,IsUrl:()=>Jl,IsUuid:()=>Xl,Reset:()=>iu,Set:()=>eu,Test:()=>ru});function ou(e,t,n,r){return no(H(`Format`,`Test`),[U(n.format),r])}function su(e,t,n,r){return ru(n.format,r)}function cu(e,t,n,r,i,a){return su(e,t,i,a)||t.AddError({keyword:`format`,schemaPath:n,instancePath:r,params:{format:i.format}})}function lu(e,t,n,r){let i=!bs(n)||n.then,a=!Uo(n)||n.else;return io(hf(e,t,n.if,r),hf(e,t,i,r),hf(e,t,a,r))}function uu(e,t,n,r){let i=!bs(n)||n.then,a=!Uo(n)||n.else;return _f(e,t,n.if,r)?_f(e,t,i,r):_f(e,t,a,r)}function du(e,t,n,r,i,a){let o=!bs(i)||i.then,s=!Uo(i)||i.else,c=new Os,l=yf(e,c,`${n}/if`,r,i.if,a)?yf(e,c,`${n}/then`,r,o,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`then`}}):yf(e,t,`${n}/else`,r,s,a)||t.AddError({keyword:`if`,schemaPath:n,instancePath:r,params:{failingKeyword:`else`}});return l&&t.Merge([c]),l}function fu(e,t,n,r){return lo(n.items.map((n,i)=>{let a=Ga(H(r,`length`),U(i)),o=mf(e,t,n,`${r}[${i}]`),s=t.AddIndex(U(i));return Da(a,t.UseUnevaluated()?Ea(o,s):o)}))}function pu(e,t,n,r){return ht(n.items,0,(n,i)=>w(r.length,i)||gf(e,t,n,r[i])&&t.AddIndex(i))}function mu(e,t,n,r,i,a){return Be(i.items,0,(i,o)=>{let s=`${n}/items/${o}`,c=`${r}/${o}`;return w(a.length,o)||vf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function hu(e,t,n,r){let i=ps(n)?n.prefixItems.length:0,a=mf(e,t,n.items,`element`),o=t.AddIndex(`index`),s=t.UseUnevaluated()?Ea(a,o):a;return Ya(r,U(i),[`element`,`index`],s)}function gu(e,t,n,r){let i=ps(n)?n.prefixItems.length:0;return ht(r,i,(r,i)=>gf(e,t,n.items,r)&&t.AddIndex(i))}function _u(e,t,n,r,i,a){let o=ps(i)?i.prefixItems.length:0;return Be(a,o,(a,o)=>vf(e,t,`${n}/items`,`${r}/${o}`,i.items,a)&&t.AddIndex(o))}function vu(e,t,n,r){return Zo(n)?fu(e,t,n,r):hu(e,t,n,r)}function yu(e,t,n,r){return Zo(n)?pu(e,t,n,r):gu(e,t,n,r)}function bu(e,t,n,r,i,a){return Zo(i)?mu(e,t,n,r,i,a):_u(e,t,n,r,i,a)}function xu(e){return Io(e)}function Su(e,t,n,r){if(!xu(n))return U(!0);let[i,a]=[Ls(),Ls()];return Ga(no(H(r,`reduce`),[to([i,a],io(hf(e,t,n.contains,a),fo(i),i)),U(0)]),U(n.maxContains))}function Cu(e,t,n,r){if(!xu(n))return!0;let i=r.reduce((r,i)=>_f(e,t,n.contains,i)?++r:r,0);return w(i,n.maxContains)}function wu(e,t,n,r,i,a){let o=is(i)?i.minContains:1;return Cu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:o,maxContains:i.maxContains}})}function Tu(e,t,n,r){return Ga(r,U(n.maximum))}function Eu(e,t,n,r){return w(r,n.maximum)}function Du(e,t,n,r,i,a){return Eu(e,t,i,a)||t.AddError({keyword:`maximum`,schemaPath:n,instancePath:r,params:{comparison:`<=`,limit:i.maximum}})}function Ou(e,t,n,r){return Ga(H(r,`length`),U(n.maxItems))}function ku(e,t,n,r){return w(r.length,n.maxItems)}function Au(e,t,n,r,i,a){return ku(e,t,i,a)||t.AddError({keyword:`maxItems`,schemaPath:n,instancePath:r,params:{limit:i.maxItems}})}function ju(e,t,n,r){return Ja(r,U(n.maxLength))}function Mu(e,t,n,r){return F(r,n.maxLength)}function Nu(e,t,n,r,i,a){return Mu(e,t,i,a)||t.AddError({keyword:`maxLength`,schemaPath:n,instancePath:r,params:{limit:i.maxLength}})}function Pu(e,t,n,r){return Ga(H(Za(r),`length`),U(n.maxProperties))}function Fu(e,t,n,r){return w(k(r).length,n.maxProperties)}function Iu(e,t,n,r,i,a){return Fu(e,t,i,a)||t.AddError({keyword:`maxProperties`,schemaPath:n,instancePath:r,params:{limit:i.maxProperties}})}function Lu(e){return Io(e)}function Ru(e,t,n,r){if(!Lu(n))return U(!0);let[i,a]=[Ls(),Ls()];return Ka(no(H(r,`reduce`),[to([i,a],io(hf(e,t,n.contains,a),fo(i),i)),U(0)]),U(n.minContains))}function zu(e,t,n,r){if(!Lu(n))return!0;let i=r.reduce((r,i)=>_f(e,t,n.contains,i)?++r:r,0);return Ie(i,n.minContains)}function Bu(e,t,n,r,i,a){return zu(e,t,i,a)||t.AddError({keyword:`contains`,schemaPath:n,instancePath:r,params:{minContains:i.minContains}})}function Vu(e,t,n,r){return Ka(r,U(n.minimum))}function Hu(e,t,n,r){return Ie(r,n.minimum)}function Uu(e,t,n,r,i,a){return Hu(e,t,i,a)||t.AddError({keyword:`minimum`,schemaPath:n,instancePath:r,params:{comparison:`>=`,limit:i.minimum}})}function Wu(e,t,n,r){return Ka(H(r,`length`),U(n.minItems))}function Gu(e,t,n,r){return Ie(r.length,n.minItems)}function Ku(e,t,n,r,i,a){return Gu(e,t,i,a)||t.AddError({keyword:`minItems`,schemaPath:n,instancePath:r,params:{limit:i.minItems}})}function qu(e,t,n,r){return qa(r,U(n.minLength))}function Ju(e,t,n,r){return ne(r,n.minLength)}function Yu(e,t,n,r,i,a){return Ju(e,t,i,a)||t.AddError({keyword:`minLength`,schemaPath:n,instancePath:r,params:{limit:i.minLength}})}function Xu(e,t,n,r){return Ka(H(Za(r),`length`),U(n.minProperties))}function Zu(e,t,n,r){return Ie(k(r).length,n.minProperties)}function Qu(e,t,n,r,i,a){return Zu(e,t,i,a)||t.AddError({keyword:`minProperties`,schemaPath:n,instancePath:r,params:{limit:i.minProperties}})}function $u(e,t,n,r){return po(r,U(n.multipleOf))}function ed(e,t,n,r){return D(r,n.multipleOf)}function td(e,t,n,r,i,a){return ed(e,t,i,a)||t.AddError({keyword:`multipleOf`,schemaPath:n,instancePath:r,params:{multipleOf:i.multipleOf}})}function nd(e,t,n,r){return Xs(e,t,[n.not],r,Oa(Ha(H(`results`,`length`),U(1))))}function rd(e,t,n,r){return Oa(hf(e,t,n.not,r))}function id(e,t,n,r){return t.UseUnevaluated()?nd(e,t,n,r):rd(e,t,n,r)}function ad(e,t,n,r){let i=new Es;return!_f(e,i,n.not,r)&&t.Merge([i])}function od(e,t,n,r,i,a){return ad(e,t,i,a)||t.AddError({keyword:`not`,schemaPath:n,instancePath:r,params:{}})}function sd(e,t,n,r){return Xs(e,t,n.oneOf,r,Ha(H(`results`,`length`),U(1)))}function cd(e,t,n,r){return Ha(no(H(eo(n.oneOf.map(n=>hf(e,t,n,r))),`reduce`),[to([`count`,`result`],io(Ha(`result`,U(!0)),fo(`count`),`count`)),U(0)]),U(1))}function ld(e,t,n,r){return t.UseUnevaluated()?sd(e,t,n,r):cd(e,t,n,r)}function ud(e,t,n,r){let i=n.oneOf.reduce((t,n)=>{let i=new Es;return _f(e,i,n,r)?[...t,i]:t},[]);return B(i.length,1)&&t.Merge(i)}function dd(e,t,n,r,i,a){let o=[],s=[],c=i.oneOf.reduce((t,i,c)=>{let l=new Os,u=yf(e,l,`${n}/oneOf/${c}`,r,i,a);return u&&s.push(c),u||o.push(l),u?[...t,l]:t},[]),l=B(c.length,1)&&t.Merge(c);return!l&&B(s.length,0)&&o.forEach(e=>e.GetErrors().forEach(e=>t.AddError(e))),l||t.AddError({keyword:`oneOf`,schemaPath:n,instancePath:r,params:{passingSchemas:s}})}function fd(e,t,n,r){return no(H(As(j(n.pattern)?new RegExp(n.pattern,`u`):n.pattern),`test`),[r])}function pd(e,t,n,r){return(j(n.pattern)?new RegExp(n.pattern,`u`):n.pattern).test(r)}function md(e,t,n,r,i,a){return pd(e,t,i,a)||t.AddError({keyword:`pattern`,schemaPath:n,instancePath:r,params:{pattern:i.pattern}})}function hd(e,t,n,r){return lo(Re(n.patternProperties).map(([n,i])=>{let[a,o]=[Ls(),Ls()],s=Oa(no(H(As(new RegExp(n,`u`)),`test`),[a])),c=mf(e,t,i,o),l=t.AddKey(a),u=t.UseUnevaluated()?Da(s,Ea(c,l)):Da(s,c);return Ya(Xa(r),U(0),[`[${a}, ${o}]`,`_`],u)}))}function gd(e,t,n,r){return ht(Re(n.patternProperties),0,([n,i])=>{let a=new RegExp(n,`u`);return ht(Re(r),0,([n,r])=>!a.test(n)||gf(e,t,i,r)&&t.AddKey(n))})}function _d(e,t,n,r,i,a){return Be(Re(i.patternProperties),0,([i,o])=>{let s=`${n}/patternProperties/${i}`,c=new RegExp(i,`u`);return Be(Re(a),0,([n,i])=>{let a=`${r}/${n}`;return!c.test(n)||vf(e,t,s,a,o,i)&&t.AddKey(n)})})}function vd(e,t,n,r){return lo(n.prefixItems.map((n,i)=>{let a=Ga(H(r,`length`),U(i)),o=mf(e,t,n,`${r}[${i}]`),s=t.AddIndex(U(i));return Da(a,t.UseUnevaluated()?Ea(o,s):o)}))}function yd(e,t,n,r){return B(r.length,0)||ht(n.prefixItems,0,(n,i)=>w(r.length,i)||gf(e,t,n,r[i])&&t.AddIndex(i))}function bd(e,t,n,r,i,a){return B(a.length,0)||Be(i.prefixItems,0,(i,o)=>{let s=`${n}/prefixItems/${o}`,c=`${r}/${o}`;return w(a.length,o)||vf(e,t,s,c,i,a[o])&&t.AddIndex(o)})}function xd(e,t){return e.includes(t)||st().exactOptionalPropertyTypes}function Sd(e,t){return za(H(e,t))}function Cd(e,t){return ve(e[t])}function wd(e,t,n,r){let i=ys(n)?n.required:[];return lo(Re(n.properties).map(([n,a])=>{let o=Oa(Qa(r,U(n))),s=mf(e,t,a,H(r,n)),c=t.AddKey(U(n)),l=t.UseUnevaluated()?Ea(s,c):s,u=i.includes(n)?l:Da(o,l);return xd(i,n)?u:Da(Sd(r,n),u)}))}function Td(e,t,n,r){let i=ys(n)?n.required:[];return ht(Re(n.properties),0,([n,a])=>{let o=!z(r,n)||gf(e,t,a,r[n])&&t.AddKey(n);return xd(i,n)?o:Cd(r,n)||o})}function Ed(e,t,n,r,i,a){let o=ys(i)?i.required:[];return Be(Re(i.properties),0,([i,s])=>{let c=`${n}/properties/${i}`,l=`${r}/${i}`,u=()=>!z(a,i)||vf(e,t,c,l,s,a[i])&&t.AddKey(i);return xd(o,i)?u():Cd(a,i)||u()})}function Dd(e,t,n,r){let[i,a]=[Ls(),Ls()];return Ya(Za(r),U(0),[i,a],hf(e,t,n.propertyNames,i))}function Od(e,t,n,r){return ht(k(r),0,(r,i)=>_f(e,t,n.propertyNames,r))}function kd(e,t,n,r,i,a){let o=[];return Be(k(a),0,(t,a)=>{let s=`${r}/${t}`,c=`${n}/propertyNames`,l=yf(e,new Os,c,s,i.propertyNames,t);return l||o.push(t),l})||t.AddError({keyword:`propertyNames`,schemaPath:n,instancePath:r,params:{propertyNames:o}})}function Ad(e,t,n,r){return kf(e,t,e.RecursiveRef(n)??!1,r)}function jd(e,t,n,r){let i=e.RecursiveRef(n)??!1;return ko(i)&&_f(e,t,i,r)}function Md(e,t,n,r,i,a){let o=e.RecursiveRef(i)??!1;return ko(o)&&yf(e,t,`#`,r,o,a)}function Nd(e,t,n,r){let i=to([`context`,`value`],kf(e,t,n,`value`));return no(to([`context`,`value`],ao([oo(`nextContext`,ro(`CheckContext`,[])),oo(`result`,no(i,[`nextContext`,`value`])),so(`result`,t.Merge(`[nextContext]`)),co(`result`)])),[`context`,r])}function Pd(e,t,n,r){return kf(e,t,n,r)}function Fd(e,t,n,r){let i=e.Ref(n)??!1;return t.UseUnevaluated()?Nd(e,t,i,r):Pd(e,t,i,r)}function Id(e,t,n,r){let i=e.Ref(n)??!1,a=new Es,o=ko(i)&&_f(e,a,i,r);return o&&t.Merge([a]),o}function Ld(e,t,n,r,i,a){let o=e.Ref(i)??!1,s=new Os,c=ko(o)&&yf(e,s,`#`,r,o,a);return c&&t.Merge([s]),c||s.GetErrors().forEach(e=>t.AddError(e)),c}function Rd(e,t,n,r){return lo(n.required.map(e=>Qa(r,U(e))))}function zd(e,t,n,r){return ht(n.required,0,e=>z(r,e))}function Bd(e,t,n,r,i,a){let o=[];return Be(i.required,0,e=>{let t=z(a,e);return t||o.push(e),t})||t.AddError({keyword:`required`,schemaPath:n,instancePath:r,params:{requiredProperties:o}})}function Vd(e,t,n,r){return B(n,`object`)?Fa(r):B(n,`array`)?ka(r):B(n,`boolean`)?ja(r):B(n,`integer`)?Ma(r):B(n,`number`)?Pa(r):B(n,`null`)?Na(r):B(n,`string`)?La(r):B(n,`bigint`)?Aa(r):B(n,`constructor`)?Va(r):B(n,`function`)?Ba(r):B(n,`symbol`)?Ra(r):B(n,`undefined`)||B(n,`void`)?za(r):U(!0)}function Hd(e,t,n,r,i){return B(n,`object`)?Ze(i):B(n,`array`)?lt(i):B(n,`boolean`)?qe(i):B(n,`integer`)?P(i):B(n,`number`)?$e(i):B(n,`null`)?ge(i):B(n,`string`)?j(i):B(n,`bigint`)?it(i):B(n,`constructor`)?eee(i):B(n,`function`)?St(i):B(n,`symbol`)?me(i):B(n,`undefined`)?ve(i):!B(n,`void`)||ve(i)}function Ud(e,t,n,r){return uo(n.map(n=>Vd(e,t,n,r)))}function Wd(e,t,n,r,i){return n.some(n=>Hd(e,t,n,r,i))}function Gd(e,t,n,r){return lt(n.type)?Ud(e,t,n.type,r):Vd(e,t,n.type,r)}function Kd(e,t,n,r){return lt(n.type)?Wd(e,t,n.type,n,r):Hd(e,t,n.type,n,r)}function qd(e,t,n,r,i,a){return(lt(i.type)?Wd(e,t,i.type,i,a):Hd(e,t,i.type,i,a))||t.AddError({keyword:`type`,schemaPath:n,instancePath:r,params:{type:i.type}})}function Jd(e,t,n,r){let[i,a]=[Ls(),Ls()],o=no(H(`context`,`GetIndices`),[]),s=no(H(`indices`,`has`),[i]),c=hf(e,t,n.unevaluatedItems,a),l=no(H(`context`,`AddIndex`),[i]),u=Ya(r,U(0),[a,i],Ea(Da(s,c),l));return no(to([`context`],ao([oo(`indices`,o),co(u)])),[`context`])}function Yd(e,t,n,r){let i=t.GetIndices();return ht(r,0,(r,a)=>(i.has(a)||_f(e,t,n.unevaluatedItems,r))&&t.AddIndex(a))}function Xd(e,t,n,r,i,a){let o=t.GetIndices(),s=[];return Be(a,0,(a,c)=>{let l=new Os,u=(o.has(c)||yf(e,l,n,r,i.unevaluatedItems,a))&&t.AddIndex(c);return u||s.push(c),u})||t.AddError({keyword:`unevaluatedItems`,schemaPath:n,instancePath:r,params:{unevaluatedItems:s}})}function Zd(e,t,n,r){let[i,a]=[Ls(),Ls()],o=no(H(`context`,`GetKeys`),[]),s=no(H(`keys`,`has`),[i]),c=no(H(`context`,`AddKey`),[i]),l=hf(e,t,n.unevaluatedProperties,a),u=Ya(Xa(r),U(0),[`[${i}, ${a}]`,`_`],Da(s,Ea(l,c)));return no(to([`context`],ao([oo(`keys`,o),co(u)])),[`context`])}function Qd(e,t,n,r){let i=t.GetKeys();return ht(Re(r),0,([r,a])=>i.has(r)||_f(e,t,n.unevaluatedProperties,a)&&t.AddKey(r))}function $d(e,t,n,r,i,a){let o=t.GetKeys(),s=[];return Be(Re(a),0,([a,c])=>{let l=new Os,u=o.has(a)||yf(e,l,n,r,i.unevaluatedProperties,c)&&t.AddKey(a);return u||s.push(a),u})||t.AddError({keyword:`unevaluatedProperties`,schemaPath:n,instancePath:r,params:{unevaluatedProperties:s}})}function ef(e){return!B(e.uniqueItems,!1)}function tf(e,t,n,r){return ef(n)?Ha(H(ro(`Set`,[no(H(r,`map`),[H(`Hashing`,`Hash`)])]),`size`),H(r,`length`)):U(!0)}function nf(e,t,n,r){if(!ef(n))return!0;let i=new Set(r.map(C)).size,a=r.length;return B(i,a)}function rf(e,t,n,r,i,a){if(!ef(i))return!0;let o=new Set,s=a.reduce((e,t,n)=>{let r=C(t);return o.has(r)?[...e,n]:(o.add(r),e)},[]);return B(s.length,0)||t.AddError({keyword:`uniqueItems`,schemaPath:n,instancePath:r,params:{duplicateItems:s}})}function af(e,t){return xs(e)&&(lt(e.type)&&xt(e.type.length,0)&&ht(e.type,0,e=>B(e,t))||B(e.type,t))}function of(e){return af(e,`object`)}function sf(e){return Do(e)&&(jo(e)||Ro(e)||zo(e)||Bo(e)||ms(e)||fs(e)||hs(e)||ss(e)||ns(e)||ys(e)||ws(e))}function cf(e){return af(e,`array`)}function lf(e){return Do(e)&&(Ao(e)||Xo(e)||Io(e)||$o(e)||es(e)||is(e)||as(e)||ps(e)||Cs(e)||Ss(e))}function uf(e){return af(e,`string`)}function df(e){return Do(e)&&(os(e)||ts(e)||qo(e)||ds(e))}function ff(e){return af(e,`number`)||af(e,`bigint`)}function pf(e){return Do(e)&&(rs(e)||Qo(e)||Go(e)||Ko(e)||cs(e))}function mf(e,t,n,r){return t.UseUnevaluated()?Ea(Ea(t.Push(),hf(e,t,n,r)),t.Pop()):hf(e,t,n,r)}function hf(e,t,n,r){e.Push(n);let i=[];if(Oo(n))return sc(e,t,n,r);if(xs(n)&&i.push(Gd(e,t,n,r)),sf(n)){let a=[];ys(n)&&a.push(Rd(e,t,n,r)),jo(n)&&a.push(qs(e,t,n,r)),Ro(n)&&a.push(_c(e,t,n,r)),zo(n)&&a.push(bc(e,t,n,r)),Bo(n)&&a.push(Cc(e,t,n,r)),fs(n)&&a.push(hd(e,t,n,r)),ms(n)&&a.push(wd(e,t,n,r)),hs(n)&&a.push(Dd(e,t,n,r)),ss(n)&&a.push(Xu(e,t,n,r)),ns(n)&&a.push(Pu(e,t,n,r));let o=lo(a),s=Da(Oa(Fa(r)),o);i.push(of(n)?o:s)}if(lf(n)){let a=[];Ao(n)&&a.push(zs(e,t,n,r)),Io(n)&&a.push(mc(e,t,n,r)),Xo(n)&&a.push(vu(e,t,n,r)),$o(n)&&a.push(Su(e,t,n,r)),es(n)&&a.push(Ou(e,t,n,r)),is(n)&&a.push(Ru(e,t,n,r)),as(n)&&a.push(Wu(e,t,n,r)),ps(n)&&a.push(vd(e,t,n,r)),Ss(n)&&a.push(tf(e,t,n,r));let o=lo(a),s=Da(Oa(ka(r)),o);i.push(cf(n)?o:s)}if(df(n)){let a=[];ts(n)&&a.push(ju(e,t,n,r)),os(n)&&a.push(qu(e,t,n,r)),qo(n)&&a.push(ou(e,t,n,r)),ds(n)&&a.push(fd(e,t,n,r));let o=lo(a),s=Da(Oa(La(r)),o);i.push(uf(n)?o:s)}if(pf(n)){let a=[];Go(n)&&a.push(Mc(e,t,n,r)),Ko(n)&&a.push(Fc(e,t,n,r)),Qo(n)&&a.push(Tu(e,t,n,r)),rs(n)&&a.push(Vu(e,t,n,r)),cs(n)&&a.push($u(e,t,n,r));let o=lo(a),s=Da(Oa(Da(Pa(r),Aa(r))),o);i.push(ff(n)?o:s)}vs(n)&&i.push(Fd(e,t,n,r)),_s(n)&&i.push(Ad(e,t,n,r)),Ho(n)&&i.push(Ec(e,t,n,r)),Fo(n)&&i.push(uc(e,t,n,r)),Wo(n)&&i.push(kc(e,t,n,r)),Yo(n)&&i.push(lu(e,t,n,r)),ls(n)&&i.push(id(e,t,n,r)),Mo(n)&&i.push($s(e,t,n,r)),Po(n)&&i.push(ic(e,t,n,r)),us(n)&&i.push(ld(e,t,n,r)),Cs(n)&&i.push(Da(Oa(ka(r)),Jd(e,t,n,r))),ws(n)&&i.push(Da(Oa(Ia(r)),Zd(e,t,n,r))),Eo(n)&&i.push(Ns(e,t,n,r));let a=lo(i);return e.Pop(n),a}function gf(e,t,n,r){return t.Push()&&_f(e,t,n,r)&&t.Pop()}function _f(e,t,n,r){e.Push(n);let i=Oo(n)?cc(e,t,n,r):(!xs(n)||Kd(e,t,n,r))&&(!(x(r)&&!lt(r))||(!ys(n)||zd(e,t,n,r))&&(!jo(n)||Js(e,t,n,r))&&(!Ro(n)||vc(e,t,n,r))&&(!zo(n)||xc(e,t,n,r))&&(!Bo(n)||wc(e,t,n,r))&&(!fs(n)||gd(e,t,n,r))&&(!ms(n)||Td(e,t,n,r))&&(!hs(n)||Od(e,t,n,r))&&(!ss(n)||Zu(e,t,n,r))&&(!ns(n)||Fu(e,t,n,r)))&&(!lt(r)||(!Ao(n)||Bs(e,t,n,r))&&(!Io(n)||hc(e,t,n,r))&&(!Xo(n)||yu(e,t,n,r))&&(!$o(n)||Cu(e,t,n,r))&&(!es(n)||ku(e,t,n,r))&&(!is(n)||zu(e,t,n,r))&&(!as(n)||Gu(e,t,n,r))&&(!ps(n)||yd(e,t,n,r))&&(!Ss(n)||nf(e,t,n,r)))&&(!j(r)||(!ts(n)||Mu(e,t,n,r))&&(!os(n)||Ju(e,t,n,r))&&(!qo(n)||su(e,t,n,r))&&(!ds(n)||pd(e,t,n,r)))&&(!($e(r)||it(r))||(!Go(n)||Nc(e,t,n,r))&&(!Ko(n)||Ic(e,t,n,r))&&(!Qo(n)||Eu(e,t,n,r))&&(!rs(n)||Hu(e,t,n,r))&&(!cs(n)||ed(e,t,n,r)))&&(!vs(n)||Id(e,t,n,r))&&(!_s(n)||jd(e,t,n,r))&&(!Ho(n)||Dc(e,t,n,r))&&(!Fo(n)||dc(e,t,n,r))&&(!Wo(n)||Ac(e,t,n,r))&&(!Yo(n)||uu(e,t,n,r))&&(!ls(n)||ad(e,t,n,r))&&(!Mo(n)||ec(e,t,n,r))&&(!Po(n)||ac(e,t,n,r))&&(!us(n)||ud(e,t,n,r))&&(!Cs(n)||!lt(r)||Yd(e,t,n,r))&&(!ws(n)||!x(r)||Qd(e,t,n,r))&&(!Eo(n)||Ps(e,t,n,r));return e.Pop(n),i}function vf(e,t,n,r,i,a){return t.Push()&&yf(e,t,n,r,i,a)&&t.Pop()}function yf(e,t,n,r,i,a){e.Push(i);let o=Oo(i)?lc(e,t,n,r,i,a):!!((!xs(i)||qd(e,t,n,r,i,a))&+(!(x(a)&&!lt(a))||!!((!ys(i)||Bd(e,t,n,r,i,a))&+(!jo(i)||Ys(e,t,n,r,i,a))&(!Ro(i)||yc(e,t,n,r,i,a))&(!zo(i)||Sc(e,t,n,r,i,a))&(!Bo(i)||Tc(e,t,n,r,i,a))&(!fs(i)||_d(e,t,n,r,i,a))&(!ms(i)||Ed(e,t,n,r,i,a))&(!hs(i)||kd(e,t,n,r,i,a))&(!ss(i)||Qu(e,t,n,r,i,a))&(!ns(i)||Iu(e,t,n,r,i,a))))&(!lt(a)||!!((!Ao(i)||Vs(e,t,n,r,i,a))&+(!Io(i)||gc(e,t,n,r,i,a))&(!Xo(i)||bu(e,t,n,r,i,a))&(!$o(i)||wu(e,t,n,r,i,a))&(!es(i)||Au(e,t,n,r,i,a))&(!is(i)||Bu(e,t,n,r,i,a))&(!as(i)||Ku(e,t,n,r,i,a))&(!ps(i)||bd(e,t,n,r,i,a))&(!Ss(i)||rf(e,t,n,r,i,a))))&(!j(a)||!!((!ts(i)||Nu(e,t,n,r,i,a))&+(!os(i)||Yu(e,t,n,r,i,a))&(!qo(i)||cu(e,t,n,r,i,a))&(!ds(i)||md(e,t,n,r,i,a))))&(!($e(a)||it(a))||!!((!Go(i)||Pc(e,t,n,r,i,a))&+(!Ko(i)||Lc(e,t,n,r,i,a))&(!Qo(i)||Du(e,t,n,r,i,a))&(!rs(i)||Uu(e,t,n,r,i,a))&(!cs(i)||td(e,t,n,r,i,a))))&(!vs(i)||Ld(e,t,n,r,i,a))&(!_s(i)||Md(e,t,n,r,i,a))&(!Ho(i)||Oc(e,t,n,r,i,a))&(!Fo(i)||fc(e,t,n,r,i,a))&(!Wo(i)||jc(e,t,n,r,i,a))&(!Yo(i)||du(e,t,n,r,i,a))&(!ls(i)||od(e,t,n,r,i,a))&(!Mo(i)||tc(e,t,n,r,i,a))&(!Po(i)||oc(e,t,n,r,i,a))&(!us(i)||dd(e,t,n,r,i,a))&(!Cs(i)||!lt(a)||Xd(e,t,n,r,i,a))&(!ws(i)||!x(a)||$d(e,t,n,r,i,a)))&&(!Eo(i)||Fs(e,t,n,r,i,a));return e.Pop(i),o}const bf=[0],xf=new Map,Sf=new Map;function Cf(){return C(bf[0]++)}function wf(e,t){xf.has(e)||xf.set(e,new Map);let n=xf.get(e);if(n.has(t))return n.get(t);let r=Cf();return n.set(t,r),r}function Tf(e,t,n,r){return e.UseUnevaluated()?no(`check_${n}`,[`context`,r]):no(`check_${n}`,[r])}function Ef(e,t,n,r){let i=hf(e,t,n,`value`);return t.UseUnevaluated()?oo(`check_${r}`,to([`context`,`value`],i)):oo(`check_${r}`,to([`value`],i))}function Df(){bf[0]=0,xf.clear(),Sf.clear()}function Of(){return[...Sf.values()]}function kf(e,t,n,r){let i=wf(n,e.BaseURL().href),a=Tf(t,n,i,r);return Sf.has(i)?a:(Sf.set(i,``),Sf.set(i,Ef(e,t,n,i)),a)}function Af(e,t){return x(t)&&!O(e)?t[e]:void 0}function jf(e,t){return e.reduce((e,t)=>Af(t,e),t)}function Mf(e){if(B(e.length,0))return[];let t=e.split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`));return t.length>0&&t[0]===``?t.slice(1):t}function Nf(e,t){return jf(Mf(t),e)}function Pf(e,t,n){if(e.$id===n.hash)return e;let r=new URL(e.$id,t.href),i=new URL(n.href,t.href);if(B(r.pathname,i.pathname))return n.hash.startsWith(`#`)?Lf(e,t,n):e}function Ff(e,t,n){let r=new URL(`#${e.$anchor}`,t.href),i=new URL(n.href,t.href);return B(r.href,i.href)?e:void 0}function If(e,t,n){let r=new URL(`#${e.$dynamicAnchor}`,t.href),i=new URL(n.href,t.href);return B(r.href,i.href)?e:void 0}function Lf(e,t,n){if(n.href.endsWith(`#`))return e;if(!n.hash.startsWith(`#`))return;let r=decodeURIComponent(n.hash.slice(1));if(r.startsWith(`/`))return Nf(e,r)}function Rf(e,t,n){if(Jo(e)){let r=Pf(e,t,n);if(!ve(r))return r}if(No(e)){let r=Ff(e,t,n);if(!ve(r))return r}if(Vo(e)){let r=If(e,t,n);if(!ve(r))return r}return Lf(e,t,n)}function zf(e,t,n){return e.reduce((e,r)=>{let i=Vf(r,t,n);return ve(i)?e:i},void 0)}function Bf(e,t,n){return k(e).reduce((r,i)=>{let a=Vf(e[i],t,n);return ve(a)?r:a},void 0)}function Vf(e,t,n){let r=Do(e)&&Jo(e)?new URL(e.$id,t.href):t;if(Do(e)){let t=Rf(e,r,n);if(!ve(t))return t}if(lt(e))return zf(e,r,n);if(x(e))return Bf(e,r,n)}function Hf(e,t){let n=new URL(`http://unknown/`),r=Jo(e)?new URL(e.$id,n.href):n;return Vf(e,r,new URL(t,r.href))}function Uf(e,t,n,r){let i=n.$dynamicRef.startsWith(`#`)?Hf(t,n.$dynamicRef):Hf(e,n.$dynamicRef);if(!ve(i))return!Do(i)||!Vo(i)||new URL(n.$dynamicRef,`http://unknown/`).hash.startsWith(`#/`)?i:r.find(e=>e.$dynamicAnchor===i.$dynamicAnchor)??i}var Wf=function(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)},Gf,Kf,qf,Jf,Yf,Xf=class{constructor(e,t){Gf.add(this),this.context=e,this.schema=t,this.ids=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[]}BaseURL(){return this.ids.reduce((e,t)=>new URL(t.$id,e),new URL(`http://unknown`))}Base(){return this.ids[this.ids.length-1]??this.schema}Push(e){Do(e)&&(Jo(e)&&(this.ids.push(e),Wf(this,Gf,`m`,Kf).call(this,e)),No(e)&&this.anchors.push(e),gs(e)&&this.recursiveAnchors.push(e),Vo(e)&&this.dynamicAnchors.push(e))}Pop(e){Do(e)&&(Jo(e)&&(this.ids.pop(),Wf(this,Gf,`m`,qf).call(this,e)),No(e)&&this.anchors.pop(),gs(e)&&this.recursiveAnchors.pop(),Vo(e)&&this.dynamicAnchors.pop())}Ref(e){return Wf(this,Gf,`m`,Jf).call(this,e)??Wf(this,Gf,`m`,Yf).call(this,e)}RecursiveRef(e){return gs(this.Base())?Hf(this.recursiveAnchors[0],e.$recursiveRef):Hf(this.Base(),e.$recursiveRef)}DynamicRef(e){let t=this.schema;return Uf(t,this.Base(),e,this.dynamicAnchors)}};Gf=new WeakSet,Kf=function e(t,n=!0){if(!Do(t))return;let r=t;if(!(!n&&Jo(r))){!n&&Vo(r)&&this.dynamicAnchors.push(r);for(let t of k(r))Wf(this,Gf,`m`,e).call(this,r[t],!1)}},qf=function e(t,n=!0){if(!Do(t))return;let r=t;if(!(!n&&Jo(r))){!n&&Vo(r)&&this.dynamicAnchors.pop();for(let t of k(r))Wf(this,Gf,`m`,e).call(this,r[t],!1)}},Jf=function(e){return z(this.context,e.$ref)?this.context[e.$ref]:void 0},Yf=function(e){let t=this.schema;return e.$ref.startsWith(`#`)?Hf(this.Base(),e.$ref):Hf(t,e.$ref)};function Zf(e){return`${e.Functions().join(`;
|
|
880
|
+
`)}; return (value) => { ${(e.UseUnevaluated()?[`const context = new CheckContext({}, {})`,`return ${e.Entry()}`]:[`return ${e.Entry()}`]).join(`; `)} }`}function Qf(e,t){return yo(`CheckContext`,`Guard`,`Format`,`Hashing`,e.External().identifier,t)(Es,xe,au,Te,e.External().variables)}function $f(e){let t=new Xf(e.Context(),e.Schema()),n=new Es;return r=>_f(t,n,e.Schema(),r)}function ep(e,t){return vo()?Qf(e,t):$f(e)}var tp=class{constructor(e,t,n){this.isAccelerated=e,this.code=t,this.check=n}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}},np=class{constructor(e,t,n,r,i,a){this.context=e,this.schema=t,this.external=n,this.functions=r,this.entry=i,this.useUnevaluated=a}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=Zf(this),t=ep(this,e);return new tp(vo(),e,t)}};function rp(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});js(),Df();let r=new Xf(t,n),i=new ute(lte(t,n)),a=kf(r,i,n,`value`),o=Of();return new np(t,n,Ms(),o,a,i.UseUnevaluated())}function ip(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),i=st(),a=So(),o=[];return[yf(new Xf(t,n),new Ds(e=>{if(!Ie(o.length,i.maxErrors))return o.push({...e,message:a(e)})}),`#`,``,n,r),o]}function ap(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return _f(new Xf(t,n),new Es,n,r)}function op(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return ap(t,n,r)}function sp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]}),[i,a]=ip(t,n,r);return a}var cp=class extends Error{constructor(e,t,n){super(e),Object.defineProperty(this,"cause",{value:{source:e,errors:n,value:t},writable:!1,configurable:!1,enumerable:!1})}};function lp(e,t,n){return lt(n)?n.map(n=>bp(e,t.items,n)):n}function up(e,t,n){return bp({...e,...t.$defs},b(t.$ref),n)}function dp(e,t){let n=z(t,`unevaluatedProperties`)?{additionalProperties:t.unevaluatedProperties}:{},r=gt(e,t),i=nt(r);return le(i)?Ve(i,n):i}function fp(e,t,n){return bp(e,dp(e,t),n)}function pp(e){return z(e,`additionalProperties`)?e.additionalProperties:void 0}function mp(e,t,n){if(!x(n)||lt(n))return n;let r=pp(t);for(let i of k(n)){if(z(t.properties,i)){n[i]=bp(e,t.properties[i],n[i]);continue}if(qe(r)&&B(r,!0)||Pe(r)&&op(e,r,n[i])){n[i]=bp(e,r,n[i]);continue}delete n[i]}return n}function hp(e,t,n){if(!x(n))return n;let r=pp(t),[i,a]=[new RegExp(_t(t)),Ct(t)];for(let t of k(n)){if(i.test(t)){n[t]=bp(e,a,n[t]);continue}if(qe(r)&&B(r,!0)||Pe(r)&&op(e,r,n[t])){n[t]=bp(e,r,n[t]);continue}delete n[t]}return n}function gp(e,t,n){return z(e,t.$ref)?bp(e,e[t.$ref],n):n}function _p(e,t,n){if(!lt(n))return n;let r=Math.min(n.length,t.items.length);for(let i=0;i<r;i++)n[i]=bp(e,t.items[i],n[i]);return xt(n.length,r)?n.slice(0,r):n}function vp(e){return nee(e)}function yp(e,t,n){for(let r of t.anyOf){let t=bp(e,r,vp(n));if(op(e,r,t))return t}return n}function bp(e,t,n){return ft(t)?lp(e,t,n):ue(t)?up(e,t,n):Ee(t)?fp(e,t,n):le(t)?mp(e,t,n):Je(t)?hp(e,t,n):M(t)?gp(e,t,n):Le(t)?_p(e,t,n):T(t)?yp(e,t,n):n}function xp(e,t){for(let n of mo.Keys(e))mo.HasPropertyKey(t,n)||(t[n]=e[n]);return t}function Sp(e){let t={};for(let n of mo.Keys(e))t[n]=Tp(e[n]);return t}function Cp(e){return wp(ze(e))}function wp(e){return e.map(e=>Tp(e))}function Tp(e){return xp(e,ft(e)?Ye(Tp(e.items),tee(e)):Ee(e)?I(wp(e.allOf)):T(e)?bt(Cp(e.anyOf)):le(e)?ke(Sp(e.properties)):Je(e)?Ge(Ne(e),Tp(Ct(e))):Le(e)?aee(wp(e.items)):e)}function Ep(e){return Tp(e)}function Dp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return bp(t,st().unionPrioritySort?Ep(n):n,r)}function Op(e){return x(e)&&z(e,`value`)}function W(e){return{value:e}}function kp(e){return lt(e)?W(e):W([e])}function Ap(e){return B(e,!0)?W(BigInt(1)):W(BigInt(0))}const dte=/^-?(0|[1-9]\d*)n$/,fte=/^-?(0|[1-9]\d*)\.\d+$/,pte=/^-?(0|[1-9]\d*)$/;function mte(e){return dte.test(e)}function hte(e){return fte.test(e)}function gte(e){return pte.test(e)}function _te(e){let t=e.toLowerCase();return mte(e)?W(BigInt(e.slice(0,e.length-1))):hte(e)?W(BigInt(e.split(`.`)[0])):gte(e)?W(BigInt(e)):B(t,`false`)?W(BigInt(0)):B(t,`true`)?W(BigInt(1)):void 0}function jp(e){return it(e)?W(e):qe(e)?Ap(e):$e(e)?W(BigInt(Math.trunc(e))):ge(e)?W(BigInt(0)):j(e)?_te(e):ve(e)?W(BigInt(0)):void 0}function vte(e){return B(e,BigInt(0))?W(!1):B(e,BigInt(1))?W(!0):void 0}function yte(e){return B(e,0)?W(!1):B(e,1)?W(!0):void 0}function bte(e){return B(e.toLowerCase(),`false`)?W(!1):B(e.toLowerCase(),`true`)?W(!0):B(e,`0`)?W(!1):B(e,`1`)?W(!0):void 0}function Mp(e){return it(e)?vte(e):qe(e)?W(e):$e(e)?yte(e):ge(e)?W(!1):j(e)?bte(e):ve(e)?W(!1):void 0}function xte(e){return B(e,BigInt(0))?W(null):void 0}function Ste(e){return B(e,!1)?W(null):void 0}function Cte(e){return B(e,0)?W(null):void 0}function wte(e){let t=e.toLowerCase();return B(t,`undefined`)||B(t,`null`)||B(e,``)||B(e,`0`)?W(null):void 0}function Tte(e){return it(e)?xte(e):qe(e)?Ste(e):$e(e)?Cte(e):ge(e)?W(null):j(e)?wte(e):ve(e)?W(null):void 0}const Np=BigInt(2**53-1),Pp=BigInt(-(2**53-1));function Ete(e){return e<=Np&&e>=Pp?W(Number(e)):void 0}function Dte(e){return W(+!!e)}function Ote(e){let t=+e;if($e(t))return W(t);let n=e.toLowerCase();if(B(n,`false`))return W(0);if(B(n,`true`))return W(1);let r=jp(e);if(Op(r))return r.value<=Np&&r.value>=Pp?W(Number(r.value)):void 0}function Fp(e){return it(e)?Ete(e):qe(e)?Dte(e):$e(e)?W(e):ge(e)?W(0):j(e)?Ote(e):ve(e)?W(0):void 0}function Ip(e){return it(e)||qe(e)||$e(e)?W(e.toString()):ge(e)?W(`null`):j(e)?W(e):ve(e)?W(``):void 0}function kte(e){return B(e,BigInt(0))?W(void 0):void 0}function Ate(e){return B(e,!1)?W(void 0):void 0}function jte(e){return B(e,0)?W(void 0):void 0}function Mte(e){let t=e.toLowerCase();return B(t,`undefined`)||B(t,`null`)||B(e,``)||B(e,`0`)?W(void 0):void 0}function Lp(e){return it(e)?kte(e):qe(e)?Ate(e):$e(e)?jte(e):ge(e)?W(void 0):j(e)?Mte(e):ve(e)?W(e):void 0}function Nte(e,t,n){return kp(n).value.map(n=>Bp(e,t.items,n))}function Pte(e,t,n){let r=jp(n);return Op(r)?r.value:n}function Fte(e,t,n){let r=Mp(n);return Op(r)?r.value:n}function Ite(e,t,n){return Bp({...e,...t.$defs},b(t.$ref),n)}function Lte(e,t,n){return Bp(e,nt(t),n)}function Rte(e,t,n){let r=Fp(n);return Op(r)?Math.trunc(r.value):n}function zte(e,t,n){let r=gt(e,t);return Bp(e,nt(r),n)}function Bte(e,t,n){let r=jp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Vte(e,t,n){let r=Mp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Hte(e,t,n){let r=Fp(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Ute(e,t,n){let r=Ip(n);return Op(r)&&B(t.const,r.value)?r.value:n}function Wte(e,t,n){return B(t.const,n)?n:Qe(t)?Bte(e,t,n):pe(t)?Vte(e,t,n):he(t)?Hte(e,t,n):ye(t)?Ute(e,t,n):oe()}function Gte(e,t,n){let r=Tte(n);return Op(r)?r.value:n}function Kte(e,t,n){let r=Fp(n);return Op(r)?r.value:n}function Rp(e,t,n,r){let i=k(r);for(let[a,o]of t)for(let t of i)a.test(t)||(r[t]=Bp(e,n,r[t]));return r}function zp(e,t,n){return Oe(e)&&ve(n[t])}function qte(e,t,n){let r=tt(t.properties),i=k(n);for(let[t,a]of r)for(let r of i)!t.test(r)||zp(a,r,n)||(n[r]=Bp(e,a,n[r]));return z(t,`additionalProperties`)&&x(t.additionalProperties)?Rp(e,r,t.additionalProperties,n):n}function Jte(e,t,n){return Ze(n)?qte(e,t,n):n}function Yte(e,t,n){let r=tt(t.patternProperties),i=k(n);for(let[t,a]of r)for(let r of i)t.test(r)&&(n[r]=Bp(e,a,n[r]));return z(t,`additionalProperties`)&&x(t.additionalProperties)?Rp(e,r,t.additionalProperties,n):n}function Xte(e,t,n){return Ze(n)?Yte(e,t,n):n}function Zte(e,t,n){return z(e,t.$ref)?Bp(e,e[t.$ref],n):n}function Qte(e,t,n){let r=Ip(n);return Op(r)?r.value:n}function $te(e,t,n){return Bp(e,nt(t),n)}function ene(e,t,n){if(!lt(n))return n;for(let r=0;r<Math.min(t.items.length,n.length);r++)n[r]=Bp(e,t.items[r],n[r]);return n}function tne(e,t,n){let r=Lp(n);return Op(r)?r.value:n}function nne(e,t,n){if(t.anyOf.some(t=>op(e,t,n)))return n;let r=t.anyOf.map(t=>Bp(e,t,vp(n))).find(n=>op(e,t,n));return ve(r)?n:r}function rne(e,t,n){return Op(Lp(n))?void 0:n}function Bp(e,t,n){return ft(t)?Nte(e,t,n):Se(t)?Pte(e,t,n):fe(t)?Fte(e,t,n):ue(t)?Ite(e,t,n):ae(t)?Lte(e,t,n):ce(t)?Rte(e,t,n):Ee(t)?zte(e,t,n):S(t)?Wte(e,t,n):et(t)?Gte(e,t,n):_e(t)?Kte(e,t,n):le(t)?Jte(e,t,n):Je(t)?Xte(e,t,n):M(t)?Zte(e,t,n):we(t)?Qte(e,t,n):We(t)?$te(e,t,n):Le(t)?ene(e,t,n):at(t)?tne(e,t,n):T(t)?nne(e,t,n):ut(t)?rne(e,t,n):n}function Vp(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Bp(t,n,r)}function ine(e,t,n){if(!lt(n))return n;for(let r=0;r<n.length;r++)n[r]=Hp(e,t.items,n[r]);return n}function ane(e,t,n){return Hp({...e,...t.$defs},b(t.$ref),n)}function one(e,t){return ve(t)?St(e.default)?e.default():vp(e.default):t}function sne(e,t,n){let r=gt(e,t);return Hp(e,nt(r),n)}function cne(e,t,n){if(!x(n))return n;let r=k(t.properties);for(let i of r){let r=Hp(e,t.properties[i],n[i]);ve(r)&&(Oe(t.properties[i])||!z(t.properties[i],`default`))||(n[i]=r)}if(!jo(t)||qe(t.additionalProperties))return n;for(let i of k(n))r.includes(i)||(n[i]=Hp(e,t.additionalProperties,n[i]));return n}function lne(e,t,n){if(!x(n))return n;let[r,i]=[new RegExp(_t(t)),Ct(t)];for(let t of k(n))r.test(t)&&Lo(i)&&(n[t]=Hp(e,i,n[t]));if(!jo(t))return n;for(let i of k(n))r.test(i)||(n[i]=Hp(e,t.additionalProperties,n[i]));return n}function une(e,t,n){return z(e,t.$ref)?Hp(e,e[t.$ref],n):n}function dne(e,t,n){if(!lt(n))return n;let[r,i]=[t.items,Math.max(t.items.length,n.length)];for(let t=0;t<i;t++)t<r.length&&(n[t]=Hp(e,r[t],n[t]));return n}function fne(e,t,n){for(let r of t.anyOf){let t=Hp(e,r,vp(n));if(op(e,r,t))return t}return n}function Hp(e,t,n){let r=Lo(t)?one(t,n):n;return ft(t)?ine(e,t,r):ue(t)?ane(e,t,r):Ee(t)?sne(e,t,r):le(t)?cne(e,t,r):Je(t)?lne(e,t,r):M(t)?une(e,t,r):Le(t)?dne(e,t,r):T(t)?fne(e,t,r):r}function Up(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Hp(t,n,r)}function Wp(e){return(...t)=>{let[n,r,i]=ho(t,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return e.reduce((e,t)=>t(n,r,e),i)}}function pne(e,t,n){return t[`~codec`].decode(n)}function mne(e,t,n){return t[`~codec`].encode(n)}function Gp(e,t,n,r){return wt(n)?B(e,`Decode`)?pne(t,n,r):mne(t,n,r):r}function hne(e,t,n,r){if(!lt(r))return r;for(let i=0;i<r.length;i++)r[i]=Yp(e,t,n.items,r[i]);return Gp(e,t,n,r)}function gne(e,t,n,r){let i=Gp(e,t,n,r);if(!lt(i))return i;for(let r=0;r<i.length;r++)i[r]=Yp(e,t,n.items,i[r]);return i}function _ne(e,t,n,r){return B(e,`Decode`)?hne(e,t,n,r):gne(e,t,n,r)}function vne(e,t,n,r){return r=Yp(e,{...t,...n.$defs},b(n.$ref),r),Gp(e,t,n,r)}function Kp(e){return e.reduce((e,t)=>({...e,...t}),{})}function qp(e,t){for(let n of t)if(!Me(e,n))return n;return e}function yne(e,t,n,r){if(B(n.allOf.length,0))return Gp(e,t,n,r);let i=n.allOf.map(n=>Yp(e,t,n,Dp(n,vp(r))));return Gp(e,t,n,i.every(e=>x(e))?Kp(i):qp(r,i))}function bne(e,t,n,r){if(B(n.allOf.length,0))return Gp(e,t,n,r);let i=Gp(e,t,n,r),a=n.allOf.map(n=>Yp(e,t,n,Dp(n,vp(i))));return a.every(e=>x(e))?Kp(a):qp(i,a)}function xne(e,t,n,r){return B(e,`Decode`)?yne(e,t,n,r):bne(e,t,n,r)}function Sne(e,t,n,r){if(!Ze(r))return r;for(let i of k(n.properties))!z(r,i)||zp(n.properties[i],i,r)||(r[i]=Yp(e,t,n.properties[i],r[i]));return Gp(e,t,n,r)}function Cne(e,t,n,r){let i=Gp(e,t,n,r);if(!Ze(i))return i;for(let r of k(n.properties))!z(i,r)||zp(n.properties[r],r,i)||(i[r]=Yp(e,t,n.properties[r],i[r]));return i}function wne(e,t,n,r){return B(e,`Decode`)?Sne(e,t,n,r):Cne(e,t,n,r)}function Tne(e,t,n,r){if(!Ze(r))return r;let i=new RegExp(_t(n));for(let a of k(r))i.test(a)&&(r[a]=Yp(e,t,Ct(n),r[a]));return Gp(e,t,n,r)}function Ene(e,t,n,r){let i=Gp(e,t,n,r);if(!Ze(i))return i;let a=new RegExp(_t(n));for(let r of k(i))a.test(r)&&(i[r]=Yp(e,t,Ct(n),i[r]));return i}function Dne(e,t,n,r){return B(e,`Decode`)?Tne(e,t,n,r):Ene(e,t,n,r)}function Jp(e,t,n,r){return z(t,n.$ref)?Yp(e,t,t[n.$ref],r):r}function One(e,t,n,r){return B(e,`Decode`)?Gp(e,t,n,Jp(e,t,n,r)):Jp(e,t,n,Gp(e,t,n,r))}function kne(e,t,n,r){if(!lt(r))return r;for(let i=0;i<Math.min(n.items.length,r.length);i++)r[i]=Yp(e,t,n.items[i],r[i]);return Gp(e,t,n,r)}function Ane(e,t,n,r){let i=Gp(e,t,n,r);if(!lt(i))return r;for(let r=0;r<Math.min(n.items.length,i.length);r++)i[r]=Yp(e,t,n.items[r],i[r]);return i}function jne(e,t,n,r){return B(e,`Decode`)?kne(e,t,n,r):Ane(e,t,n,r)}function Mne(e,t,n,r){for(let i of n.anyOf)if(op(t,i,r))return Gp(e,t,n,Yp(e,t,i,r));return r}function Nne(e,t,n,r){let i=Gp(e,t,n,r);for(let r of n.anyOf){let n=Yp(e,t,r,vp(i));if(op(t,r,n))return n}return i}function Pne(e,t,n,r){return B(e,`Decode`)?Mne(e,t,n,r):Nne(e,t,n,r)}function Yp(e,t,n,r){return ft(n)?_ne(e,t,n,r):ue(n)?vne(e,t,n,r):Ee(n)?xne(e,t,n,r):le(n)?wne(e,t,n,r):Je(n)?Dne(e,t,n,r):M(n)?One(e,t,n,r):Le(n)?jne(e,t,n,r):T(n)?Pne(e,t,n,r):Gp(e,t,n,r)}var Fne=class extends cp{constructor(e,t){super(`Decode`,e,t)}};function Ine(e,t,n){if(!op(e,t,n))throw new Fne(n,sp(e,t,n));return n}function Lne(e,t,n){return Yp(`Decode`,e,st().unionPrioritySort?Ep(t):t,n)}const Rne=Wp([(e,t,n)=>vp(n),(e,t,n)=>Up(e,t,n),(e,t,n)=>Vp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>Ine(e,t,n),(e,t,n)=>Lne(e,t,n)]);function zne(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Rne(t,n,r)}var Bne=class extends cp{constructor(e,t){super(`Encode`,e,t)}};function Vne(e,t,n){if(!op(e,t,n))throw new Bne(n,sp(e,t,n));return n}function Hne(e,t,n){return Yp(`Encode`,e,st().unionPrioritySort?Ep(t):t,n)}const Une=Wp([(e,t,n)=>vp(n),(e,t,n)=>Hne(e,t,n),(e,t,n)=>Up(e,t,n),(e,t,n)=>Vp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>Vne(e,t,n)]);function Wne(...e){let[t,n,r]=ho(e,{3:(e,t,n)=>[e,t,n],2:(e,t)=>[{},e,t]});return Une(t,n,r)}function Gne(e,t){return wt(t)||Zp(e,t.items)}function Kne(e,t){return wt(t)||Xp({...e,...t.$defs},b(t.$ref))}function qne(e,t){return wt(t)||t.allOf.some(t=>Zp(e,t))}function Jne(e,t){return wt(t)||k(t.properties).some(n=>Zp(e,t.properties[n]))}function Yne(e,t){return wt(t)||Zp(e,Ct(t))}function Xp(e,t){return!Qp.has(t.$ref)&&(Qp.add(t.$ref),wt(t)||z(e,t.$ref)&&Zp(e,e[t.$ref]))}function Xne(e,t){return wt(t)||t.items.some(t=>Zp(e,t))}function Zne(e,t){return wt(t)||t.anyOf.some(t=>Zp(e,t))}function Zp(e,t){return ft(t)?Gne(e,t):ue(t)?Kne(e,t):Ee(t)?qne(e,t):le(t)?Jne(e,t):Je(t)?Yne(e,t):M(t)?Xp(e,t):Le(t)?Xne(e,t):T(t)?Zne(e,t):wt(t)}const Qp=new Set;function Qne(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return Qp.clear(),Zp(t,n)}var $p=class extends Error{constructor(e,t){super(t),this.type=e}};function $ne(e,t){return St(t.default)?t.default(t):x(t.default)?vp(t.default):t.default}function ere(e,t){if(Ss(t)&&!Lo(t))throw new $p(t,`Arrays with uniqueItems constraints must specify a default annotation`);let n=as(t)?t.minItems:0;return Array.from({length:n},()=>dm(e,t.items))}function tre(e,t){return Ko(t)?BigInt(t.exclusiveMinimum)+BigInt(1):rs(t)?BigInt(t.minimum):BigInt(0)}function nre(e,t){return!1}function rre(e,t){let n=dm(e,t.instanceType);return class{constructor(){Object.assign(this,n)}}}function ire(e,t){return dm({...e,...t.$defs},b(t.$ref))}function em(e,t){return dm(e,nt(t))}function tm(e,t){let n=dm(e,t.returnType);return()=>n}function nm(e,t){return Ko(t)&&$e(t.exclusiveMinimum)?t.exclusiveMinimum+1:rs(t)?t.minimum:0}function rm(e,t){let n=gt(e,t);return dm(e,nt(n))}function im(e,t){return t.const}function am(e,t){throw new $p(t,`Cannot create TNever types`)}function om(e,t){return null}function are(e,t){return Ko(t)&&$e(t.exclusiveMinimum)?t.exclusiveMinimum+1:rs(t)?t.minimum:0}function ore(e,t){return(ve(t.required)?[]:t.required).reduce((n,r)=>({...n,[r]:dm(e,t.properties[r])}),{})}function sre(e,t){if(ss(t)&&!Lo(t))throw new $p(t,`Record with the minProperties constraint must have a default annotation`);return{}}function cre(e,t){return z(e,t.$ref)?dm(e,e[t.$ref]):(()=>{throw new $p(t,`Unable to deref Ref`)})()}function lre(e,t){if((ds(t)||qo(t))&&!Lo(t))throw Error(`Strings with format or pattern constraints must specify default`);let n=os(t)?t.minLength:0;return``.padEnd(n)}function sm(e,t){return Symbol()}function cm(e,t){let n=Ce(t.pattern);if(we(n))throw new $p(t,`Unable to create TemplateLiteral due to infinite type expansion`);return dm(e,n)}function lm(e,t){return Array.from({length:t.minItems},(n,r)=>dm(e,t.items[r]))}function um(e,t){if(B(t.anyOf.length,0))throw Error(`Unable to create Union with no variants`);return dm(e,t.anyOf[0])}function dm(e,t){return Lo(t)?$ne(e,t):ft(t)?ere(e,t):Se(t)?tre(e,t):fe(t)?nre(e,t):iee(t)?rre(e,t):ue(t)?ire(e,t):ae(t)?em(e,t):He(t)?tm(e,t):ce(t)?nm(e,t):Ee(t)?rm(e,t):S(t)?im(e,t):je(t)?am(e,t):et(t)?om(e,t):_e(t)?are(e,t):le(t)?ore(e,t):Je(t)?sre(e,t):M(t)?cre(e,t):we(t)?lre(e,t):ee(t)?sm(e,t):We(t)?cm(e,t):Le(t)?lm(e,t):at(t)?void 0:T(t)?um(e,t):(ut(t),void 0)}function fm(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return dm(t,n)}var pm=class extends cp{constructor(e,t){super(`Parse`,e,t)}};function mm(e,t,n){if(!op(e,t,n))throw new pm(n,sp(e,t,n));return n}const hm=Wp([(e,t,n)=>vp(n),(e,t,n)=>Up(e,t,n),(e,t,n)=>Vp(e,t,n),(e,t,n)=>Dp(e,t,n),(e,t,n)=>mm(e,t,n)]),gm=ke({type:ie(`insert`),path:re(),value:dt()}),_m=Object({type:ie(`update`),path:re(),value:dt()}),vm=ke({type:ie(`delete`),path:re()});bt([gm,_m,vm]);var ym=class{constructor(e,t){this.hasCodec=Qne(e,t),this.buildResult=rp(e,t),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(st().correctiveParse)return hm(this.Context(),this.Type(),e);throw new pm(e,this.Errors(e))}Errors(e){return this.IsAccelerated()&&this.Check(e)?[]:sp(this.Context(),this.Type(),e)}Clean(e){return Dp(this.Context(),this.Type(),e)}Convert(e){return Vp(this.Context(),this.Type(),e)}Create(){return fm(this.Context(),this.Type())}Default(e){return Up(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?zne(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?Wne(this.Context(),this.Type(),e):this.Parse(e)}};function bm(...e){let[t,n]=ho(e,{2:(e,t)=>[e,t],1:e=>[{},e]});return new ym(t,n)}const xm=new WeakMap,Sm=Symbol.for(`TypeBox.Kind`);function Cm(e){return typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type.filter(e=>typeof e==`string`):[]}function wm(e,t){switch(t){case`number`:return typeof e==`number`;case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`string`:return typeof e==`string`;case`null`:return e===null;case`array`:return Array.isArray(e);case`object`:return typeof e==`object`&&!!e&&!Array.isArray(e);default:return!1}}function Tm(e){try{return Mm(e)}catch{return}}function Em(e,t){switch(t){case`number`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return typeof e==`boolean`?+!!e:e;case`integer`:if(e===null)return 0;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isInteger(t))return t}return typeof e==`boolean`?+!!e:e;case`boolean`:if(e===null)return!1;if(typeof e==`string`){if(e===`true`)return!0;if(e===`false`)return!1}if(typeof e==`number`){if(e===1)return!0;if(e===0)return!1}return e;case`string`:return e===null?``:typeof e==`number`||typeof e==`boolean`?String(e):e;case`null`:return e===``||e===0||e===!1?null:e;default:return e}}function Dm(e,t){let n=t.properties,r=new Set(n?Object.keys(n):[]);if(n)for(let[t,r]of Object.entries(n))t in e&&(e[t]=Am(e[t],r));if(t.additionalProperties&&typeof t.additionalProperties==`object`)for(let[n,i]of Object.entries(e))r.has(n)||(e[n]=Am(i,t.additionalProperties))}function Om(e,t){if(Array.isArray(t.items)){for(let n=0;n<e.length;n++){let r=t.items[n];r&&(e[n]=Am(e[n],r))}return}if(t.items&&typeof t.items==`object`)for(let n=0;n<e.length;n++)e[n]=Am(e[n],t.items)}function km(e,t){for(let n of t)if(Tm(n)?.Check(e))return e;for(let n of t){let t=Am(structuredClone(e),n);if(Tm(n)?.Check(t))return t}return e}function Am(e,t){let n=e;if(Array.isArray(t.allOf))for(let e of t.allOf)n=Am(n,e);Array.isArray(t.anyOf)&&(n=km(n,t.anyOf)),Array.isArray(t.oneOf)&&(n=km(n,t.oneOf));let r=Cm(t),i=r.length>1&&r.some(e=>wm(n,e));if(r.length>0&&!i)for(let e of r){let t=Em(n,e);if(t!==n){n=t;break}}return r.includes(`object`)&&typeof n==`object`&&n&&!Array.isArray(n)&&Dm(n,t),r.includes(`array`)&&Array.isArray(n)&&Om(n,t),n}function jm(e,t){if(Array.isArray(e)){if(Array.isArray(t.items))for(let n=0;n<e.length;n++){let r=t.items[n];r&&jm(e[n],r)}else if(t.items)for(let n of e)jm(n,t.items);return}if(typeof e!=`object`||!e||!t.properties)return;let n=e,r=new Set(t.required??[]);for(let[e,i]of Object.entries(t.properties))e in n&&(n[e]===null&&!r.has(e)&&typeof i.$ref!=`string`&&Tm(i)?.Check(null)===!1?delete n[e]:jm(n[e],i))}function Mm(e){let t=e,n=xm.get(t);if(n)return n;let r=bm(e);return xm.set(t,r),r}function ure(e){if(e.keyword===`required`){let t=e.params.requiredProperties?.[0];if(t){let n=e.instancePath.replace(/^\//,``).replace(/\//g,`.`);return n?`${n}.${t}`:t}}return e.instancePath.replace(/^\//,``).replace(/\//g,`.`)||`root`}function dre(e,t){let n=structuredClone(t.arguments);jm(n,e.parameters),Vp(e.parameters,n);let r=Mm(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(Sm)){let t=Am(n,e.parameters);if(t!==n)if(typeof n==`object`&&n&&typeof t==`object`&&t){for(let e of Object.keys(n))delete n[e];Object.assign(n,t)}else return r.Check(t)?t:n}if(r.Check(n))return n;let i=r.Errors(n).map(e=>` - ${ure(e)}: ${e.message}`).join(`
|
|
881
881
|
`)||`Unknown validation error`,a=`Validation failed for tool "${t.name}":\n${i}\n\nReceived arguments:\n${JSON.stringify(t.arguments,null,2)}`;throw Error(a)}function Nm(){throw Error(`No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().`)}async function fre(e,t,n,r,i,a){let o=[...e],s={...t,messages:[...t.messages,...e]};await r({type:`agent_start`}),await r({type:`turn_start`});for(let t of e)await r({type:`message_start`,message:t}),await r({type:`message_end`,message:t});return await Pm(s,o,n,i,r,a??Nm()),o}async function pre(e,t,n,r,i){if(e.messages.length===0)throw Error(`Cannot continue: no messages in context`);if(e.messages[e.messages.length-1].role===`assistant`)throw Error(`Cannot continue from message role: assistant`);let a=[],o={...e};return await n({type:`agent_start`}),await n({type:`turn_start`}),await Pm(o,a,t,r,n,i??Nm()),a}async function Pm(e,t,n,r,i,a){let o=e,s=n,c=!0,l=await s.getSteeringMessages?.()||[];for(;;){let e=!0;for(;e||l.length>0;){if(c?c=!1:await i({type:`turn_start`}),l.length>0){for(let e of l)await i({type:`message_start`,message:e}),await i({type:`message_end`,message:e}),o.messages.push(e),t.push(e);l=[]}let n=await mre(o,s,r,i,a);if(t.push(n),n.stopReason===`error`||n.stopReason===`aborted`){await i({type:`turn_end`,message:n,toolResults:[]}),await i({type:`agent_end`,messages:t});return}let u=n.content.filter(e=>e.type===`toolCall`),d=[];if(e=!1,u.length>0){let a=n.stopReason===`length`?await hre(u,i):await gre(o,n,s,r,i);d.push(...a.messages),e=!a.terminate;for(let e of d)o.messages.push(e),t.push(e)}await i({type:`turn_end`,message:n,toolResults:d});let f={message:n,toolResults:d,context:o,newMessages:t},p=await s.prepareNextTurn?.(f);if(p&&(o=p.context??o,s={...s,model:p.model??s.model,reasoning:p.thinkingLevel===void 0?s.reasoning:p.thinkingLevel===`off`?void 0:p.thinkingLevel}),await s.shouldStopAfterTurn?.({message:n,toolResults:d,context:o,newMessages:t})){await i({type:`agent_end`,messages:t});return}l=await s.getSteeringMessages?.()||[]}let n=await s.getFollowUpMessages?.()||[];if(n.length>0){l=n;continue}break}await i({type:`agent_end`,messages:t})}async function mre(e,t,n,r,i){let a=e.messages;t.transformContext&&(a=await t.transformContext(a,n));let o=await t.convertToLlm(a),s={systemPrompt:e.systemPrompt,messages:o,tools:e.tools},c=(t.getApiKey?await t.getApiKey(t.model.provider):void 0)||t.apiKey,l=await i(t.model,s,{...t,apiKey:c,signal:n}),u=null,d=!1;for await(let t of l)switch(t.type){case`start`:u=t.partial,e.messages.push(u),d=!0,await r({type:`message_start`,message:{...u}});break;case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:u&&(u=t.partial,e.messages[e.messages.length-1]=u,await r({type:`message_update`,assistantMessageEvent:t,message:{...u}}));break;case`done`:case`error`:{let t=await l.result();return d?e.messages[e.messages.length-1]=t:e.messages.push(t),d||await r({type:`message_start`,message:{...t}}),await r({type:`message_end`,message:t}),t}}let f=await l.result();return d?e.messages[e.messages.length-1]=f:(e.messages.push(f),await r({type:`message_start`,message:{...f}})),await r({type:`message_end`,message:f}),f}async function hre(e,t){let n=[];for(let r of e){await t({type:`tool_execution_start`,toolCallId:r.id,toolName:r.name,args:r.arguments});let e={toolCall:r,result:zm(`Tool call "${r.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Bm(e,t);let i=Vm(e);await Hm(i,t),n.push(i)}return{messages:n,terminate:!1}}async function gre(e,t,n,r,i){let a=t.content.filter(e=>e.type===`toolCall`),o=a.some(t=>e.tools?.find(e=>e.name===t.name)?.executionMode===`sequential`);return n.toolExecution===`sequential`||o?_re(e,t,a,n,r,i):vre(e,t,a,n,r,i)}async function _re(e,t,n,r,i,a){let o=[],s=[];for(let c of n){await a({type:`tool_execution_start`,toolCallId:c.id,toolName:c.name,args:c.arguments});let n=await Im(e,t,c,r,i),l;l=n.kind===`immediate`?{toolCall:c,result:n.result,isError:n.isError}:await Rm(e,t,n,await Lm(n,i,a),r,i),await Bm(l,a);let u=Vm(l);if(await Hm(u,a),o.push(l),s.push(u),i?.aborted)break}return{messages:s,terminate:Fm(o)}}async function vre(e,t,n,r,i,a){let o=[];for(let s of n){await a({type:`tool_execution_start`,toolCallId:s.id,toolName:s.name,args:s.arguments});let n=await Im(e,t,s,r,i);if(n.kind===`immediate`){let e={toolCall:s,result:n.result,isError:n.isError};if(await Bm(e,a),o.push(e),i?.aborted)break;continue}if(o.push(async()=>{let o=await Lm(n,i,a),s=await Rm(e,t,n,o,r,i);return await Bm(s,a),s}),i?.aborted)break}let s=await Promise.all(o.map(e=>typeof e==`function`?e():Promise.resolve(e))),c=[];for(let e of s){let t=Vm(e);await Hm(t,a),c.push(t)}return{messages:c,terminate:Fm(s)}}function Fm(e){return e.length>0&&e.every(e=>e.result.terminate===!0)}function yre(e,t){if(!e.prepareArguments)return t;let n=e.prepareArguments(t.arguments);return n===t.arguments?t:{...t,arguments:n}}async function Im(e,t,n,r,i){let a=e.tools?.find(e=>e.name===n.name);if(!a)return{kind:`immediate`,result:zm(`Tool ${n.name} not found`),isError:!0};try{let o=dre(a,yre(a,n));if(r.beforeToolCall){let a=await r.beforeToolCall({assistantMessage:t,toolCall:n,args:o,context:e},i);if(i?.aborted)return{kind:`immediate`,result:zm(`Operation aborted`),isError:!0};if(a?.block){let e=zm(a.reason||`Tool execution was blocked`);return a.terminate===!0&&(e.terminate=!0),{kind:`immediate`,result:e,isError:!0}}}return i?.aborted?{kind:`immediate`,result:zm(`Operation aborted`),isError:!0}:{kind:`prepared`,toolCall:n,tool:a,args:o}}catch(e){return{kind:`immediate`,result:zm(e instanceof Error?e.message:String(e)),isError:!0}}}async function Lm(e,t,n){let r=[],i=!0;try{let a=await e.tool.execute(e.toolCall.id,e.args,t,t=>{i&&r.push(Promise.resolve(n({type:`tool_execution_update`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,args:e.toolCall.arguments,partialResult:t})))});return i=!1,await Promise.all(r),{result:a,isError:!1}}catch(e){return i=!1,await Promise.all(r),{result:zm(e instanceof Error?e.message:String(e)),isError:!0}}finally{i=!1}}async function Rm(e,t,n,r,i,a){let o=r.result,s=r.isError;if(i.afterToolCall)try{let r=await i.afterToolCall({assistantMessage:t,toolCall:n.toolCall,args:n.args,result:o,isError:s,context:e},a);r&&(o={...o,content:r.content??o.content,details:r.details??o.details,usage:r.usage??o.usage,terminate:r.terminate??o.terminate},s=r.isError??s)}catch(e){o=zm(e instanceof Error?e.message:String(e)),s=!0}return{toolCall:n.toolCall,result:o,isError:s}}function zm(e){return{content:[{type:`text`,text:e}],details:{}}}async function Bm(e,t){await t({type:`tool_execution_end`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError})}function Vm(e){return{role:`toolResult`,toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,...e.result.addedToolNames?.length?{addedToolNames:e.result.addedToolNames}:{},isError:e.isError,timestamp:Date.now()}}async function Hm(e,t){await t({type:`message_start`,message:e}),await t({type:`message_end`,message:e})}function Um(e){return e.filter(e=>e.role===`user`||e.role===`assistant`||e.role===`toolResult`)}const Wm={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Gm={id:`unknown`,name:`unknown`,api:`unknown`,provider:`unknown`,baseUrl:``,reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function Km(e){let t=e?.tools?.slice()??[],n=e?.messages?.slice()??[];return{systemPrompt:e?.systemPrompt??``,model:e?.model??Gm,thinkingLevel:e?.thinkingLevel??`off`,get tools(){return t},set tools(e){t=e.slice()},get messages(){return n},set messages(e){n=e.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}var qm=class{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}drain(){if(this.mode===`all`){let e=this.messages.slice();return this.messages=[],e}let e=this.messages[0];return e?(this.messages=this.messages.slice(1),[e]):[]}clear(){this.messages=[]}},Jm=class{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;beforeToolCall;afterToolCall;shouldStopAfterTurn;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let t=e??{};this._state=Km(t.initialState),this.convertToLlm=t.convertToLlm??Um,this.transformContext=t.transformContext,this.streamFunction=t.streamFn??Nm(),this.getApiKey=t.getApiKey,this.onPayload=t.onPayload,this.onResponse=t.onResponse,this.beforeToolCall=t.beforeToolCall,this.afterToolCall=t.afterToolCall,this.shouldStopAfterTurn=t.shouldStopAfterTurn,this.prepareNextTurn=t.prepareNextTurn,this.prepareNextTurnWithContext=t.prepareNextTurnWithContext,this.steeringQueue=new qm(t.steeringMode??`one-at-a-time`),this.followUpQueue=new qm(t.followUpMode??`one-at-a-time`),this.sessionId=t.sessionId,this.thinkingBudgets=t.thinkingBudgets,this.transport=t.transport??`auto`,this.maxRetryDelayMs=t.maxRetryDelayMs,this.toolExecution=t.toolExecution??`parallel`}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before resetting.`);this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,t){if(this.activeRun)throw Error(`Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.`);let n=this.normalizePromptInput(e,t);await this.runPromptMessages(n)}async continue(){if(this.activeRun)throw Error(`Agent is already processing. Wait for completion before continuing.`);let e=this._state.messages[this._state.messages.length-1];if(!e)throw Error(`No messages to continue from`);if(e.role===`assistant`){let e=this.steeringQueue.drain();if(e.length>0){await this.runPromptMessages(e,{skipInitialSteeringPoll:!0});return}let t=this.followUpQueue.drain();if(t.length>0){await this.runPromptMessages(t);return}throw Error(`Cannot continue from message role: assistant`)}await this.runContinuation()}normalizePromptInput(e,t){if(Array.isArray(e))return e;if(typeof e!=`string`)return[e];let n=[{type:`text`,text:e}];return t&&t.length>0&&n.push(...t),[{role:`user`,content:n,timestamp:Date.now()}]}async runPromptMessages(e,t={}){await this.runWithLifecycle(async n=>{await fre(e,this.createContextSnapshot(),this.createLoopConfig(t),e=>this.processEvents(e),n,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async e=>{await pre(this.createContextSnapshot(),this.createLoopConfig(),e=>this.processEvents(e),e,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let t=e.skipInitialSteeringPoll===!0,n=this.shouldStopAfterTurn;return{model:this._state.model,reasoning:this._state.thinkingLevel===`off`?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,shouldStopAfterTurn:n?async e=>await n(e,this.signal):void 0,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async e=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(e,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>t?(t=!1,[]):this.steeringQueue.drain(),getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error(`Agent is already processing.`);let t=new AbortController,n=()=>{},r=new Promise(e=>{n=e});this.activeRun={promise:r,resolve:n,abortController:t},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(t.signal)}catch(e){await this.handleRunFailure(e,t.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,t){let n={role:`assistant`,content:[{type:`text`,text:``}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:Wm,stopReason:t?`aborted`:`error`,errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:`message_start`,message:n}),await this.processEvents({type:`message_end`,message:n}),await this.processEvents({type:`turn_end`,message:n,toolResults:[]}),await this.processEvents({type:`agent_end`,messages:[n]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case`message_start`:this._state.streamingMessage=e.message;break;case`message_update`:this._state.streamingMessage=e.message;break;case`message_end`:this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case`tool_execution_start`:{let t=new Set(this._state.pendingToolCalls);t.add(e.toolCallId),this._state.pendingToolCalls=t;break}case`tool_execution_end`:{let t=new Set(this._state.pendingToolCalls);t.delete(e.toolCallId),this._state.pendingToolCalls=t;break}case`turn_end`:e.message.role===`assistant`&&e.message.errorMessage&&(this._state.errorMessage=e.message.errorMessage);break;case`agent_end`:this._state.streamingMessage=void 0}let t=this.activeRun?.abortController.signal;if(!t)throw Error(`Agent listener invoked outside active run`);for(let n of this.listeners)await n(e,t)}};function Ym(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function Xm(e){let t=e.mimeType||`application/octet-stream`;return`${e.name} (${t}, ${Ym(e.size)})`}function Zm(e){let t=Xm(e);return e.kind===`image`&&e.data?e.path?`[Attached image: ${t} — full-resolution copy saved to ${e.path}]`:`[Attached image: ${t}]`:e.kind===`text`&&e.text!==void 0?[`----- BEGIN ATTACHMENT ${t} -----`,e.text,`----- END ATTACHMENT ${e.name} -----`].join(`
|
|
882
882
|
`):e.path?`[Attached ${e.kind===`image`?`image`:e.kind===`text`?`text file`:`file`} saved to ${e.path} — ${t}. Read it from the virtual filesystem when you need its contents.]`:e.error?`[Attachment not included: ${t}. ${e.error}]`:`[Attachment not included: ${t}. Unsupported binary attachment.]`}function Qm(e,t){if(!t?.length)return e;let n=t.map(Zm),r=e.trim();return r?`${r}\n\n${n.join(`
|
|
883
883
|
|
|
884
884
|
`)}`:n.join(`
|
|
885
885
|
|
|
886
886
|
`)}function $m(e){return e?.length?e.filter(e=>e.kind===`image`&&e.data).map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})):[]}const eh=`sessions`;function th(){return new Promise((e,t)=>{let n=indexedDB.open(`agent-sessions`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(eh)||e.createObjectStore(eh,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var nh=class{dbPromise=null;getDB(){return this.dbPromise||=th().then(e=>(e.onversionchange=()=>{e.close(),this.dbPromise=null},e.onclose=()=>{this.dbPromise=null},e)),this.dbPromise}async save(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(eh,`readwrite`).objectStore(eh).put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(eh,`readonly`).objectStore(eh).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async delete(e){let t=await this.getDB();return new Promise((n,r)=>{let i=t.transaction(eh,`readwrite`).objectStore(eh).delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async loadAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(eh,`readonly`).objectStore(eh).getAll();r.onsuccess=()=>t(r.result??[]),r.onerror=()=>n(r.error)})}async list(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(eh,`readonly`).objectStore(eh).getAll();r.onsuccess=()=>{t((r.result??[]).map(e=>({id:e.id,updatedAt:e.updatedAt})))},r.onerror=()=>n(r.error)})}async clearAll(){let e=await this.getDB();return new Promise((t,n)=>{let r=e.transaction(eh,`readwrite`).objectStore(eh).clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}static newId(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}static createSession(e,t){let n=Date.now();return{id:e,messages:[],config:t,createdAt:n,updatedAt:n}}static updateMessages(e,t){return{...e,messages:t,updatedAt:Date.now()}}};function rh(e){return e.parentJid===null}function ih(){return{filesystem:{kind:`full-workspace`},canCreateChildren:!0,canManageChildren:!0,canWriteSharedMemory:!0,canResolveApprovals:!0,approvalAuthority:`user`,sudoDefaultDisposition:`allow`,persistCommandGrants:!0}}function ah(e,t={}){return{filesystem:{kind:`restricted`,writablePaths:[...t.writablePaths??[]],visiblePaths:[...t.visiblePaths??[]]},canCreateChildren:!1,canManageChildren:!1,canWriteSharedMemory:!1,canResolveApprovals:!1,approvalAuthority:{parentId:e},sudoDefaultDisposition:`require-approval`,persistCommandGrants:!1}}function oh(e){return e.parentJid===null?ih():ah(e.parentJid,{writablePaths:e.config?.writablePaths,visiblePaths:e.config?.visiblePaths})}function sh(e){return e.parentJid===null?{mode:`interactive`}:e.notifyOnComplete===!1?{mode:`silent`}:{mode:`notify-parent`}}function ch(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(r);return n}function lh(e,t){if(!t)return;let n=new Map;for(let t of e)n.set(t.jid,t);let r=new Set,i=t;for(;i&&i.parentJid!==null&&!r.has(i.jid);)r.add(i.jid),i=n.get(i.parentJid);return i?.parentJid===null?i:void 0}function uh(e){let t=[];for(let n of e)n.parentJid===null&&t.push(n);return t.sort((e,t)=>e.addedAt.localeCompare(t.addedAt)||e.jid.localeCompare(t.jid))}function dh(e){return e.isCone===!0}function fh(e){Eh(e);let t=e;return delete t.isCone,delete t.type,rh(e)&&(e.trigger=void 0,e.requiresTrigger=!1,e.assistantLabel=e.assistantLabel||`sliccy`),e}const ph=`cone`;function mh(e){return`session-${e.folder}`}function hh(e){return rh(e)&&e.folder===`cone`}function gh(e){return e.toLowerCase().normalize(`NFKD`).replace(/\p{M}+/gu,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`cone`}function _h(e,t){let n=new Set;for(let e of t)n.add(e.folder);if(!n.has(`cone`))return ph;let r=`cone-${gh(e)}`;if(!n.has(r))return r;for(let e=2;;e++){let t=`${r}-${e}`;if(!n.has(t))return t}}function vh(e){return rh(e)?`cone`:`scoop`}function yh(e){return rh(e)?`cone`:e.name??e.folder}function bh(e){if(e.model)return e.model;let t=e.config?.modelId,n=e.config?.modelProviderId;return t!==void 0&&n!==void 0?{provider:n,id:t}:void 0}function xh(e){return e.model?.id??e.config?.modelId}function Sh(e){return e.model?.provider??e.config?.modelProviderId}function Ch(e){if(e.thinking)return e.thinking;let t=e.config?.thinkingLevel,n=e.config?.effortOverride;return t===void 0&&n===void 0?{}:{level:t,effortOverride:n}}function wh(e,t){return e.model=t?{provider:t.provider,id:t.id}:void 0,Dh(e),e}function Th(e,t){return e.thinking=t&&(t.level!==void 0||t.effortOverride!==void 0)?{level:t.level,effortOverride:t.effortOverride}:void 0,Oh(e),e}function Eh(e){let t=e.config;t&&(!e.model&&t.modelId!==void 0&&t.modelProviderId!==void 0&&(e.model={provider:t.modelProviderId,id:t.modelId}),!e.thinking&&(t.thinkingLevel!==void 0||t.effortOverride!==void 0)&&(e.thinking={level:t.thinkingLevel,effortOverride:t.effortOverride}),e.model&&Dh(e),e.thinking&&Oh(e))}function Dh(e){if(!e.config||e.config.modelId===void 0&&e.config.modelProviderId===void 0)return;let{modelId:t,modelProviderId:n,...r}=e.config;e.config=r}function Oh(e){if(!e.config||e.config.thinkingLevel===void 0&&e.config.effortOverride===void 0)return;let{thinkingLevel:t,effortOverride:n,...r}=e.config;e.config=r}function kh(e){switch(e){case`initializing`:return`creating`;case`processing`:return`running`;case`error`:return`failed`;case`ready`:return`ready`;default:return`creating`}}const Ah=`/workspace/skills`;function jh(e){if(rh(e)){if(hh(e))return{root:`/workspace`,memoryPath:`/workspace/CLAUDE.md`,scratch:`/tmp`};let t=`/cones/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:`/tmp`}}let t=`/scoops/${e.folder}`;return{root:`${t}/workspace`,memoryPath:`${t}/CLAUDE.md`,scratch:t}}const Mh=Object.freeze(jh({parentJid:null,folder:ph}));function Nh(e,t){let n=[...e],r=lh(n,t)??uh(n)[0];return r?jh(r):Mh}function Ph(e){let t=`${e.root}/`,n=`${Ah}/`;return n.startsWith(t)?[t]:[t,n]}function Fh(e,t){let n=rh(e);return{id:e.jid,parentId:e.parentJid,name:e.name,folder:e.folder,status:kh(t?.status),display:{role:n?`primary`:`child`,label:e.assistantLabel},workspace:jh(e),policy:oh(e),completion:sh(e)}}const Ih=`abject.abortive.abrasive.absolute.abstruse.abundant.abyssal.accessible.acerbic.acrid.adamant.adept.adlerian.adornian.adroit.adventurous.aeolian.aerated.aesthetic.affable.aged.ageless.agile.airborne.airlocked.airy.akkadian.alabaster.alacritous.alert.alien.alloyed.allusive.aloof.alpha.alpine.alternate.altruistic.amaranthine.amber.ambidextrous.ambivalent.ambrosial.amiable.amorphous.ample.analog.analytical.ancestral.ancient.angelic.animated.animist.anomalous.antediluvian.antic.antlered.apollinairian.apollonian.apt.aquatic.arbitrary.arcadian.arcane.archaic.archimedean.ardent.arduous.arendtian.argent.argentine.argive.aristotelian.armstrongian.aromatic.arresting.artful.arthurian.articulate.artificial.artisanal.artless.ascetic.ashen.ashy.asimovian.aspiring.assiduous.assyrian.asteroidal.astral.astute.asynchronous.athenian.atlantean.atomic.attentive.attic.audacious.audenesque.augmented.august.augustan.aureate.auric.auroral.austenian.austere.austral.authentic.autonomous.autumnal.avalonian.avid.avuncular.aztec.azure.babbagean.babylonian.bacchic.bachian.bactrian.ballardian.ballistic.balmy.banksian.barefoot.barreled.barthesian.bartokian.bashy.baudelairean.bayesian.beatific.beckettesque.beckettian.beethovenian.beguiling.bellicose.bemused.benevolent.benign.benjaminian.bergmanesque.beta.bewitched.binary.bionic.bismarckian.bitter.bitwise.blackened.blakean.blameless.bland.blazar.blazing.blended.blessed.blissful.blistered.blithe.blooming.blunt.blustery.boeotian.boggy.bohrian.boingy.boisterous.bold.bolted.bombastic.bonny.boolean.boreal.borgesian.borgian.bosky.botticellian.bottled.bouncy.boundless.bountiful.bourbon.bradburyan.brahmsian.braised.brambly.brash.brave.brazen.bready.breathless.brechtian.breezy.briared.briery.bright.brilliant.brined.briny.brisk.bristling.briton.brittenesque.broadband.brontean.bronzed.brooding.browned.browningesque.brucknerian.brumal.brusque.bubbling.bubbly.bucolic.budding.bunuelian.buoyant.burnished.burnt.buttered.buttery.bygone.byronic.bytewise.byzantine.cacophonous.caesarean.callow.calm.candescent.candid.candied.canny.cantorian.capable.capricious.caramelized.caravaggesque.carbon.carefree.carolingian.cartesian.carved.casked.cast.cavafian.cavalier.celebrated.celestial.celtic.ceramic.cerebral.ceremonious.cerulean.cervantine.cezannesque.chagallian.chalky.chaplinesque.charcoal.charismatic.charmed.charming.charred.chaucerian.cheeky.cheerful.chekhovian.cherished.cherubic.chewy.chilled.chilly.chimerical.chipper.chirpy.chivalrous.chopinesque.chromospheric.chronal.chthonic.chubby.chunky.churchillian.cimmerian.cindered.circumspect.circumstellar.citrusy.civil.clandestine.clangy.clarified.clarkean.classic.clement.clever.cloaked.clockwork.clompy.cloned.cloudlike.cloudy.clunky.clustered.coastal.cobalt.cognitive.coherent.coleridgean.colossal.coltranesque.comely.cometary.compiled.complacent.composite.concurrent.conradian.constablean.convivial.copernican.copious.coplandesque.cordial.corinthian.corked.cornelian.coronal.cortical.cosmic.coy.cozy.cracked.crackling.crafty.cranky.crashy.creamy.credible.crepuscular.cretan.crimson.crisp.crispy.crowned.crumbly.crunchy.crushed.cryo.cryofrozen.cryogenic.cryonic.cryptic.crystalline.cuddly.cumulative.cunning.cupric.cured.curious.cursed.cursory.cushy.cybernetic.cyberpunk.cynical.cyprian.daliesque.dancy.dandy.dantean.dantesque.dapper.dappled.daring.dark.darwinian.dashing.dashy.dauntless.davisian.dawning.dazzling.deathless.debonair.deboned.debussyan.decanted.decompiled.decorous.decrypted.deep.deferential.deft.degasian.delectable.deleuzian.delian.deliberate.delicate.delirious.delphic.delta.demure.depressurized.derridean.destined.devout.dewy.dexterous.diaphanous.diced.dickensian.dickian.dickinsonian.didactic.dieselpunk.diffident.digital.dignified.diligent.dimensional.dinky.dionysian.discerning.discreet.disheveled.disparate.distant.distinct.distributed.diurnal.divine.dizzy.docile.docked.dogged.doomed.dorian.dormant.dostoevskian.dotty.doughty.doughy.downy.dozy.draconic.dreamful.dreamy.drifting.dripping.drizzly.droll.drowsy.druidic.dulcet.dun.dunky.durkheimian.dusky.dwarven.dynamic.dystopian.eager.earnest.earthy.eastward.easygoing.ebony.ebullient.eclectic.eclipsed.ecstatic.edenic.edwardian.effervescent.effulgent.effusive.einsteinian.elamite.elastic.elated.eldritch.electric.electronic.elegant.elegiac.elgarian.eliotian.eliotic.elizabethan.ellingtonian.eloquent.elusive.elven.elvish.elysian.embered.emergent.eminent.emphatic.emulsified.enchanted.encoded.encrypted.endearing.endless.endogenous.energetic.enhanced.enigmatic.enthralling.ephemeral.epic.epicurean.equanimous.errant.erudite.escherian.esoteric.esteemed.eternal.ethereal.ethiopian.etruscan.euclidean.eulerian.euphonious.euphoric.evanescent.evening.eventide.everlasting.evocative.exacting.exalted.exemplary.exo.exogenous.expansive.expressive.exquisite.extraterrestrial.extruded.exuberant.fabled.fabulous.facetious.faithful.fallow.fanciful.fantastic.faradayic.faraway.farmhouse.fastidious.fated.fateful.fathomless.faulknerian.faunal.fearless.feathered.feathery.fecund.federated.feisty.felicitous.felliniesque.fenny.fermented.ferny.ferrous.fervent.fervid.festive.fetching.fey.fickle.fierce.fiery.filleted.filtered.fitzgeraldian.fizzy.flaky.flamboyant.flamed.flashy.flawless.fleecy.fleet.fleeting.flexible.flickering.flinty.floral.florid.flouncy.flourishing.flowering.fluent.fluffy.fluid.fluvial.foamy.folded.fond.foraged.forged.formidable.forthright.fortuitous.forward.foucauldian.fourier.fractal.fragrant.frank.frankish.freckled.free.fresh.freudian.friedmanite.frisky.frizzy.frolicsome.frosted.frosty.frothy.frozen.frugal.fruiting.fruity.funky.furred.furtive.futuristic.fuzzy.gaelic.galactic.galbraithian.galilean.gallant.gallic.galvanic.gamesome.gamma.gandhian.garlanded.garrulous.gauguinesque.gaussian.gauzy.generous.genetic.genial.genomic.genteel.gentle.geomagnetic.georgian.gershwinesque.ghostly.giant.gibsonian.giddy.gifted.giga.giggly.gilded.giottesque.glacial.glad.glazed.gleaming.gleeful.glimmering.glistening.glorious.glossy.glowing.gnomish.godardian.godelian.goethean.goethesque.gogolian.golden.gooey.goofy.gorgeous.gorsy.gossamer.gothic.gowned.goyaesque.graceful.gracious.grainy.grand.grassy.grated.gravitic.gregarious.grilled.groovy.ground.grounded.guileless.gushy.gusty.habermasian.habsburg.hadrianic.halcyon.hale.hallowed.haloed.halved.hamiltonian.han.handelian.handmade.handsome.hanoverian.hapless.happy.hardy.hardyesque.harmonious.hashed.haunted.haydnesque.hayekian.hazy.heady.heaneyesque.hearthside.hearty.heathen.heathered.heavenly.hegelian.heideggerian.heinesque.heinleinian.heirloom.heisenbergian.heliacal.hellenic.hellish.hemingwayesque.herbal.herbertian.herculean.hermetic.heroic.hexed.hibernal.hilbertian.histrionic.hitchcockian.hittite.hoar.hoary.hobbesian.hobbitish.hogarthian.holderlinian.holo.holographic.holy.homerian.homeric.homeward.honest.honeyed.honky.hooded.hooved.hopeful.hopkinsian.hopperesque.hoppy.horatian.horned.hospitable.hot.housemade.huggy.humble.humean.humming.humorous.hunky.hunnish.hurrian.hushed.hydraulic.hyper.hyperborean.hypersonic.hyperspatial.hypnotic.iberian.ibsenite.iced.icy.ideal.idyllic.igneous.illustrious.imaginative.immaculate.immense.immortal.impassioned.impeccable.impetuous.impish.impressive.incan.incandescent.incisive.incorrigible.indefatigable.indelible.indigo.indolent.indomitable.industrious.ineffable.inexorable.infernal.infinite.infra.infrared.infused.ingenious.ingenuous.inimitable.innocuous.inquisitive.insatiable.inspired.intense.intergalactic.interstellar.intragalactic.intrepid.intricate.intrinsic.intuitive.inventive.inveterate.invincible.inward.ionian.ionic.ionospheric.irenic.iridescent.irrepressible.ithacan.itinerant.ivory.jacobean.jammy.jangly.jaunty.jazzy.jeffersonian.jiggly.jingly.jocular.jocund.johnsonian.jolly.jouncy.jovial.jovian.joycean.joyful.joyous.jubilant.judicious.juiced.juicy.jumped.jumpy.jungian.junky.justinianic.jute.kafkaesque.kandinskian.kantian.keatonesque.keatsian.keen.keplerian.keynesian.kierkegaardian.kindly.kindred.kinetic.kiplingesque.klimtian.knowing.kooky.kubrickian.kurosawan.lacanian.laconic.lacquered.lacustrine.lacy.lamarckian.lambda.lambent.laminated.landed.languid.lanky.laplacian.larkinesque.laser.latent.lathed.latin.lattice.laudable.launched.laureled.lavish.layered.leaden.leafy.lean.learned.legendary.leguinian.leibnizian.lemian.lemurian.lenient.leonardesque.liberal.libyan.lidar.light.lighthearted.likable.lilac.lilting.liminal.limpid.lincolnesque.lingering.linnaean.lissome.lisztian.literate.lithe.littoral.lively.loamy.local.lockean.lofty.logical.loopy.loose.loquacious.lorcaesque.lorcan.lossless.lossy.lovecraftian.lovelacean.loyal.lucent.lucid.lucky.ludic.lukewarm.luminal.luminous.lunar.luscious.lush.lushy.lusitanian.lustrous.lydian.lynchian.lyotardian.lyric.lyrical.macerated.machiavellian.macro.magical.magnanimous.magnetar.magnetic.magnetospheric.magnificent.magrittean.mahlerian.majestic.mallarmean.malleable.malthusian.malty.mandelan.manetesque.manifold.marbled.marshy.martial.martian.marvelous.marxian.maser.masked.masterful.matchless.matin.matissean.mature.matutinal.mauve.maverick.mawkish.maxwellian.mayan.meandering.mechanical.median.medicean.mega.mellifluous.mellow.melodic.mendelian.merciful.mercurial.merovingian.merry.meshed.meta.metamorphic.meteoric.meticulous.metternichian.mettlesome.michelangelesque.micro.microwave.midnight.mighty.mild.milled.miltonian.miltonic.minced.mindful.mineral.ming.mingusian.minoan.minty.miraculous.mired.miroesque.mirthful.mischievous.misty.mobile.modest.modular.molecular.molieresque.momentous.mondrianesque.monetian.monkish.mono.montane.moonless.moonlit.mordant.morning.mossy.motley.mottled.mouthwatering.mozartian.mughal.multiversal.munificent.murmuring.mushy.musical.mutable.mutant.mycenaean.mysterious.mystical.mythic.nabokovian.nameless.nano.nanoscale.napoleonic.narrowband.nascent.natty.neat.nebular.nebulous.nefarious.neptunian.nerudian.networked.neural.neutron.neutronic.newtonian.nietzschean.nifty.nimble.noble.nocturnal.nonchalant.nonpareil.noontide.norse.northward.nostalgic.notable.novel.nozickian.nuanced.nubian.nuclear.numinous.nutty.oaky.obdurate.oblique.observant.obstinate.obtuse.oceanic.ochre.odyssean.olden.olympian.omega.omni.onward.opaline.opportune.optical.optimistic.opulent.oracular.orbital.orbiting.orderly.original.ornate.orphic.orwellian.osirian.ostentatious.otherworldly.otiose.ottoman.outgoing.outspoken.outward.overcast.overclocked.ovidian.pacific.pagan.painstaking.palatial.pale.pallid.palpable.paradisal.paradoxical.parallel.paramount.parkerish.parsonian.parthian.passionate.pastoral.patched.pathless.patient.pavlovian.peaceable.peaceful.peachy.pearly.peaty.pebbly.peeled.peered.peerless.pelagic.pellucid.penetrating.pensive.peppered.peppery.peppy.perceptive.perennial.perfect.perfumed.perky.persian.persistent.perspicacious.persuasive.pert.pervasive.pessoan.petaled.petrarchan.phantom.pharaonic.phased.philosophical.phlegmatic.phoenician.photonic.photospheric.phrygian.picassoesque.pickled.pictish.picturesque.pillowy.pindaric.pinteresque.piping.piquant.pirandellian.pithy.pivotal.pixelated.placid.planckian.planetary.planetoid.plangent.plasmic.plathian.platinum.platonic.playful.pleasant.plentiful.pliant.plinky.plonky.plucky.plumed.plummy.plush.plushy.plutonian.plutonic.pneumatic.poached.poesque.poetic.poignant.poised.polished.polite.pollockian.poly.polygonal.polymer.polynesian.popean.popped.popular.portly.posh.positronic.posthuman.potent.pouncy.powdery.powerful.pragmatic.prancy.precise.precocious.precognitive.preeminent.premier.prescient.pressed.pressurized.prestigious.pretty.primeval.primordial.princely.printed.pristine.private.prized.prodigious.profane.proficient.profound.profuse.prokofievian.prolific.promethean.prompt.proper.prophetic.prosaic.prosperous.protean.proto.protostellar.proud.proustian.providential.prudent.psionic.puccinian.puckish.pudgy.puffed.pulled.pulsar.punctilious.punctual.pungent.punic.pure.purposeful.pushkinian.pynchonesque.pythagorean.quaint.quantum.quartered.quasar.questing.quick.quiescent.quiet.quintessential.quirky.quixotic.rabelaisian.racinian.radar.radiant.radio.rainwashed.rainy.rakish.rambunctious.raphaelesque.rapid.rapturous.rare.rational.ravelian.rawlsian.raytraced.ready.reasonable.rebooted.receptive.recondite.recursive.redolent.reduced.reedy.refined.reflective.refulgent.regal.relativistic.relaxed.reliable.remarkable.rembrandtesque.remote.rendered.renoiresque.renowned.replete.replicated.resilient.resinous.resolute.resourceful.respectful.resplendent.responsive.restful.restive.restless.reticent.retro.reverent.rhapsodic.rhodian.rhythmic.ricardian.rich.richelieuvian.riemannian.rigorous.rilkean.rimbaudian.rimed.ringed.ripe.ripening.rippling.risible.riverine.riveted.roaming.roaring.roasted.robed.robotic.robust.rolled.roly.roman.romanov.romantic.rompy.rooseveltian.roseate.rosy.rothkoesque.rousing.rousseauian.rowdy.royal.rubenesque.ruddy.runic.rushy.russet.rustic.sabine.sable.sacred.sagacious.sage.saintly.salient.saline.salingeresque.salted.salty.salubrious.samian.sandaled.sandy.sanguine.sapid.sapient.sapphic.sardonic.sarmatian.sartrean.sassy.satiny.saturnian.saturnine.saucy.savory.savvy.saxon.scalding.scarlet.schielesque.schillerian.schoenbergian.scholarly.schubertian.schumannesque.schumpeterian.scintillating.scorched.scorsesean.scrappy.scruffy.scrupulous.scythian.seaborne.seamless.seared.seasonal.seaward.secure.sedate.sedgy.sedimentary.sedulous.seemly.seismic.selenic.selfless.sensible.sensitive.sentient.sentimental.seraphic.sere.serene.seuratian.shaded.shadowed.shadowy.shaggy.shaken.shakespearean.shamanic.shannonian.sharded.sharp.shaved.shavian.shelleyan.shielded.shimmering.shiny.shoreless.shostakovian.shrewd.shucked.sibelian.sibilant.sibylline.sicilian.sidereal.sienna.sifted.sigma.silicon.silken.silky.silly.silty.silver.silvered.simmering.simulated.sincere.singed.singing.singular.sinuous.sisyphean.sizzling.skeptical.skillful.skinnerian.skittish.skyward.sleek.sleepless.sleepy.slender.sliced.slick.slipstreamed.slow.sly.smart.smashy.smithian.smoked.smoky.smoldering.smooth.snappy.snazzy.snoozy.snowy.snug.snuggly.soaring.sociable.socratic.sodden.soft.sogdian.solar.solarpunk.solemn.solid.somnolent.sonar.song.sonic.sonorous.sooty.soporific.soulful.sound.soundless.sour.southward.sovereign.spaceborne.spacefaring.spacious.sparkling.sparkly.spartan.special.speckled.spectacular.spectral.speedy.spellbound.spiced.spicy.spielbergian.spiffy.spinozan.spirited.splashy.splendid.split.sploshy.spontaneous.spooky.sporty.spotless.spotted.sprightly.sproingy.spry.spun.spunky.squally.squashy.squelchy.squiggly.squishy.staid.stainless.stalwart.starborn.starfaring.starless.starlit.stasisbound.stately.steadfast.steady.steaming.steampunk.steely.steeped.steinbeckian.stellar.stellarborn.sticky.stirred.stirring.stoic.stoical.stolid.stompy.stoppardian.storied.stormy.stout.strained.stratospheric.straussian.stravinskian.streaky.stretched.striking.strindbergian.striped.strong.stuart.stubby.studious.stunning.sturdy.stygian.suave.subatomic.sublime.suborbital.subsonic.substantial.subtle.succinct.succulent.sudsy.sugared.sugary.sumerian.summery.sunless.sunlit.sunny.sunward.superb.supergalactic.superlative.superluminal.supersonic.supple.supreme.sure.surreptitious.svelte.swanky.sweeping.sweet.swift.swiftian.swirled.swooshy.sylvan.sympathetic.synaptic.synchronous.synthetic.syrupy.tableside.tachyonic.taciturn.talented.talleyrandian.tame.tang.tangy.tarantinoesque.tarkovskian.tart.tasteful.tattered.taut.tawny.tectonic.telekinetic.telepathic.temperate.tempered.temporal.tenacious.tender.tennysonian.tenuous.tepid.tera.terran.terrific.terse.textured.thackerayan.thankful.thawed.theban.thessalian.theta.thorny.thorough.thoughtful.thracian.threadbare.thriving.thundery.tidal.tidy.timeless.timely.timeworn.tinkly.tiny.tipsy.tireless.titanesque.titanian.titanic.titanium.titianesque.toasted.toasty.tocharian.tokenized.tolerant.tolkienesque.tolstoyan.tonic.tonky.toothsome.torched.totemic.tough.towering.trackless.tranquil.transcendent.transhuman.treacly.treasured.tremendous.tremulous.trenchant.tricky.trim.triumphant.trojan.trollopian.truculent.true.truffautian.truffled.trusty.truthful.tudor.turbo.turingian.turneresque.twangy.twilight.twilit.twinkling.twinkly.ubiquitous.ultra.ultrasonic.ultraviolet.umami.umber.unassuming.unbounded.uncanny.uncorked.unctuous.undaunted.underworldly.undocked.undying.unearthly.unerring.unflappable.unique.unknown.unruffled.upbeat.upgraded.upright.upstanding.upward.uranian.urbane.utopian.vacuous.valeryan.valiant.valorous.vandal.vangoghian.vast.veblenian.vectorized.vedic.vehement.veiled.velazquezian.velvet.velvety.venerable.venturous.venusian.veracious.verbose.verdant.verdian.verdurous.verlainian.vermeerian.vermilion.vernal.verneian.versatile.vesper.vespertine.vibrant.victorian.vigilant.vigorous.vintage.violet.virgilian.virtual.virtuous.visceral.vital.vivacious.vivid.vocal.voidborn.voidward.volcanic.voltairean.voluble.vonnegutian.voracious.voxel.vroomy.wacky.wagnerian.wakeful.waking.wan.wandering.warholian.warm.warped.wary.washingtonian.wayward.wealthy.weathered.weberian.welcome.welded.wellesian.wellsian.westward.whacky.whimsical.whimsy.whipped.whisked.whispering.whistlerian.whitmanesque.whole.wholesome.whooshy.wide.wiggly.wild.wildean.willowy.wilsonian.wily.windswept.windy.winged.winning.winsome.wintry.wired.wireframe.wireless.wise.wishful.wispy.wistful.wittgensteinian.witty.wobbly.wodehousian.wondrous.wonky.wooded.woody.woolly.woozy.wordless.wordsworthian.wormholed.worthy.wraithlike.wreathed.wriggly.wry.xenial.xeno.yanky.yearning.yeasty.yeatsian.young.youthful.yuletide.yummy.zany.zappy.zealous.zested.zestful.zesty.zeta.zingy.zippy.zodiacal.zonked.zonky.zoomy.zoroastrian`.split(`.`),Lh=`abalone.absinthe.absyrtus.accelerator.achilles.acorn.acquerello.actuator.adobo.adonis.aeetes.aegis.aello.aeneas.aengus.aether.affogato.afterburner.agartha.agate.agni.agnolotti.aioli.airlock.ajax.aji.albatross.alder.ale.alecto.aleppo.alfheim.allegory.alliteration.almond.amaranth.amaretto.amaterasu.ambrosia.americano.amphiaraus.anago.anapest.ancho.anchovy.android.andromeda.anise.annal.annwn.ansible.antaeus.antenna.anthem.antigone.antimony.antistrophe.anubis.aoidos.aperol.aphelion.aphrodite.apogee.apollo.apple.apricot.aquamarine.aquavit.aqueduct.arabica.arachne.arawn.arbor.arborio.arc.arcadia.arch.archipelago.ares.argo.argon.argonaut.aria.ariadne.ark.arke.armagnac.array.arrow.artemis.arthur.artichoke.artifact.arugula.asgard.asgardia.ash.asparagus.aspen.assam.assonance.asteroid.astronaut.atalanta.athena.atlantis.atlas.atoll.atom.atropos.aubergine.augean.aura.aurora.avalon.avalonia.avocado.awning.axion.axle.azurite.bacchus.bagna.baharat.balder.ballad.balladeer.banana.banshee.baozi.bard.barge.barium.barley.barn.basalt.basil.basilisk.basmati.bastet.bastion.bay.bayleaf.beacon.beam.bean.bearing.beech.beetroot.behemoth.bellini.beowulf.bergamot.berth.beryl.beryllium.bifrost.biodome.birch.biscotti.bismuth.bisque.bit.bittern.blackberry.blast.blaster.blini.block.blodeuwedd.bloodstone.blossom.bluebell.blueberry.bolt.bomba.bonito.boom.borage.boson.botargo.bottarga.bouillon.boundary.bow.bower.bragi.bramble.bran.branch.brandy.branwen.breeze.brew.bridge.brigid.brioche.broccoli.brook.brulee.brunhild.brush.bucatini.buckler.buckwheat.buffer.bulkhead.bunting.burrata.burst.bus.busiris.butte.butter.buttercup.butterscotch.byte.cabbage.cabin.cacao.cachaca.cache.cacus.cadence.caesura.calamarata.calamari.calcite.caldera.calliope.calvados.calypso.cam.camellia.camelot.camembert.campari.canal.cannelloni.cannoli.canopy.cantaloupe.cantata.canticle.canvas.canyon.canzone.capacitor.capellini.caper.capon.cappelletti.cappuccino.capsule.caramel.cardamom.cardoon.carillon.carnaroli.carnation.carol.carrier.carrot.cascade.cashew.cassandra.cassis.castle.castor.cavatelli.caviar.cayenne.cedar.celaeno.celeriac.cell.centaur.cerberi.cerberus.cernunnos.ceryneian.cesium.ceto.ceylon.chaff.chaffinch.chai.chain.chalk.chamomile.champagne.chandra.channel.chanson.chanterelle.chard.charon.chartreuse.cheddar.cherry.chert.chervil.chestnut.chickweed.chicory.chili.chime.chimera.chimichurri.chimney.chip.chipotle.chirashi.chiron.chive.chocolate.chorale.chorizo.chorus.chronicle.chrysanthemum.chrysaor.chrysomallus.chutney.ciabatta.cibola.cider.cilantro.cinder.cinnamon.cipher.circe.circlet.circuit.cirque.cistern.citadel.citrine.citron.clementine.cliff.clio.clipper.cloak.clotho.cloud.clove.clover.cluster.coal.cobbler.cockaigne.cockpit.cocoa.coconut.codex.coffee.cog.cognac.coif.coil.col.colchis.collider.colony.combe.comet.compote.concerto.conchiglie.conduit.confit.console.consomme.consonance.continuum.contour.cookies.coordinate.core.coriander.cormorant.corona.coronet.cortado.corvette.cosmos.cottage.couplet.course.couscous.cove.cowl.cowslip.crab.craft.crag.cranberry.crane.crayon.cream.creme.crepe.cress.crocus.croissant.crosne.crown.cruiser.crumble.cryopod.cryosleep.crystal.cuchulainn.cuckoo.cucumber.cuirass.cumin.cupid.curlew.currant.current.curry.custard.cyborg.cycle.cyclops.cyclotron.cylinder.dactyl.daedalus.daemon.daffodil.dagda.dahlia.daiquiri.dais.daisy.dale.dam.dandelion.danu.daphne.darjeeling.dart.dashi.date.dawn.daydream.deck.deirdre.demeter.destroyer.dew.diadem.diary.dill.dimension.diode.diomedean.dionysus.ditalini.ditch.djinn.dock.doenjang.domain.donburi.donjon.door.doppio.dove.downlink.dreadnought.dream.drift.droid.dryad.dukkah.dulce.dumpling.dune.durga.dusk.dust.dyke.eagle.earlgrey.easel.echidna.echo.eclair.eclipse.ecliptic.edamame.eddy.edelweiss.edge.egret.einsteinium.elderflower.eldorado.electra.elegy.elm.elysium.ember.endive.enigma.enjambment.enkidu.envoi.eos.epigram.epistle.epode.erato.erinyes.eros.erymanthian.escargot.espresso.estuary.eumenides.euryale.eurybia.eurydice.eurytion.excalibur.exoplanet.fable.fafnir.falcon.fancy.farfalle.fate.feather.feldspar.fell.fence.fennel.fenrir.fenugreek.fermion.fern.fettuccine.fiddlehead.field.fig.finch.finn.fionn.firebird.firefly.fission.fizz.fjord.flake.flame.flare.flash.flicker.flint.flue.fluorite.flux.flywheel.focaccia.fog.folio.fondant.forge.fortress.foxglove.fragment.fraise.frame.frangipane.frappe.freesia.fregola.freighter.freya.frigate.frigg.frost.fudge.fugue.fumarole.furies.fusilli.fusion.gaia.galahad.galangal.galatea.galaxy.galette.galleon.gallium.ganache.ganesh.gannet.gantry.ganymede.garam.gardenia.garlic.garuda.gateway.gauntlet.gawain.gazebo.gear.gelato.gemelli.genmaicha.genoise.geranium.germ.germanium.geryon.geyser.ghazal.ghee.ghost.gilgamesh.ginger.gingko.ginnungagap.girder.glacier.glade.glaze.gleam.gleeman.glen.glimmer.glint.glitter.gloss.glow.gluon.gnocchi.gochujang.goldfinch.golem.goose.gooseberry.gorgon.gouda.governor.gradient.graeae.granary.granite.grapefruit.grappa.gratin.graviton.greave.grebe.gremolata.grenadine.grendel.grid.griffin.gruyere.guajillo.guava.gudrun.guinevere.gunkan.gwydion.gyoza.gyroscope.habanero.habitat.hades.hadron.haiku.hall.halloumi.halo.halva.hamachi.hangar.hanuman.harissa.harpies.harpy.harvest.hatch.hauberk.hawthorn.haze.hazel.hazelnut.heading.headland.heap.heart.hearth.heather.hecate.hedge.heimdall.hel.helheim.helios.helium.helix.helle.hellebore.helm.hemistich.hephaestus.hera.hermes.heron.hesperides.hestia.hibiscus.hippogriff.hirame.hive.hoisin.hojicha.hollandaise.hollow.holly.hologram.honey.honeycomb.honeysuckle.hood.hoopoe.horizon.horseradish.horus.hrothgar.hub.huckleberry.hue.huginn.hull.husk.hut.hyacinth.hydra.hydras.hylas.hymn.hyperborea.hypercube.hyperdrive.hyperion.hyperspace.hyssop.iamb.ibis.icarus.idas.idunn.idyll.igniter.igraine.ikura.indium.indra.inductor.infusion.injector.ink.inlet.inspiration.ion.iridium.iris.ishtar.isis.isolde.isotope.ivy.iwashi.izanagi.jackdaw.jackfruit.jalapeno.janus.jasmine.jason.jasper.javelin.jay.jet.jiaozi.jongleur.jonquil.jormungandr.jotunheim.journal.julep.jumpgate.juniper.juno.jupiter.kaffir.kale.kali.kampachi.karaage.karasumi.katsu.keel.keep.kefir.kelpie.kenning.kernel.kestrel.khinkali.kiln.kimchi.kingfisher.kinmedai.kirsch.kite.kitsune.kiwi.koan.kohlrabi.kombucha.koshihikari.kraken.krypton.kumquat.kvass.lachesis.lacquer.ladon.ladons.laertes.lager.lagoon.lake.lakshmi.lambic.lament.lance.lancelot.lander.lane.langoustine.lantern.lapis.lark.larkspur.lasagna.latte.laureate.laurel.lava.lavender.leaf.leda.leek.legend.lemon.lemonbalm.lemongrass.lemuria.lens.lentil.lepton.lernaean.lethe.letter.levee.lever.leviathan.lightyear.lily.lime.limerick.limoncello.linden.linguine.link.linnet.lir.lithium.lityerses.lobster.loch.lock.lodge.loki.loop.loquat.lotus.lovage.lugh.lullaby.lungo.luster.lychee.lynceus.lyonesse.lyricist.macadamia.macaron.macchiato.madai.madeleine.madrigal.magma.magnolia.magpie.mail.mainframe.maki.makrut.malachite.manannan.mango.manicotti.manor.manti.manticore.mantle.mantou.manuscript.maple.marble.marduk.margarita.marigold.marjoram.marquee.marrow.martini.marvel.marzipan.masago.masala.mascarpone.mast.matcha.matrix.mead.meadow.mech.medea.medusa.megaera.meleager.memoir.mentaiko.mercury.meringue.merlin.merlot.mesa.mesh.metaphor.meteor.meter.mezcal.mezzaluna.mica.midas.midgard.mill.mimir.mimosa.minerva.minotaur.minstrel.mint.minuet.miracle.mirin.mirror.miso.missive.mist.mjolnir.mocha.module.moira.mojito.molasses.mole.momo.monolith.moonbase.moonbeam.moonstone.moor.mopsus.mordred.morel.morgana.morpheus.morrigan.moss.mote.motet.mousse.mu.mulberry.muninn.muon.muse.muspelheim.mustard.myrtle.mystery.myth.nadir.naga.naiad.nanite.nanobot.narcissus.neapolitan.nebula.nectarine.needle.negroni.nemean.nemesis.neon.neptune.neptunium.nereid.nereus.nessus.nest.nestor.net.nettle.neutrino.nexus.niamh.nib.nibble.nibiru.niflheim.nightingale.nigiri.nike.niobe.njord.nocturne.node.nog.nori.norn.note.nougat.nova.nozzle.nuada.nutmeg.nyx.oak.oasis.oat.obelisk.oberon.obsidian.oceanid.oceanus.octave.octavo.ocypete.ode.odin.odysseus.oisin.okonomiyaki.olive.olympus.oni.onigiri.oolong.oracle.orange.orb.orbit.orbiter.orchard.orchid.oreads.orecchiette.oregano.orion.orpheus.orthros.orthrus.orzo.oscillator.osiris.osmium.osprey.ouroboros.outline.outpost.ouzo.oven.overture.owl.oyster.paccheri.packet.padron.page.palace.palette.palladium.palm.pan.pandan.pandora.panettone.pansotti.pansy.pantoum.papaya.pappardelle.paprika.papyrus.parable.paradox.parcae.parchment.parfait.parmesan.parsec.parsley.parsnip.particle.partridge.parvati.pasilla.passionfruit.pastel.pastis.patina.pavilion.pavlova.peach.peak.pear.pebble.pecan.pegasi.pegasus.pekoe.peleus.pelican.pelmeni.pen.pencil.penelope.penne.peony.pepper.peppermint.percival.peregrine.pergola.peridot.perigee.perihelion.perry.persephone.perseus.persillade.persimmon.pesto.petal.petrel.phase.pheasant.phoenix.pholus.phorcys.photon.phrixus.pickle.pierogi.pigment.pimento.pine.pineapple.ping.pinot.pipe.pipit.piquillo.pisco.pistachio.piston.pith.plane.plasma.plate.plover.plum.plume.pluto.plutonium.poblano.pod.podarge.poet.polenta.pollux.polyphemus.pomegranate.pomelo.pond.pontus.ponzu.pooka.pool.poplar.poppy.porcini.port.portal.porter.porthole.poseidon.positron.prairie.praline.prelude.primrose.prism.probe.profile.prometheus.prosciutto.prosecco.proteus.protocol.psalm.psyche.pudding.puffin.pulse.pumice.pumpkin.purslane.pwyll.pylon.pyrrhic.quadrant.quail.quark.quarto.quartz.quatrain.qubit.quetzalcoatl.queue.quill.quince.quinoa.quiver.radish.radium.radon.ragnarok.rain.rama.ramen.ramp.rampart.ramson.raspberry.ratatoskr.raven.ravioli.ray.reactor.realm.reaper.reed.reef.refrain.region.register.relay.relic.remnant.requiem.reservoir.residue.resistor.resonator.reverie.rhapsode.rhapsody.rhea.rhiannon.rhodium.rhododendron.rhubarb.rhyme.ricotta.riddle.ridge.riesling.rigatoni.rim.ring.risotto.ristretto.river.roast.robin.robusta.roc.rocket.rod.romesco.rondeau.rooibos.rook.root.rose.rosemary.rosewater.roundel.rover.rowan.rubidium.rum.rune.saba.saffron.saga.saison.sake.salmoriglio.salsa.salsify.sambal.sambuca.samphire.sancerre.sandpiper.sangria.sanma.sansho.saraswati.sashimi.sasquatch.satellite.satyr.sauternes.savanna.sawara.sazerac.scaffold.scalar.scallop.scansion.scepter.schnapps.schooner.scop.scorzonera.scotchbonnet.scroll.sector.seed.sekhmet.selene.selenite.selenium.selkie.sencha.sensor.sequoia.serenade.serrano.servo.sesame.sestina.sextet.shack.shade.shadow.shaft.shale.shallot.shambhala.shard.shed.sheen.sherbet.sherry.shield.shimmer.ship.shishito.shiso.shiva.shoyu.shrub.shumai.shuttle.sibyl.sif.signal.sigurd.silhouette.silo.simile.simurgh.singularity.siren.sita.skadi.skald.skiff.skuld.skylark.slant.slate.sleipnir.sling.slipstream.sliver.sloop.sluice.smithy.smoke.snowdrop.socket.sofrito.sonata.sonnet.soot.sorbet.sorrel.souffle.soul.soy.spaceport.spaghetti.spark.sparkle.sparrow.spear.speck.specter.speculoos.spelt.sphere.sphinx.sphinxes.spindle.spinel.spiral.spire.spirit.splinter.spoke.spondee.spore.spring.spritz.spruce.sriracha.ssamjang.stack.stanza.starbase.starlight.starling.starport.starship.stasis.station.steam.stellarator.steppe.stheno.stork.stracciatella.strawberry.stream.strontium.strophe.strozzapreti.strut.stylus.stymphalian.styx.subspace.sumac.summit.sunbeam.sunstone.supernova.surge.surya.susanoo.sushi.svartalfheim.swallow.swan.swarm.sycamore.syleus.synchrotron.tabard.tachyon.tagliatelle.tahini.takoyaki.taliesin.tamari.tamarind.tangerine.tanka.tanker.tapenade.tapioca.tarako.taranis.tare.tarn.tarragon.tartarus.telamon.telemetry.teleporter.tellurium.temaki.tempura.tengu.tensor.tent.tequila.tercet.teriyaki.terminal.tern.terraform.tesseract.tethys.thalassa.thalia.thallium.thaumas.themis.theseus.thistle.thor.thorium.thoth.threshold.throne.throttle.thrush.thruster.thule.thunderbird.thyme.tiamat.tiara.tide.tint.tintagel.tiphys.tiramisu.tirnanog.tisane.tisiphone.titan.tobiko.toccata.toddy.toffee.tofu.tokamak.tomatillo.tomato.tome.tone.tonka.tonkatsu.tor.tortellini.torus.tourmaline.tower.trace.track.transducer.transistor.treacle.trellis.triolet.tristan.triton.trochee.trofie.trope.troubadour.trouvere.truffle.trunk.truss.tug.tulip.tundra.tungsten.turbine.turmeric.turquoise.turret.twinkle.typhon.tyr.udon.ulysses.unagi.uni.unicorn.uplink.uramaki.urania.uranium.urd.urfa.uther.vale.valhalla.valkyrie.valve.vanadium.vanaheim.vanilla.vapor.vareniki.varnish.varuna.vector.veil.vellum.vent.venus.verbena.verdandi.verge.verjus.vermouth.verse.vessel.vesta.vestige.vialone.viewport.villanelle.vishnu.vodka.volcano.volta.volume.vortex.vulcan.wall.walnut.waltz.warbler.warpgate.wasabi.wash.watercress.watermelon.wave.waypoint.web.weir.well.wendigo.wheat.whisky.whisper.wiglaf.willow.wimple.window.wisteria.wonder.wonton.woodcock.woodpecker.word.wormhole.wraith.wren.wyrm.wyvern.xenon.yacht.yakitori.yama.yarrow.yeti.yew.yggdrasil.yokai.yuzu.zaatar.zabaglione.zenith.zephyr.zeus.zinnia.zircon.zirconium.ziti.zone.zucchini`.split(`.`);Ih.length*Lh.length;function Rh(e){let t=fee(e.messages,{source:e.name}),n=t.filter(e=>e.role===`assistant`).length,r=[`# Agent session: ${e.name}`,``,`- jid: ${e.jid}`,`- exit code: ${e.exitCode}`,`- turns: ${n}`,`- messages: ${e.messages.length}`,`- timestamp: ${e.timestamp}`,``,`## Prompt`,``,e.prompt.length>0?e.prompt:`_(empty prompt)_`,``,`---`,``];if(t.length===0)r.push(`_(no messages captured)_`,``);else for(let e of t)zh(r,e);return r.join(`
|
|
887
|
-
`)}function zh(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])Bh(e,n)}function Bh(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",Vh(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function Vh(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const Hh=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function Uh(e){return typeof e==`string`&&Hh.includes(e)}const Wh=r(`agent-bridge`),Gh=`__slicc_agent`;function Kh(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${ug(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function qh(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=xh(n);if(!r||r.length===0)return null;let i=Sh(n);return i?{modelId:r,providerId:i}:{modelId:r}}function Jh(e,t){let n=e.getWorkUnits();return Ph(((t===null?null:n.rootOf(t))??n.resolveDefaultRoot())?.descriptor.workspace??Mh)}function Yh(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Ch(n).level;return r&&Uh(r)?r:null}function Xh(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!Uh(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${Hh.join(`, `)})`,exitCode:1}};let o=e.backgroundAfterSeconds;if(o!==void 0&&(typeof o!=`number`||!Number.isFinite(o)||o<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(o)} (seconds >= 0)`,exitCode:1}};let s=e.successReceiptPath;if(s!==void 0&&!s.startsWith(`/`))return{error:{finalText:`agent: successReceiptPath must be absolute: ${s}`,exitCode:1}};let c=e.name;if(c!==void 0&&!$h(c))return{error:{finalText:`agent: invalid name: ${c} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}async function Zh(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){Wh.warn(`success receipt write failed`,{path:t,error:gg(e)})}}const Qh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function $h(e){return Qh.test(e)}async function eg(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=Rh({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){Wh.warn(`agent session archive write failed`,{path:s,error:gg(e)})}}function tg(e,t,n,r,i,a){let o=fg(e.cwd),s={visiblePaths:mg(e,a),writablePaths:hg([...pg(e.writablePaths,o),`${i}/`,`/tmp/`]),allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(s.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(s.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(s.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(s.modelId=t,n!==void 0&&(s.modelProviderId=n)),r!==void 0&&(s.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(s.structuredOutputSchema=e.structuredOutputSchema),s}function ng(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function rg(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function ig(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){Wh.warn(`unregisterScoop failed`,{jid:t,error:gg(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){_g(e,`ENOENT`)||Wh.warn(`scratch folder cleanup failed`,{folder:n,error:gg(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){Wh.warn(`sessionStore.delete failed`,{jid:t,error:gg(e)})}}async function ag(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??gg(e),exitCode:1}}try{let n=await rg(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n?(n.exitCode===0&&t.successReceiptPath&&await Zh(e.sharedFs,t.successReceiptPath),n):{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??gg(e),exitCode:1}}}function og(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??lg,generateUid:r.generateUid??cg,resolveModel:r.resolveModel??dg};async function a(e){let t=Xh(e,i.resolveModel);if(`error`in t)return t.error;let n=qh(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??Yh(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?Kh(i):e.name,c=`agent-${s}`,l=`agent_${ug(s)}`;if(e.name!==void 0&&i.orchestrator.getScoops().some(e=>e.jid===l))return{finalText:`agent: name already in use: ${s}`,exitCode:1};let u=`/scoops/${c}`,d=e.parentJid??uh(i.orchestrator.getScoops())[0]?.jid??null,f=tg(e,r,a,o,u,Jh(i.orchestrator,d)),p={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:f,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:d},m=ng(i.orchestrator,l),h=()=>{try{i.orchestrator.stopScoop(l)}catch(e){Wh.warn(`stopScoop on abort failed`,{jid:l,error:gg(e)})}};if(e.signal?.addEventListener(`abort`,h,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,h),m.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let g={finalText:``,exitCode:1};try{return g=await ag(i,e,p,l,m),g}finally{e.signal?.removeEventListener(`abort`,h),m.unsubscribe?.(),await eg(i,e,l,s,g),await ig(i,l,c,u)}}return{spawn:a}}function sg(e,t,n=null,r={}){let i=og(e,t,n,r);return globalThis[Gh]=i,Wh.info(`agent bridge published on globalThis.__slicc_agent`),i}function cg(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function lg(){return`${Ih[Math.floor(Math.random()*Ih.length)]}-${Lh[Math.floor(Math.random()*Lh.length)]}`}function ug(e){return e.replace(/-/g,`_`)}function dg(e){try{return L(e)}catch(t){return Wh.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function fg(e){let t=Pt(e);return t.endsWith(`/`)?t:`${t}/`}function pg(e,t){let n=[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?n:e.map(fg)}function mg(e,t){if(e.visiblePaths!==void 0)return e.visiblePaths.map(fg);let n=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&n.push(fg(e.invokingCwd)),hg(n)}function hg(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function gg(e){return e instanceof Error?e.message:String(e)}function _g(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const vg=`sessions`;function yg(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(vg)||e.createObjectStore(vg,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var bg=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await yg();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readwrite`);i.objectStore(vg).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readonly`).objectStore(vg).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(vg,`readonly`).objectStore(vg).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readwrite`);i.objectStore(vg).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};async function xg(e,t,n){let r=await n({method:`GET`,path:`/${e}/sites/${t}/config.json`,origin:nn});if(r.status===401||r.status===403)throw Error(`not authorized to read the site config for ${e}/${t} — log in via Settings → Providers → Adobe, or pass --backend to skip the probe`);if(r.status===404)throw Error(`no site config for ${e}/${t} — check the org and site names`);if(r.status>=400)throw Error(`site config probe failed for ${e}/${t}: ${r.status}`);let i;try{i=await r.json()}catch(n){throw Error(`site config for ${e}/${t} is not JSON: ${n instanceof Error?n.message:String(n)}`)}let a=i.content?.source?.url;return{backend:Sg(a),sourceUrl:a}}function Sg(e){if(!e)return`da`;let t;try{t=new URL(e).host}catch{return`da`}return t===`api.aem.live`?`aem`:`da`}const Cg=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`bash`,`sudo-request`,`preview`,`discovery`]);function wg(e){return e!=null&&Cg.has(e)}const Tg={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,bash:`Background Command`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function Eg(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`bash`:return e.bashJobId;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Dg(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=gee(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=Fg(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function Og(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
|
|
887
|
+
`)}function zh(e,t){e.push(`## ${t.role}`,``);let n=t.content.trim();n.length>0&&e.push(n,``);for(let n of t.toolCalls??[])Bh(e,n)}function Bh(e,t){e.push(`### tool: ${t.name}`,``,`Input:`,``,"```json",Vh(t.input),"```",``),t.result!==void 0&&e.push(t.isError?`Result (error):`:`Result:`,``,"```",t.result,"```",``)}function Vh(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return String(e)}}const Hh=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function Uh(e){return typeof e==`string`&&Hh.includes(e)}const Wh=r(`agent-bridge`),Gh=`__slicc_agent`;function Kh(e){for(let t=0;t<8;t++){let t=e.generateName(),n=`agent_${ug(t)}`;if(!e.orchestrator.getScoops().some(e=>e.jid===n))return t}return e.generateUid()}function qh(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=xh(n);if(!r||r.length===0)return null;let i=Sh(n);return i?{modelId:r,providerId:i}:{modelId:r}}function Jh(e,t){let n=e.getWorkUnits();return Ph(((t===null?null:n.rootOf(t))??n.resolveDefaultRoot())?.descriptor.workspace??Mh)}function Yh(e,t){if(t===void 0)return null;let n=e.getScoops().find(e=>e.jid===t);if(!n)return null;let r=Ch(n).level;return r&&Uh(r)?r:null}function Xh(e,t){let n=e.modelId,r,i;if(n!==void 0){let a=e.modelProviderId!==void 0&&n!==``?`${e.modelProviderId}:${n}`:n,o=a===``?{ok:!1,error:`unknown model: ${n}`}:t(a);if(!o.ok)return{error:{finalText:`agent: ${o.error}`,exitCode:1}};r=o.selection.modelId,i=o.selection.providerId}let a=e.thinkingLevel;if(a!==void 0&&!Uh(a))return{error:{finalText:`agent: invalid thinking level: ${String(a)} (one of: ${Hh.join(`, `)})`,exitCode:1}};let o=e.backgroundAfterSeconds;if(o!==void 0&&(typeof o!=`number`||!Number.isFinite(o)||o<0))return{error:{finalText:`agent: invalid backgroundAfterSeconds: ${String(o)} (seconds >= 0)`,exitCode:1}};let s=e.successReceiptPath;if(s!==void 0&&!s.startsWith(`/`))return{error:{finalText:`agent: successReceiptPath must be absolute: ${s}`,exitCode:1}};let c=e.name;if(c!==void 0&&!$h(c))return{error:{finalText:`agent: invalid name: ${c} (lowercase tokens joined by single dashes)`,exitCode:1}};for(let[t,n]of[[`maxTurns`,e.maxTurns],[`maxWallClockMs`,e.maxWallClockMs]])if(n!==void 0&&(!Number.isInteger(n)||n<=0))return{error:{finalText:`agent: ${t} must be a positive integer: ${String(n)}`,exitCode:1}};return{resolvedModelId:r,resolvedProviderId:i}}async function Zh(e,t){try{let n=t.slice(0,t.lastIndexOf(`/`));n&&await e.mkdir(n,{recursive:!0}),await e.writeFile(t,new Date().toISOString())}catch(e){Wh.warn(`success receipt write failed`,{path:t,error:gg(e)})}}const Qh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function $h(e){return Qh.test(e)}async function eg(e,t,n,r,i){if(t.persistSession===!1)return;let a=t.persistSession===!0?`/sessions`:`/tmp`,o=new Date().toISOString().replace(/[:.]/g,`-`),s=`${a}/agent-${r}-${o}.md`;try{let c=e.orchestrator.getScoopContext(n),l=typeof c?.getAgentMessages==`function`?c.getAgentMessages():[],u=Rh({name:r,jid:n,prompt:t.prompt,exitCode:i.exitCode,messages:l,timestamp:o});await e.sharedFs.mkdir(a,{recursive:!0}),await e.sharedFs.writeFile(s,u)}catch(e){Wh.warn(`agent session archive write failed`,{path:s,error:gg(e)})}}function tg(e,t,n,r,i,a){let o=fg(e.cwd),s={visiblePaths:mg(e,a),writablePaths:hg([...pg(e.writablePaths,o),`${i}/`,`/tmp/`]),allowedCommands:e.allowedCommands};return e.maxTurns!==void 0&&(s.maxTurns=e.maxTurns),e.maxWallClockMs!==void 0&&(s.maxWallClockMs=e.maxWallClockMs),e.backgroundAfterSeconds!==void 0&&(s.backgroundAfterSeconds=e.backgroundAfterSeconds),t&&(s.modelId=t,n!==void 0&&(s.modelProviderId=n)),r!==void 0&&(s.thinkingLevel=r),e.structuredOutputSchema!==void 0&&(s.structuredOutputSchema=e.structuredOutputSchema),s}function ng(e,t){let n={sendMessages:[],responseBuffer:``,scoopError:null,unsubscribe:null};return n.unsubscribe=e.observeScoop(t,{onSendMessage:e=>{n.sendMessages.push(e)},onResponse:(e,t)=>{t?n.responseBuffer+=e:n.responseBuffer=e},onError:e=>{n.scoopError===null&&(n.scoopError=e)}}),n}async function rg(e,t,n,r,i){if(await e.sendPrompt(t,n,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};if(r){let n=e.getScoopContext(t),r=n?.getStructuredOutput?.();for(let a=0;a<2&&!r?.captured;a++){if(await e.sendPrompt(t,`You did not call StructuredOutput. Call it now with your result, matching the schema.`,`agent`,`agent`),i.scoopError!==null)return{finalText:i.scoopError,exitCode:1};r=n?.getStructuredOutput?.()}return r?.captured?{finalText:JSON.stringify(r.value),exitCode:0}:{finalText:`agent: scoop did not produce StructuredOutput`,exitCode:1}}return{finalText:i.sendMessages.length>0?i.sendMessages[i.sendMessages.length-1]:i.responseBuffer,exitCode:0}}async function ig(e,t,n,r){try{await e.orchestrator.unregisterScoop(t)}catch(e){Wh.warn(`unregisterScoop failed`,{jid:t,error:gg(e)})}try{await e.sharedFs.rm(r,{recursive:!0})}catch(e){_g(e,`ENOENT`)||Wh.warn(`scratch folder cleanup failed`,{folder:n,error:gg(e)})}if(e.sessionStore)try{await e.sessionStore.delete(t)}catch(e){Wh.warn(`sessionStore.delete failed`,{jid:t,error:gg(e)})}}async function ag(e,t,n,r,i){try{await e.orchestrator.registerScoop(n)}catch(e){return{finalText:i.scoopError??gg(e),exitCode:1}}try{let n=await rg(e.orchestrator,r,t.prompt,t.structuredOutputSchema,i);return t.signal?.aborted?{finalText:`agent: aborted`,exitCode:1}:n?(n.exitCode===0&&t.successReceiptPath&&await Zh(e.sharedFs,t.successReceiptPath),n):{finalText:i.scoopError??``,exitCode:1}}catch(e){return{finalText:i.scoopError??gg(e),exitCode:1}}}function og(e,t,n=null,r={}){let i={orchestrator:e,sharedFs:t,sessionStore:n,generateName:r.generateName??lg,generateUid:r.generateUid??cg,resolveModel:r.resolveModel??dg};async function a(e){let t=Xh(e,i.resolveModel);if(`error`in t)return t.error;let n=qh(i.orchestrator,e.parentJid),r=t.resolvedModelId??n?.modelId??``,a=t.resolvedModelId===void 0?n?.providerId:t.resolvedProviderId,o=e.thinkingLevel??Yh(i.orchestrator,e.parentJid)??void 0,s=e.name===void 0?Kh(i):e.name,c=`agent-${s}`,l=`agent_${ug(s)}`;if(e.name!==void 0&&i.orchestrator.getScoops().some(e=>e.jid===l))return{finalText:`agent: name already in use: ${s}`,exitCode:1};let u=`/scoops/${c}`,d=e.parentJid??uh(i.orchestrator.getScoops())[0]?.jid??null,f=tg(e,r,a,o,u,Jh(i.orchestrator,d)),p={jid:l,name:c,folder:c,requiresTrigger:!1,assistantLabel:c,addedAt:new Date().toISOString(),config:f,configSchemaVersion:3,notifyOnComplete:e.notifyOnComplete===!0,parentJid:d},m=ng(i.orchestrator,l),h=()=>{try{i.orchestrator.stopScoop(l)}catch(e){Wh.warn(`stopScoop on abort failed`,{jid:l,error:gg(e)})}};if(e.signal?.addEventListener(`abort`,h,{once:!0}),e.signal?.aborted)return e.signal.removeEventListener(`abort`,h),m.unsubscribe?.(),{finalText:`agent: aborted before start`,exitCode:1};let g={finalText:``,exitCode:1};try{return g=await ag(i,e,p,l,m),g}finally{e.signal?.removeEventListener(`abort`,h),m.unsubscribe?.(),await eg(i,e,l,s,g),await ig(i,l,c,u)}}return{spawn:a}}function sg(e,t,n=null,r={}){let i=og(e,t,n,r);return globalThis[Gh]=i,Wh.info(`agent bridge published on globalThis.__slicc_agent`),i}function cg(){let e=globalThis;return typeof e.crypto?.randomUUID==`function`?e.crypto.randomUUID().replace(/-/g,``).slice(0,12):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`}function lg(){return`${Ih[Math.floor(Math.random()*Ih.length)]}-${Lh[Math.floor(Math.random()*Lh.length)]}`}function ug(e){return e.replace(/-/g,`_`)}function dg(e){try{return L(e)}catch(t){return Wh.warn(`defaultResolveModel: provider/account lookup threw; treating model as unknown`,{modelId:e,error:t instanceof Error?t.message:String(t)}),{ok:!1,error:`unknown model: ${e}`}}}function fg(e){let t=Pt(e);return t.endsWith(`/`)?t:`${t}/`}function pg(e,t){let n=[t,`/shared/`];return e===void 0||e.some(e=>typeof e!=`string`||!e.startsWith(`/`)||e.includes(`\0`))?n:e.map(fg)}function mg(e,t){if(e.visiblePaths!==void 0)return e.visiblePaths.map(fg);let n=[...t];return e.invokingCwd&&e.invokingCwd.length>0&&n.push(fg(e.invokingCwd)),hg(n)}function hg(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function gg(e){return e instanceof Error?e.message:String(e)}function _g(e,t){if(typeof e!=`object`||!e)return!1;let n=e.code;return typeof n==`string`&&n===t}const vg=`sessions`;function yg(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(vg)||e.createObjectStore(vg,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var bg=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await yg();e.onversionchange=()=>{e.close(),this.db=null},e.onclose=()=>{this.db=null},this.db=e}return this.db}async save(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readwrite`);i.objectStore(vg).put(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async load(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readonly`).objectStore(vg).get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async list(){let e=await this.getDb();return new Promise((t,n)=>{let r=e.transaction(vg,`readonly`).objectStore(vg).getAll();r.onsuccess=()=>{t(r.result.sort((e,t)=>t.updatedAt-e.updatedAt).map(e=>e.id))},r.onerror=()=>n(r.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(vg,`readwrite`);i.objectStore(vg).delete(e),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async saveMessages(e,t){let n=await this.load(e),r=n?{...n,messages:t,updatedAt:Date.now()}:{id:e,messages:t,createdAt:Date.now(),updatedAt:Date.now()};await this.save(r)}};async function xg(e,t,n){let r=await n({method:`GET`,path:`/${e}/sites/${t}/config.json`,origin:rn});if(r.status===401||r.status===403)throw Error(`not authorized to read the site config for ${e}/${t} — log in via Settings → Providers → Adobe, or pass --backend to skip the probe`);if(r.status===404)throw Error(`no site config for ${e}/${t} — check the org and site names`);if(r.status>=400)throw Error(`site config probe failed for ${e}/${t}: ${r.status}`);let i;try{i=await r.json()}catch(n){throw Error(`site config for ${e}/${t} is not JSON: ${n instanceof Error?n.message:String(n)}`)}let a=i.content?.source?.url;return{backend:Sg(a),sourceUrl:a}}function Sg(e){if(!e)return`da`;let t;try{t=new URL(e).host}catch{return`da`}return t===`api.aem.live`?`aem`:`da`}const Cg=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`bash`,`sudo-request`,`preview`,`discovery`]);function wg(e){return e!=null&&Cg.has(e)}const Tg={webhook:`Webhook Event`,sprinkle:`Sprinkle Event`,fswatch:`File Watch Event`,"session-reload":`Session Reload`,navigate:`Navigate Event`,upgrade:`Upgrade Event`,cherry:`Cherry Event`,workflow:`Workflow Event`,bash:`Background Command`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function Eg(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`session-reload`:return`mount-recovery`;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`cherry`:return e.cherryName;case`workflow`:return e.workflowName;case`bash`:return e.bashJobId;case`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Dg(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=hee(n.mounts??[]);return e===null?null:{label:t,content:`${e}${r?`\n\nLick ID: ${r}\nThis card is actionable: call \`lick_confirm\` with this lick id to re-run the listed \`mount …\` command(s) so the user can re-authorize, or \`lick_dismiss\` to leave them unmounted. The card flips to ✓ on confirm / muted ✗ on dismiss.`:``}`}}let i=Fg(e,t);if(!r)return i;let a=`\n\nLick ID: ${r}\nThis card is informational — there is NO confirm action. Call \`lick_dismiss\` with this lick id to acknowledge and clear it. The card flips to muted ✗ on dismiss.`;return{label:i.label,content:`${i.content}${a}`}}function Og(e,t){let n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`,i=e.body?.releasedAt??null,a=i?`\nReleased: ${i}`:``,o=e.lickId;return{label:t,content:`[${t}: ${n}→${r}]\n\nSLICC was upgraded from \`${n}\` to \`${r}\`.${a}${o?`\n\nLick ID: ${o}\nUse the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`). The card is a binary action: call \`lick_confirm\` with this lick id to **Update workspace files** (it runs the three-way merge of bundled vfs-root content into the user's VFS), or \`lick_dismiss\` to clear it. The card flips to ✓ on confirm / muted ✗ on dismiss. Reviewing the changelog is a separate step you can run first — it is NOT a card action.`:`
|
|
888
888
|
|
|
889
889
|
Use the **upgrade** skill (\`/workspace/skills/upgrade/SKILL.md\`) to offer the user a three-way merge of bundled vfs-root content into their workspace (bundled snapshot vs user's VFS, reconciled with the GitHub tag-to-tag diff).`}`}}function kg(e,t){let n=e.cherryOrigin??`unknown origin`,r=e.cherryRuntimeId??`unknown`;return{label:t,content:`[${t}: ${e.cherryName??`unnamed`}] from ${n} (runtime ${r})\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ag(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function jg(e,t){let n=e.workflowName??`workflow`,r=e.resultPath??`(no result file)`,i=e.preview??``;return{label:t,content:`[${t}: ${n}] ${e.body?.status??`complete`} — ${i}\nFull result: ${r} (read it only if you need the whole thing).`}}function Mg(e,t){let n=e.bashJobId??`unknown job`,r=e.bashJobPid===void 0?``:` (pid ${e.bashJobPid})`,i=e.bashCommand??`(unknown command)`,a=e.bashExitCode,o=a===0?`succeeded`:a===130||a===137||a===143?`was terminated (exit code ${a}) — killed by a signal, not by its own failure`:`failed (exit code ${a??`unknown`})`,s=e.resultPath;return{label:t,content:`[${t}: ${n}${r}] \`${i}\` ${o}.\n${s?`Full output: ${s} (page it with \`sed -n\`/\`tail\`/\`grep\` if the preview below is cut).`:`Its output could NOT be written to a file — the preview below is all that survived.`}${e.preview?.length?`\n\n\`\`\`\n${e.preview}\n\`\`\``:``}\n\nThis is the delayed result of a command that was detached earlier in this session — do not re-run it. Act on it if it still matters, otherwise acknowledge and move on.`}}function Ng(e,t){let n=e.sudoScoopName??`a scoop`,r=e.lickId??`(unknown)`,i=e.sudoKind??`unknown`,a=e.sudoDetail??``,o=[`[${t}: ${n}]`,`Lick ID: ${r}`,`Kind: ${i}`,`Detail: ${a}`];return e.sudoSuggestedPattern&&o.push(`Suggested pattern: ${e.sudoSuggestedPattern}`),o.push(``,`Use the lick_confirm tool with lick_id="${r}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${r}" to deny.`),{label:t,content:o.join(`
|
|
890
890
|
`)}}function Pg(e,t){let n=e.discoveryOrigin??`an origin`,r=e.discoveryUrl??`(unknown URL)`,i=e.discoveryKind===`llms-txt`?`an llms.txt digest`:`an ai-catalog manifest`,a=e.discoveryKind??`unknown`;return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${r}]\n${n} advertises ${i} (kind: ${a}) at ${r}.${e.discoveryKind===`llms-txt`&&e.lickId?`\n\nLick ID: ${e.lickId}\nThis card is dismiss-only: call \`lick_dismiss\` to add the advertising host to \`/etc/llmstxtignore\` and silence future discoveries without a prompt. There is NO confirm action.`:`
|
|
891
|
-
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Fg(e,t){let n=Eg(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ig(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Fg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Lg(e,t){let n=Fg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Rg(e){let t=Tg[e.type];return e.type===`session-reload`?Dg(e,t):e.type===`upgrade`?Og(e,t):e.type===`cherry`?kg(e,t):e.type===`preview`?Ag(e,t):e.type===`workflow`?jg(e,t):e.type===`bash`?Mg(e,t):e.type===`sudo-request`?Ng(e,t):e.type===`navigate`?Lg(e,t):e.type===`webhook`?Ig(e,t):e.type===`discovery`?Pg(e,t):Fg(e,t)}const zg=new Map;function Bg(e){let t=zg.get(e.id);t&&(zg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Vg=`slicc-sprinkle-routes`;function Hg(){try{let e=localStorage.getItem(Vg);return e?JSON.parse(e):{}}catch{return{}}}function Ug(e){try{localStorage.setItem(Vg,JSON.stringify(e))}catch{}}function Wg(e){return Hg()[e]}function Gg(e,t){let n=Hg();n[e]=t,Ug(n)}function Kg(e){let t=Hg();delete t[e],Ug(t)}function bre(){return Hg()}function qg(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...e.config?{config:e.config,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{}};return n||(i.trigger=`@${r}`),i}var xre=class{host;constructor(e){this.host=e}async create(e){if(e.parentId!==null&&!this.host.getScoop(e.parentId))throw Error(`Parent work unit not found: ${e.parentId}`);let t=qg(e);return await this.host.registerScoop(t),this.get(t.jid).descriptor}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return ch(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return uh(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async close(e){let t=this.get(e);if(t){for(let t of this.getChildren(e))await this.close(t.descriptor.id);await t.close()}}};const Sre=r(`kernel-agent-event-stream`);var Cre=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Sre.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${wre()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function wre(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Tre=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Ere(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:rh(e),parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=uh(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Ere(e){let t=xh(e),n=Sh(e),{level:r,effortOverride:i}=Ch(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}let Dre={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Jg(){return{...Dre}}function Ore(){let e=Jg();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(pn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Yg=new Set;function kre(e){return Yg.add(e),()=>{Yg.delete(e)}}function Xg(){return Are(_ee(),Jg())}function Are(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Zg=`__slicc_binary__`;function jre(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Zg]===`b64`&&typeof t.data==`string`}function Qg(e){if(e instanceof Uint8Array)return{[Zg]:`b64`,data:d(e)};if(Array.isArray(e))return e.map(Qg);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Qg(r);return t}return e}function $g(e){if(jre(e))return l(e.data);if(Array.isArray(e))return e.map($g);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=$g(r);return t}return e}const Mre=r(`panel-transport`);function Nre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Pre(){return{onMessage:e=>{let t=(t,n,r)=>(Nre(t)&&e($g(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Qg(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Mre.error(`Offscreen → panel transport send failed`,{error:t})})}}}const e_=r(`kernel-bridge`);function t_(){return globalThis}function Fre(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var n_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Tre;agentEventStream=new Cre;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Pre(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new bg;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${r_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{qt.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{qt.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=Jt(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??r_(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Kt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Gt(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(mh(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Xg())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Xg()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Fre(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Wg(e),s=o?Ca(a,o):void 0;if(s||=uh(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Rg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,u={id:c,chatJid:s.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:l,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(s.jid).push({id:c,role:`user`,content:l,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(s.jid),await this.orchestrator.handleMessage(u)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=uh(this.orchestrator.getScoops())[0];if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=mh(t);this.sessionStore.saveMessages(n,e).catch(e=>{e_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?uh(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:yh(e)}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=mh(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t});return}}catch(e){e_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[]})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=_h(e,i),o=a===ph,s=uh(i)[0],c=r??(s?bh(s):void 0),l=t?.trim(),u={...qg({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}};await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let d=n?.trim();d&&await this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:d,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`})}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=this.orchestrator?.getSudoManager()??null;if(!r)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await r.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:i_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:yh(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:i_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=mh(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=mh(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){e_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${r_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?yh(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Bg(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear())}}async handleAgentSpawn(e){let t=t_()[Gh];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&rh(n)){if(uh(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);for(let e of[...r,n])this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=mh({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t){let n=this.orchestrator?.getScoops()??[],r=(t?n.find(e=>e.jid===t):void 0)??uh(n)[0],i=r?.jid;i&&await this.orchestrator?.clearScoopMessages(i),this.sessionStore&&await this.sessionStore.delete(mh({folder:r?.folder??`cone`})),i&&(this.messageBuffers.delete(i),this.currentMessageId.delete(i),this.agentEventStream.clear(i)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=t_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=t_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Ut.markMounted(t);return}try{await Ut.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Ut.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function r_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function i_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
892
|
-
`)}const Ire=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Lre(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Ire.map(e=>Rre(i,e,t,r)))).filter(e=>e!==null)}async function Rre(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!zre(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function zre(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}const a_=r(`navigation-watcher`);function Bre(e,t){return
|
|
891
|
+
This is informational — there is no card action.`}\nYou MAY fetch it (e.g. \`curl ${r}\`) when relevant.`}}function Fg(e,t){let n=Eg(e);return{label:t,content:`${e.originLabel?`_Forwarded from ${e.originLabel}._\n\n`:``}[${t}: ${n}]\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Ig(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Fg(e,t);let i=n[`x-slicc-preview-token`]??``;return{label:`Preview Event`,content:`[Preview event: ${e.body?.name??`event`}] from tab${i?` (preview:${i}:${r})`:` (conn ${r})`}\n\`\`\`json\n${JSON.stringify(e.body,null,2)}\n\`\`\``}}function Lg(e,t){let n=Fg(e,t),r=e.lickId;if(!r)return n;let i=e.body?.verb===`upskill`?`\n\nLick ID: ${r}\nUpskill install. To install, call \`lick_confirm\` with this lick id (it runs \`upskill\` with any branch/path scope from the body); to skip, call \`lick_dismiss\`. The card flips to ✓ on confirm / muted ✗ on dismiss.`:`\n\nLick ID: ${r}\nExternal handoff — stays human-gated. Show the approval dip and wait for the user; do NOT use \`lick_confirm\` / \`lick_dismiss\` here. Carry the lick id in the dip action so the card resolves: slicc.lick({action:'accept'|'dismiss', data:{lickId:'${r}'}}).`;return{label:n.label,content:`${n.content}${i}`}}function Rg(e){let t=Tg[e.type];return e.type===`session-reload`?Dg(e,t):e.type===`upgrade`?Og(e,t):e.type===`cherry`?kg(e,t):e.type===`preview`?Ag(e,t):e.type===`workflow`?jg(e,t):e.type===`bash`?Mg(e,t):e.type===`sudo-request`?Ng(e,t):e.type===`navigate`?Lg(e,t):e.type===`webhook`?Ig(e,t):e.type===`discovery`?Pg(e,t):Fg(e,t)}const zg=new Map;function Bg(e){let t=zg.get(e.id);t&&(zg.delete(e.id),clearTimeout(t.timer),e.error?t.reject(Error(e.error)):t.resolve(e.result))}const Vg=`slicc-sprinkle-routes`;function Hg(){try{let e=localStorage.getItem(Vg);return e?JSON.parse(e):{}}catch{return{}}}function Ug(e){try{localStorage.setItem(Vg,JSON.stringify(e))}catch{}}function Wg(e){return Hg()[e]}function Gg(e,t){let n=Hg();n[e]=t,Ug(n)}function Kg(e){let t=Hg();delete t[e],Ug(t)}function bre(){return Hg()}function qg(e,t=Date.now){let n=e.parentId===null,r=e.folder??e.name,i={jid:e.id??(n?`cone_${t()}`:`scoop_${r}_${t()}`),name:e.name,folder:r,requiresTrigger:!n,assistantLabel:n?`sliccy`:r,addedAt:new Date(t()).toISOString(),parentJid:e.parentId,...e.config?{config:e.config,configSchemaVersion:3}:{},...e.notifyOnComplete===!1?{notifyOnComplete:!1}:{}};return n||(i.trigger=`@${r}`),i}var xre=class{host;constructor(e){this.host=e}async create(e){if(e.parentId!==null&&!this.host.getScoop(e.parentId))throw Error(`Parent work unit not found: ${e.parentId}`);let t=qg(e);return await this.host.registerScoop(t),this.get(t.jid).descriptor}list(){return this.host.getScoops().map(e=>this.get(e.jid).descriptor)}get(e){return this.host.getScoop(e)?this.host.ensureLiveUnit(e):null}getParent(e){let t=this.host.getScoop(e)?.parentJid;return t?this.get(t):null}getChildren(e){return ch(this.host.getScoops(),e).map(e=>this.get(e.jid)).filter(e=>e!==null)}roots(){return uh(this.host.getScoops()).map(e=>this.get(e.jid)).filter(e=>e!==null)}resolveDefaultRoot(){return this.roots()[0]??null}rootOf(e){let t=new Set,n=this.host.getScoop(e);for(;n&&n.parentJid!==null;){if(t.has(n.jid))return null;t.add(n.jid),n=this.host.getScoop(n.parentJid)}return n?this.get(n.jid):null}abort(e,t){let n=this.get(e);return n?n.abort(t):Promise.resolve()}async close(e){let t=this.get(e);if(t){for(let t of this.getChildren(e))await this.close(t.descriptor.id);await t.close()}}};const Sre=r(`kernel-agent-event-stream`);var Cre=class{listeners=new Set;messageIds=new Map;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(e){this.messageIds.delete(e)}publish(e){let t=this.translate(e);for(let n of t)for(let t of this.listeners)try{t(e.scoopJid,n)}catch(e){Sre.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}translate(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.messageIds.get(t);return e||(e=`scoop-${t}-${wre()}`,this.messageIds.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput,toolCallId:e.toolCallId});break}case`tool_end`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError,toolCallId:e.toolCallId});break}case`tool_ui`:{let t=e.displayScoopJid?`tool-ui-${e.requestId??``}`:i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=e.displayScoopJid?`tool-ui-${e.requestId??``}`:this.messageIds.get(t);if(!n)return r;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`tool_progress`:{let n=this.messageIds.get(t);if(!n||!e.progress)return r;r.push({type:`tool_progress`,messageId:n,toolName:e.toolName??``,progress:e.progress,toolCallId:e.toolCallId});break}case`response_done`:{let n=this.messageIds.get(t);if(!n)return r;r.push({type:`content_done`,messageId:n,model:e.model,usage:e.usage}),this.messageIds.delete(t);break}case`turn_end`:this.messageIds.delete(t)}return r}};function wre(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}var Tre=class{statuses=new Map;activeScoopJid=null;setStatus(e,t){this.statuses.set(e,t)}clearStatus(e){this.statuses.delete(e)}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}projectScoop(e){let t=Ere(e);return{jid:e.jid,name:e.name,folder:e.folder,isCone:rh(e),parentId:e.parentJid,assistantLabel:e.assistantLabel,status:this.statuses.get(e.jid)??`ready`,...t?{config:t}:{}}}projectScoops(e){return e.map(e=>this.projectScoop(e))}buildStateSnapshot(e,t){let n=this.projectScoops(e),r=uh(e)[0];return{type:`state-snapshot`,scoops:n,activeScoopJid:this.activeScoopJid??r?.jid??null,trayRuntimeStatus:t}}};function Ere(e){let t=xh(e),n=Sh(e),{level:r,effortOverride:i}=Ch(e);if(t!==void 0||n!==void 0||r!==void 0||i!==void 0)return{...t===void 0?{}:{modelId:t},...n===void 0?{}:{modelProviderId:n},...r===void 0?{}:{thinkingLevel:r},...i===void 0?{}:{effortOverride:i}}}let Dre={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Jg(){return{...Dre}}function Ore(){let e=Jg();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(mn);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Yg=new Set;function kre(e){return Yg.add(e),()=>{Yg.delete(e)}}function Xg(){return Are(gee(),Jg())}function Are(e,t){return{leader:{state:e.state,session:e.session?{workerBaseUrl:e.session.workerBaseUrl,trayId:e.session.trayId,createdAt:e.session.createdAt,controllerId:e.session.controllerId,controllerUrl:e.session.controllerUrl,joinUrl:e.session.joinUrl,webhookUrl:e.session.webhookUrl,...e.session.leaderKey===void 0?{}:{leaderKey:e.session.leaderKey},...e.session.leaderWebSocketUrl===void 0?{}:{leaderWebSocketUrl:e.session.leaderWebSocketUrl},runtime:e.session.runtime}:null,error:e.error??null,reconnectAttempts:e.reconnectAttempts??0},follower:{state:t.state,joinUrl:t.joinUrl,trayId:t.trayId,error:t.error,lastError:t.lastError,reconnectAttempts:t.reconnectAttempts,attachAttempts:t.attachAttempts,lastAttachCode:t.lastAttachCode,connectingSince:t.connectingSince,lastPingTime:t.lastPingTime}}}const Zg=`__slicc_binary__`;function jre(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Zg]===`b64`&&typeof t.data==`string`}function Qg(e){if(e instanceof Uint8Array)return{[Zg]:`b64`,data:d(e)};if(Array.isArray(e))return e.map(Qg);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Qg(r);return t}return e}function $g(e){if(jre(e))return l(e.data);if(Array.isArray(e))return e.map($g);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=$g(r);return t}return e}const Mre=r(`panel-transport`);function Nre(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Pre(){return{onMessage:e=>{let t=(t,n,r)=>(Nre(t)&&e($g(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Qg(e);chrome.runtime.sendMessage({source:`offscreen`,payload:n}).catch(e=>{let t=e instanceof Error?e.message:String(e);/receiving end does not exist/i.test(t)||Mre.error(`Offscreen → panel transport send failed`,{error:t})})}}}const e_=r(`kernel-bridge`);function t_(){return globalThis}function Fre(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.action!==`accept`&&t.action!==`dismiss`)return null;let n=t.data,r=n&&typeof n.lickId==`string`?n.lickId:null;return r?{lickId:r,accepted:t.action===`accept`}:null}var n_=class{orchestrator=null;agentSpawnAborts=new Map;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopPresentation=new Tre;agentEventStream=new Cre;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;constructor(e){this._transport=e??null}get transport(){return this._transport||=Pre(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new bg;await n.init(),this.sessionStore=n}static createCallbacks(e){return{onResponse:(t,n,r)=>{let i=e.getOrCreateAssistantMsg(t);r?i.content+=n:(i.content=n,i.isStreaming=!1),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n})},onResponseDone:t=>{let n=e.getLatestAssistantMetadata(t),r=e.currentMessageId.get(t);if(r){let i=e.getBuffer(t).find(e=>e.id===r);i&&(i.isStreaming=!1,n&&Object.assign(i,n)),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,...n??{}})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${r_()}`;r.push({id:i,role:`assistant`,content:n,timestamp:Date.now()}),e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:n}),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onStatusChange:(t,n)=>{e.scoopPresentation.setStatus(t,n),n===`ready`&&e.currentMessageId.delete(t),e.emit({type:`scoop-status`,scoopJid:t,status:n}),e.emitScoopList()},onCompactionStateChange:(t,n)=>{e.emit({type:`compaction-state`,scoopJid:t,state:n})},onError:(t,n)=>{e.emit({type:`error`,scoopJid:t,error:n})},onLickBackpressure:(t,n)=>{e.emit({type:`lick-backpressure`,scoopJid:t,...n})},onToolStart:(t,n,r,i)=>{qt.has(n)||e.bufferToolStart(t,n,r,i)},onToolEnd:(t,n,r,i,a)=>{qt.has(n)||e.bufferToolEnd(t,n,r,i,a)},onToolUI:(t,n,r,i,a)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i,...a?{displayScoopJid:a}:{}})},onToolUIDone:(t,n,r)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n,...r?{displayScoopJid:r}:{}})},onToolProgress:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_progress`,toolName:n,progress:r,toolCallId:i})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n,r){let i=Jt(n),a=this.getOrCreateAssistantMsg(e);a.toolCalls||=[],a.toolCalls.push({id:r??r_(),name:t,input:i}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:i,toolCallId:r})}bufferToolEnd(e,t,n,r,i){let a=this.currentMessageId.get(e);if(a){let o=this.getBuffer(e).find(e=>e.id===a);if(o?.toolCalls){let e=i?o.toolCalls.find(e=>e.id===i):[...o.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=Kt(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:Gt(n),isError:r,toolCallId:i})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.parentJid!==null&&this.sessionStore&&this.sessionStore.delete(mh(e)).catch(t=>{console.warn(`[kernel-bridge] Failed to delete session for unregistered scoop:`,e.folder,t)}),this.emitScoopList()}notifyPanelIncomingMessage(e,t){this.emit({type:`incoming-message`,scoopJid:e,message:{id:t.id,content:t.content,attachments:t.attachments,channel:t.channel,senderName:t.senderName,fromAssistant:t.fromAssistant,timestamp:t.timestamp,lickId:t.lickId,lickState:t.lickState}})}applyMessageUpdate(e,t){let n=this.messageBuffers.get(e)?.find(e=>t.lickId&&e.lickId===t.lickId||e.id===t.messageId);n&&(n.lickState=t.lickState,this.persistScoop(e)),this.emit({type:`message-updated`,scoopJid:e,messageId:t.messageId,lickId:t.lickId,lickState:t.lickState})}toScoopSnapshot(e){return this.scoopPresentation.projectScoop(e)}buildStateSnapshot(){return this.scoopPresentation.buildStateSnapshot(this.orchestrator?.getScoops()??[],Xg())}emitTrayRuntimeStatus(){let e={type:`tray-runtime-status`,...Xg()};this.emit(e)}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.scoopPresentation.setActiveScoopJid(e)}getActiveScoopJid(){return this.scoopPresentation.getActiveScoopJid()}onAgentEvent(e){return this.agentEventStream.subscribe(e)}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=Fre(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n??Wg(e),s=o?Ca(a,o):void 0;if(s||=uh(a)[0],!s)return;let c=`sprinkle-${e}-${Date.now()}`,l=Rg({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,u={id:c,chatJid:s.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:l,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(s.jid).push({id:c,role:`user`,content:l,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(s.jid),await this.orchestrator.handleMessage(u)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=uh(this.orchestrator.getScoops())[0];if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming,model:e.model,usage:e.usage}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.agentEventStream.clear(t.jid),this.sessionStore){let n=mh(t);this.sessionStore.saveMessages(n,e).catch(e=>{e_.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?uh(this.orchestrator.getScoops())[0]?.jid??null:null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`,model:e.model,usage:e.usage});break;case`tool_use_start`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_start`,toolName:e.toolName,toolInput:e.toolInput});break;case`tool_result`:this.emit({type:`agent-event`,scoopJid:t,eventType:`tool_end`,toolName:e.toolName,toolResult:e.result,isError:e.isError});break;case`turn_end`:this.emit({type:`agent-event`,scoopJid:t,eventType:`turn_end`});break;case`error`:this.emit({type:`error`,scoopJid:t,error:e.error})}}emitFollowerIncomingMessage(e,t){let n=this.getConeJid();n&&this.emit({type:`incoming-message`,scoopJid:n,message:{id:e,content:t,channel:`web`,senderName:`User`,fromAssistant:!1,timestamp:new Date().toISOString()}})}emitFollowerStatus(e){let t=this.getConeJid();if(!t)return;let n=e===`processing`?`processing`:`ready`;this.scoopPresentation.setStatus(t,n),this.emit({type:`scoop-status`,scoopJid:t,status:n})}async buildBufferFromAgentMessages(e){let t=this.orchestrator?.getScoopContext(e.jid);if(!t)return null;let n=t.getAgentMessages();if(n.length===0)return null;let{agentMessagesToChatMessages:r}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n);return r(n,{source:yh(e)}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),model:e.model,usage:e.usage,isStreaming:!1}))}async seedBuffersFromAgentState(){if(this.orchestrator)for(let e of this.orchestrator.getScoops()){let t=this.messageBuffers.get(e.jid);if(t&&t.length>0)continue;let n=await this.buildBufferFromAgentMessages(e);n&&(this.messageBuffers.set(e.jid,n),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),await this.persistScoopAwait(e.jid))}}async handleRequestScoopMessages(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=this.messageBuffers.get(e);if(n&&n.length>0){this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:n});return}let r=await this.buildBufferFromAgentMessages(t);if(r){this.messageBuffers.set(e,r),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=mh(t);try{let t=(await this.sessionStore.load(n))?.messages??[];if(t.length>0){this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.agentEventStream.clear(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t});return}}catch(e){e_.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:[]})}async handleConeCreate(e,t,n,r){if(!this.orchestrator)return;let i=this.orchestrator.getScoops(),a=_h(e,i),o=a===ph,s=uh(i)[0],c=r??(s?bh(s):void 0),l=t?.trim(),u={...qg({parentId:null,name:e,folder:a}),assistantLabel:o?`sliccy`:e,...l?{config:{systemPromptAppend:`This cone is for: ${l}`}}:{},...c?{model:c}:{}};await this.orchestrator.registerScoop(u),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(u)});let d=n?.trim();d&&await this.handleUserMessage({type:`user-message`,scoopJid:u.jid,text:d,messageId:`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`})}async handleRequestSudoApproval(e,t){let n={decision:`deny`},r=this.orchestrator?.getSudoManager()??null;if(!r)console.warn(`[kernel-bridge] request-sudo-approval before SudoManager init — denying`);else try{n=await r.approve(t)}catch(e){console.warn(`[kernel-bridge] sudo approval threw — denying`,e)}this.emit({type:`sudo-approval`,requestId:e,decision:n})}handleRequestSessionStats(e){let t=0,n=0,r=[],i=[],a=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=(this.orchestrator?.getSessionCosts({includeDropped:!0})??[]).reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getBurnRate()??0,r=this.orchestrator?.getContextFills()??[],i=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),a=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type,source:e.source}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,burnRate:n,fills:r,models:i,scoops:a})}async handleRequestScoopTranscript(e,t){let n=()=>{this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:``})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:i_(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-ChAiEgvC.js`).then(e=>e.n),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:yh(r)});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:i_(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=mh(r);try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=mh(t),r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){e_.error(`persistScoop failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}getBuffer(e){let t=this.messageBuffers.get(e);return t||(t=[],this.messageBuffers.set(e,t)),t}getOrCreateAssistantMsg(e){let t=this.getBuffer(e),n=this.currentMessageId.get(e);if(n){let e=t.find(e=>e.id===n);if(e)return e}n=`scoop-${e}-${r_()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?yh(r):`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}getLatestAssistantMetadata(e){let t=this.orchestrator?.getScoopContext?.(e)?.getAgentMessages()??[];for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role!==`assistant`)continue;let r={model:n.model},{usage:i}=n;return i&&(r.usage={input:i.input,output:i.output,cacheRead:i.cacheRead,cacheWrite:i.cacheWrite,cost:{input:i.cost.input,output:i.cost.output,cacheRead:i.cost.cacheRead,cacheWrite:i.cost.cacheWrite,total:i.cost.total}}),r}return null}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){Bg(e.payload);return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[kernel-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name,e.description,e.prompt,e.model);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[kernel-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`request-sudo-approval`:this.handleRequestSudoApproval(e.requestId,e.request);break;case`clear-chat`:await this.handleClearChat(e.requestId,e.scoopJid);break;case`agent-spawn-request`:await this.handleAgentSpawn(e);break;case`agent-spawn-abort`:this.agentSpawnAborts.get(e.requestId)?.abort();break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[kernel-bridge] clear-filesystem failed:`,e));break;case`set-model`:case`refresh-model`:this.orchestrator.refreshModels();break;case`set-scoop-model`:await this.handleSetScoopModel(e);break;case`set-thinking-level`:await this.handleSetThinkingLevel(e);break;case`sprinkle-lick`:await this.handleSprinkleLickMsg(e);break;case`lick-webhook-event`:this.orchestrator.handleWebhookEvent(e.webhookId,e.headers,e.body);break;case`set-follower-forwarding`:this.handleSetFollowerForwarding(e.enabled);break;case`inject-forwarded-lick`:this.handleInjectForwardedLick(e.event);break;case`lick-cherry-host-event`:this.orchestrator.handleCherryHostEvent(e.cherryRuntimeId,e.name,e.detail);break;case`lick-preview`:this.orchestrator.handlePreviewLick(e.event);break;case`reload-skills`:this.orchestrator.reloadAllSkills().catch(e=>{console.warn(`[kernel-bridge] Skill reload failed:`,e)});break;case`panel-cdp-command`:await this.handlePanelCdpCommand(e);break;case`tool-ui-action`:await this.handleToolUIAction(e);break;case`local-storage-set`:this.applyLocalStorageOp(e.type,t=>t.setItem(e.key,e.value));break;case`local-storage-remove`:this.applyLocalStorageOp(e.type,t=>t.removeItem(e.key));break;case`local-storage-clear`:this.applyLocalStorageOp(e.type,e=>e.clear())}}async handleAgentSpawn(e){let t=t_()[Gh];if(!t||typeof t.spawn!=`function`){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:`AgentBridge unavailable`});return}let n=new AbortController;this.agentSpawnAborts.set(e.requestId,n);try{let r=await t.spawn({...e.options,signal:n.signal});this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!0,result:r})}catch(t){this.emit({type:`agent-spawn-result`,requestId:e.requestId,ok:!1,error:t instanceof Error?t.message:String(t)})}finally{this.agentSpawnAborts.delete(e.requestId)}}async handleSetScoopModel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopModel(e.scoopJid,e.model)}catch(e){console.error(`[kernel-bridge] set-scoop-model failed:`,e)}e.requestId&&this.emit({type:`set-scoop-model-ack`,requestId:e.requestId,scoopJid:e.scoopJid,model:e.model,applied:t})}async handleSetThinkingLevel(e){if(!this.orchestrator)return;let t=!1;try{t=await this.orchestrator.setScoopThinkingLevel(e.scoopJid,e.level,e.effortOverride)!==null}catch(e){console.error(`[kernel-bridge] set-thinking-level failed:`,e)}e.requestId&&this.emit({type:`set-thinking-level-ack`,requestId:e.requestId,scoopJid:e.scoopJid,level:e.level,effortOverride:e.effortOverride,applied:t})}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete queued message:`,e)});let n=this.messageBuffers.get(e);if(!n)return;let r=n.filter(e=>e.id!==t);r.length!==n.length&&(this.messageBuffers.set(e,r),this.persistScoop(e))}async handleUserMessage(e){if(this.getBuffer(e.scoopJid).push({id:e.messageId,role:`user`,content:e.text,attachments:e.attachments,timestamp:Date.now()}),this.persistScoop(e.scoopJid),this.followerSync){e.steer?this.followerSync.sendMessage(e.text,e.messageId,e.attachments,{steer:!0}):this.followerSync.sendMessage(e.text,e.messageId,e.attachments);return}let t={id:e.messageId,chatJid:e.scoopJid,senderId:`user`,senderName:`User`,content:e.text,attachments:e.attachments,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`web`,...e.steer?{steer:!0}:{}};await this.orchestrator?.handleMessage(t),await this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops(),n=t.find(t=>t.jid===e);if(n&&rh(n)){if(uh(t).length<=1){console.warn(`[kernel-bridge] Refusing to drop the last cone:`,e),this.emitScoopList();return}let r=this.descendantsOf(t,e);await this.orchestrator.getWorkUnits().close(e);for(let e of[...r,n])this.forgetDroppedScoop(e)}else await this.orchestrator.unregisterScoop(e),this.forgetDroppedScoop(n??{jid:e});this.emitScoopList()}descendantsOf(e,t){let n=[];for(let r of e)r.parentJid===t&&n.push(...this.descendantsOf(e,r.jid),r);return n}forgetDroppedScoop(e){if(this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.agentEventStream.clear(e.jid),this.scoopPresentation.clearStatus(e.jid),e.folder&&this.sessionStore){let t=mh({folder:e.folder});this.sessionStore.delete(t).catch(e=>{console.warn(`[kernel-bridge] Failed to delete session on scoop drop:`,t,e)})}}async handleClearChat(e,t){let n=this.orchestrator?.getScoops()??[],r=(t?n.find(e=>e.jid===t):void 0)??uh(n)[0],i=r?.jid;i&&await this.orchestrator?.clearScoopMessages(i),this.sessionStore&&await this.sessionStore.delete(mh({folder:r?.folder??`cone`})),i&&(this.messageBuffers.delete(i),this.currentMessageId.delete(i),this.agentEventStream.clear(i)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[kernel-bridge] sprinkle-lick dropped: follower sync mid-reconnect`,{sprinkleName:e.sprinkleName});return}await this.routeSprinkleLick(e.sprinkleName,e.body,e.targetScoop,e.originLabel)}handleSetFollowerForwarding(e){let t=t_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] set-follower-forwarding ignored: worker LickManager unavailable`);return}e?t.setForwarder(e=>this.emit({type:`forward-lick`,event:e})):t.setForwarder(null)}handleInjectForwardedLick(e){let t=t_().__slicc_lickManager;if(!t){console.warn(`[kernel-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.handleForwardedEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[kernel-bridge] Panel CDP command received but BrowserAPI is null`),this.emit({type:`panel-cdp-response`,id:t,error:`BrowserAPI not available`});return}try{let e=await this.browserAPI.getTransport().send(n,r,i);this.emit({type:`panel-cdp-response`,id:t,result:e})}catch(e){this.emit({type:`panel-cdp-response`,id:t,error:e instanceof Error?e.message:String(e)})}}async handleToolUIAction(e){let{requestId:t,action:n,data:r}=e;if(n===`__mounted`){Ut.markMounted(t);return}try{await Ut.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[kernel-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),Ut.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[kernel-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.scoopPresentation.projectScoops(this.orchestrator?.getScoops()??[]);this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.agentEventStream.publish(e)}};function r_(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function i_(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
892
|
+
`)}const Ire=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}];async function Lre(e,t,n={}){let r=n.timeoutMs??3e3,i;try{i=new URL(e).origin}catch{return[]}return(await Promise.all(Ire.map(e=>Rre(i,e,t,r)))).filter(e=>e!==null)}async function Rre(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!zre(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function zre(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}const a_=r(`navigation-watcher`);function Bre(e,t){return bee(e,t)}var Vre=class{transport;onEvent;sessions=new Map;started=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;probedOrigins=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;t&&this.sessions.delete(t)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId)for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url))};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameNavigated=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n)return;let r=e.frame;r?.id&&(r.parentId||(n.rootFrameId=r.id,typeof r.url==`string`&&(n.url=r.url)))};onResponseReceived=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n||e.type!==`Document`)return;let r=e.frameId;if(!r||r!==n.rootFrameId)return;let i=e.response;if(!i)return;let a=typeof i.url==`string`&&i.url.length>0?i.url:n.url;if(!a)return;let{match:o,links:s}=Bre(i.headers,a);if(o){let e={url:a,verb:o.verb,target:o.target,links:s,targetId:n.targetId};o.instruction!=null&&(e.instruction=o.instruction),o.branch!=null&&(e.branch=o.branch),o.path!=null&&(e.path=o.path),n.title!=null&&(e.title=n.title),this.onEvent(e)}this.maybeRunDiscovery(a,s,n.targetId)};constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs}maybeRunDiscovery(e,t,n){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let r;try{r=new URL(e).origin}catch{return}let i=See(t);i&&this.onDiscovery({origin:r,kind:i.kind,url:i.url,targetId:n}),this.probeFetch&&!this.probedOrigins.has(r)&&(this.probedOrigins.add(r),this.runWellKnownProbe(r,n))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await Lre(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){a_.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){this.transport.on(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.on(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.on(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.on(`Target.targetCreated`,this.onTargetCreated),this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.transport.on(`Network.responseReceived`,this.onResponseReceived);try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!0})}catch(e){a_.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived);return}this.started=!0;try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;if(!(e||typeof n!=`string`))try{await this.transport.send(`Target.attachToTarget`,{targetId:n,flatten:!0})}catch(e){a_.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){a_.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}}async stop(){if(this.started){this.started=!1,this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived),this.sessions.clear();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){a_.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;if(t?.type===`page`&&typeof t.targetId==`string`&&!t.attached)try{await this.transport.send(`Target.attachToTarget`,{targetId:t.targetId,flatten:!0})}catch(e){a_.debug(`Failed to attach to discovered target`,{targetId:t.targetId,error:e instanceof Error?e.message:String(e)})}}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!(!t||!n||n.type!==`page`||typeof n.targetId!=`string`)){this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,title:n.title,url:n.url});try{await this.transport.send(`Page.enable`,{},t),await this.transport.send(`Network.enable`,{},t);let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){a_.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};function Hre(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var Ure=`# /etc/llmstxtignore — llms.txt discovery suppression
|
|
893
893
|
#
|
|
894
894
|
# One advertising hostname or glob per line. Matching is case-insensitive.
|
|
895
895
|
# \`#\` starts a comment; blank lines are ignored.
|
|
@@ -973,13 +973,13 @@ Write /etc/models
|
|
|
973
973
|
#
|
|
974
974
|
# Let connected followers export the live transcript without a prompt:
|
|
975
975
|
# NOPASSWD Export active
|
|
976
|
-
`;const f_=r(`quick-llm`);async function Yre(e){let t=rt();if(!t)return f_.debug(`No API key for active provider — skipping`),null;let n=E(),r=te(),i;if(i=e.modelId?p_(n,e.modelId)??p_(n,r):Xre(n,r),!i)return f_.debug(`No model available for provider`,{providerId:n}),null;let a={role:`user`,content:e.prompt,timestamp:Date.now()},o={};i.provider===`adobe`&&(o[`X-Session-Id`]=$re());try{let n=(await Lt(i,{systemPrompt:e.system,messages:[a]},{apiKey:t,maxTokens:e.maxTokens??60,temperature:e.temperature??.3,signal:e.signal,headers:Object.keys(o).length>0?o:void 0})).content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim();return n.length>0?n:null}catch(e){return f_.debug(`Quick label call failed`,{error:e instanceof Error?e.message:String(e)}),null}}function Xre(e,t){let n=vt(e);if(n.length===0)return;let r=n.find(e=>e.id===t)??n[0],i=Qre(r.id),a=n.filter(e=>Zre(e,r,i));return a.length===0?r:(a.sort((e,t)=>(e.cost?.input??0)-(t.cost?.input??0)),a[0])}function Zre(e,t,n){if(e.id===t.id)return!1;let r=t.cost?.input??1/0;if((e.cost?.input??1/0)>=r)return!1;let i=e.id.toLowerCase();switch(n){case`claude`:return i.includes(`haiku`);case`gpt`:return/(^|-)mini(-|$)|(^|-)nano(-|$)/.test(i);case`gemini`:return i.includes(`flash`);case`grok`:return/(^|-)mini(-|$)|(^|-)fast(-|$)/.test(i);case`unknown`:return!0}}function Qre(e){let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`gemini`)?`gemini`:t.includes(`grok`)?`grok`:/^(gpt|o\d)/.test(t)?`gpt`:`unknown`}function p_(e,t){return vt(e).find(e=>e.id===t)}function $re(){return
|
|
976
|
+
`;const f_=r(`quick-llm`);async function Yre(e){let t=rt();if(!t)return f_.debug(`No API key for active provider — skipping`),null;let n=E(),r=te(),i;if(i=e.modelId?p_(n,e.modelId)??p_(n,r):Xre(n,r),!i)return f_.debug(`No model available for provider`,{providerId:n}),null;let a={role:`user`,content:e.prompt,timestamp:Date.now()},o={};i.provider===`adobe`&&(o[`X-Session-Id`]=$re());try{let n=(await Lt(i,{systemPrompt:e.system,messages:[a]},{apiKey:t,maxTokens:e.maxTokens??60,temperature:e.temperature??.3,signal:e.signal,headers:Object.keys(o).length>0?o:void 0})).content.filter(e=>e.type===`text`).map(e=>e.text).join(``).trim();return n.length>0?n:null}catch(e){return f_.debug(`Quick label call failed`,{error:e instanceof Error?e.message:String(e)}),null}}function Xre(e,t){let n=vt(e);if(n.length===0)return;let r=n.find(e=>e.id===t)??n[0],i=Qre(r.id),a=n.filter(e=>Zre(e,r,i));return a.length===0?r:(a.sort((e,t)=>(e.cost?.input??0)-(t.cost?.input??0)),a[0])}function Zre(e,t,n){if(e.id===t.id)return!1;let r=t.cost?.input??1/0;if((e.cost?.input??1/0)>=r)return!1;let i=e.id.toLowerCase();switch(n){case`claude`:return i.includes(`haiku`);case`gpt`:return/(^|-)mini(-|$)|(^|-)nano(-|$)/.test(i);case`gemini`:return i.includes(`flash`);case`grok`:return/(^|-)mini(-|$)|(^|-)fast(-|$)/.test(i);case`unknown`:return!0}}function Qre(e){let t=e.toLowerCase();return t.includes(`claude`)?`claude`:t.includes(`gemini`)?`gemini`:t.includes(`grok`)?`grok`:/^(gpt|o\d)/.test(t)?`gpt`:`unknown`}function p_(e,t){return vt(e).find(e=>e.id===t)}function $re(){return Bee(`ui-quick-llm`)}const eie=r(`sudo-suggest`),tie=[`You generalize a single shell command into a minimal glob pattern for an`,`allow-list rule. Output ONLY the pattern on one line — no prose, no quotes,`,`no backticks. Keep the leading command/sub-command verbatim and replace only`,`the volatile tail (args, paths, refs) with a single trailing "*".`,`Examples:`,` git push origin main -> git push*`,` rm -rf build/cache -> rm -rf*`,` npm install left-pad -> npm install*`].join(`
|
|
977
977
|
`),nie=[`You generalize a single filesystem path into a minimal glob pattern for an`,`allow-list rule. Output ONLY the pattern on one line — no prose, no quotes,`,`no backticks. Keep the meaningful directory prefix and replace the volatile`,`leaf (and below) with "**". Examples:`,` /workspace/.git/config -> /workspace/.git/**`,` /shared/secrets/openai.key -> /shared/secrets/**`,` /workspace/src/app/main.ts -> /workspace/src/**`].join(`
|
|
978
978
|
`);async function m_(e,t){if(e.suggestedPattern&&e.suggestedPattern.trim().length>0)return e.suggestedPattern.trim();let n=e.detail.trim(),r=e.kind===`command`?tie:nie,i=null;try{i=await Yre({prompt:n,system:r,maxTokens:40,temperature:0,signal:t})}catch(e){eie.debug(`suggestPattern: quickLabel threw`,{error:e instanceof Error?e.message:String(e)}),i=null}return rie(i)||n}function rie(e){if(!e)return null;let t=(e.split(`
|
|
979
|
-
`,1)[0]?.trim()??``).replace(/^`+/,``).replace(/`+$/,``).replace(/^["']/,``).replace(/["']$/,``).trim();return t.length===0?null:t}const h_=r(`sudo-ext`);function g_(e={}){let t=e.suggest??m_;return{async requestApproval(e,n){let r=n?.signal,i;try{i=await t(e,r)}catch{i=e.detail}return r?.aborted?(h_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`}):__({...e,suggestedPattern:i})}}}function __(e){return new Promise(t=>{let n=globalThis.chrome?.runtime;if(!n||typeof n.sendMessage!=`function`){h_.warn(`chrome.runtime.sendMessage unavailable — denying`),t({decision:`deny`});return}let r=r=>{let i=n.lastError;if(i){h_.warn(`sudo relay lastError — denying`,{error:i.message}),t({decision:`deny`});return}if(!r||typeof r!=`object`){h_.warn(`sudo relay empty response — denying`),t({decision:`deny`});return}let a=r;if(!a.ok||!a.decision){h_.warn(`sudo relay error response — denying`,{error:a.error}),t({decision:`deny`});return}t(v_(a.decision,e.suggestedPattern??e.detail))};try{n.sendMessage({source:`offscreen`,payload:{type:`sudo-request`,request:e}},r)}catch(e){h_.warn(`sudo relay threw — denying`,{error:e instanceof Error?e.message:String(e)}),t({decision:`deny`})}})}function v_(e,t){return e.decision===`allow`?{decision:`allow`}:e.decision===`always`?{decision:`always`,pattern:typeof e.pattern==`string`&&e.pattern.trim().length>0?e.pattern.trim():t}:{decision:`deny`}}const y_=r(`sudo-http`);function b_(e={}){let t=e.fetchImpl??globalThis.fetch.bind(globalThis),n=e.path??`/api/sudo-approve`,r=e.suggest??m_;return{async requestApproval(e,i){let a=i?.signal,o;if(e.suggestedPattern)o=e.suggestedPattern;else try{o=await r(e,a)}catch{o=e.detail}if(a?.aborted)return y_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`};try{let r=await t(At(n),{method:`POST`,headers:jt({"Content-Type":`application/json`}),body:JSON.stringify({kind:e.kind,detail:e.detail,suggestedPattern:o}),signal:a});return r.ok?x_(await r.json(),o):(y_.warn(`sudo endpoint returned non-OK status — denying`,{status:r.status}),{decision:`deny`})}catch(e){return y_.warn(`sudo endpoint request failed — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}}}}function x_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e.decision;if(n===`allow`)return{decision:`allow`};if(n===`always`){let n=e.pattern;return{decision:`always`,pattern:typeof n==`string`&&n.trim().length>0?n.trim():t}}return{decision:`deny`}}const S_=r(`sudo-panel-rpc`);function C_(e={}){let t=e.suggest??m_,n=e.timeoutMs??6e5,r=e.getClient??(async()=>{let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);return e()});return{async requestApproval(e,i){let a=i?.signal,o;try{o=await t(e,a)}catch{o=e.detail}let s={...e,suggestedPattern:o},c;try{c=await r()}catch(e){return S_.warn(`panel-RPC client lookup threw — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}if(!c)return S_.warn(`panel-RPC client unavailable in worker realm — denying`),{decision:`deny`};if(a?.aborted)return S_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`};try{let{decision:e}=await c.call(`sudo-request`,{request:s},{timeoutMs:n});return w_(e,o)}catch(e){return S_.warn(`sudo panel-RPC relay failed — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}}}}function w_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e.decision;if(n===`allow`)return{decision:`allow`};if(n===`always`){let n=e.pattern;return{decision:`always`,pattern:typeof n==`string`&&n.trim().length>0?n.trim():t}}return{decision:`deny`}}const T_=r(`sudo:tray-first`);function E_(e,t={}){let n=t.suggest??m_,r=t.timeoutMs??6e5,i=t.getClient??(async()=>{let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);return e()});return{async requestApproval(t,a){if(a?.signal?.aborted)return{decision:`deny`};let o=t.suggestedPattern;if(!o)try{o=await n(t,a?.signal)}catch{o=t.detail}let s={...t,suggestedPattern:o},c=null;try{c=await i()}catch(e){T_.debug?.(`panel-RPC client lookup threw — using native broker`,{error:e instanceof Error?e.message:String(e)})}if(c)try{let e=await c.call(`sudo-request`,{request:s,mode:`tray-first`},{timeoutMs:r});if(e?.handled!==!1)return D_(e?.decision,o)}catch(e){T_.warn(`tray-first sudo probe failed — using native broker`,{error:e instanceof Error?e.message:String(e)})}return e.requestApproval(s,a)}}}function D_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e,r=n.attestation===`biometric`||n.attestation===`passcode`||n.attestation===`none`?n.attestation:void 0;return n.decision===`allow`?{decision:`allow`,...r?{attestation:r}:{}}:n.decision===`always`?{decision:`always`,pattern:typeof n.pattern==`string`&&n.pattern.trim().length>0?n.pattern.trim():t,...r?{attestation:r}:{}}:{decision:`deny`}}function O_(e,t){return{requestApproval(n){return t.enqueueSudoRequest(e,n)}}}function k_(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var A_=class{pending=new Map;timeoutMs;newId;setTimer;clearTimer;onAutoSettle;constructor(e={}){this.timeoutMs=e.timeoutMs??3e5,this.newId=e.newId??k_,this.setTimer=e.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=e.clearTimer??(e=>clearTimeout(e)),this.onAutoSettle=e.onAutoSettle??(()=>{})}notifyAutoSettle(e,t){try{this.onAutoSettle(e,t)}catch{}}register(e,t){let n=this.newId();return{id:n,pending:new Promise(r=>{let i=null;Number.isFinite(this.timeoutMs)&&this.timeoutMs>0&&(i=this.setTimer(()=>{let e=this.pending.get(n);e&&(this.pending.delete(n),e.resolve(
|
|
980
|
-
`)}\n`}var H_=class{fs;watcher;broker;onPolicyReload;policy=
|
|
981
|
-
`)?`${o}\n`:o;return await this.fs.writeFile(a,`${s}NOPASSWD ${i} ${r}\n`),await this.reloadScoopPolicy(e),F_.info(`Appended per-scoop sudoers rule`,{folder:e,kind:t,pattern:r}),r}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null,this.scoopUnwatch?.(),this.scoopUnwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=
|
|
982
|
-
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(tr,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,I_,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,R_,e=>{let t=new Set;for(let n of e){let e=z_(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let U_=null;function W_(e){return U_=e,()=>{U_===e&&(U_=null)}}function G_(){if(!U_)throw new _(`session-not-found`);return U_}function K_(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function q_(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)q_(e[r],`${t}/${r}`,n);return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))q_(i,`${t}/${K_(r)}`,n)}function J_(e,t,n){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=X_(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}function Y_(e,t,n){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=X_(o,`${t}/${K_(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}function X_(e,t,n){return typeof e==`string`?n.get(t)??e:Array.isArray(e)?J_(e,t,n):typeof e==`object`&&e?Y_(e,t,n):e}function Z_(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function Q_(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new _(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new _(`redaction-unavailable`)}if(c.length!==s.length)throw new _(`redaction-unavailable`);r.push(...c),i=o}return r}function $_(e,t,n,r){let i=[],a=Z_(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Z_(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=y(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function ev(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function tv(e,t,n,r){if(r?.aborted)throw new _(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];q_(a,``,o);let s=[...t.entries()],c=await Q_([...o.map(e=>e.value),...s.map(([,e])=>e)],n,r),l=[],u={},d=1,f=new Map,p=[];for(let e=0;e<o.length;e++){let t=o[e],n=$_(t.value,c[e],{kind:`json`,pointer:t.pointer},d);d=n.nextId,n.finalText!==t.value&&f.set(t.pointer,n.finalText),p.push(n)}ev(p,l,u);let m=new Map,h=o.length,g=[];for(let e=0;e<s.length;e++){let[t,n]=s[e],r=$_(n,c[h+e],{kind:`attachment`,attachmentId:t},d);d=r.nextId,m.set(t,r.finalText),g.push(r)}ev(g,l,u);let v=X_(e,``,f);return{document:{...v,privacy:{...v.privacy,redactionCounts:u,redactions:l}},textAttachments:m}}function nv(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function rv(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const iv={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function av(e,t){return iv[e]??(t===`text-redacted`?`.txt`:`.bin`)}function ov(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${av(t,n)}`}function sv(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}function cv(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function lv(e,t,n,r,i){let a=nv(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(sv(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=sv(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function uv(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:sv(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(lv(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function dv(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function fv(e,t,n,r,i,a,o){let s=dv(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(lv(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function pv(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=fv(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function mv(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,ov(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function hv(e,t,n,r,i){let{rawAttachments:a,textMap:o}=mv(e,n),s,c;try{let e=await tv({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof _?e:new _(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new _(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new _(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await rv(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function gv(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=uv(cv(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=pv(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await hv(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function _v(e){return mh(e)}function vv(e,t){let n=new Set([t]);for(let t=0;t<e.length;t++){let t=!1;for(let r of e)n.has(r.jid)||r.parentJid!==null&&n.has(r.parentJid)&&(n.add(r.jid),t=!0);if(!t)break}return e.filter(e=>n.has(e.jid))}function yv(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function bv(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:rh(t)?`cone`:`scoop`,name:t.name,...t.folder&&!rh(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=_v(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function xv(e,t,n={}){let r=e=>n.rootJid===void 0?e:vv(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new _(`transfer-aborted`);let i=yv(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new _(`transfer-aborted`);let s=r(e.listScoops());if(i===yv(s,e))return bv(s,a,o,e)}}function Sv(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Cv(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function wv(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Cv(t,r++));return n}function Tv(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Cv(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Ev(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Cv(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Dv(e,t,n){let r=Sv(t,n),i=wv(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function Ov(e,t,n){let r=Sv(t,n),{blocks:i,excluded:a,images:o}=Tv(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function kv(e,t,n){let r=Sv(t,n),{blocks:i,images:a}=Ev(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function Av(e,t,n){return e.role===`user`?Dv(e,t,n):e.role===`assistant`?Ov(e,t,n):e.role===`toolResult`?kv(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function jv(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function Mv(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=Av(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:jv(e),excludedReasoningBlocks:t,canonicalImages:n}}var Nv=`input is invalid type`,Pv=`finalize already called`,Fv=typeof ArrayBuffer<`u`,Iv=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(Fv&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(Nv)},G=`0123456789abcdef`.split(``),Lv=[-2147483648,8388608,32768,128],Rv=[24,16,8,0],zv=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Bv=[`hex`,`array`,`digest`,`arrayBuffer`],Vv=[],Hv=function(e,t){return function(n){return new Kv(t,!0).update(n)[e]()}},Uv=function(e){var t=Hv(`hex`,e);t.create=function(){return new Kv(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<Bv.length;++n){var r=Bv[n];t[r]=Hv(r,e)}return t},Wv=function(e,t){return function(n,r){return new qv(n,t,!0).update(r)[e]()}},Gv=function(e){var t=Wv(`hex`,e);t.create=function(t){return new qv(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<Bv.length;++n){var r=Bv[n];t[r]=Wv(r,e)}return t};function Kv(e,t){t?(Vv[0]=Vv[16]=Vv[1]=Vv[2]=Vv[3]=Vv[4]=Vv[5]=Vv[6]=Vv[7]=Vv[8]=Vv[9]=Vv[10]=Vv[11]=Vv[12]=Vv[13]=Vv[14]=Vv[15]=0,this.blocks=Vv):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Kv.prototype.update=function(e){if(this.finalized)throw Error(Pv);var t=Iv(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<Rv[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<Rv[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<Rv[a++&3],s[a>>>2]|=(128|r>>>12&63)<<Rv[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<Rv[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},Kv.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Lv[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Kv.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+zv[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+zv[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+zv[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+zv[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},Kv.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=G[e>>>28&15]+G[e>>>24&15]+G[e>>>20&15]+G[e>>>16&15]+G[e>>>12&15]+G[e>>>8&15]+G[e>>>4&15]+G[e&15]+G[t>>>28&15]+G[t>>>24&15]+G[t>>>20&15]+G[t>>>16&15]+G[t>>>12&15]+G[t>>>8&15]+G[t>>>4&15]+G[t&15]+G[n>>>28&15]+G[n>>>24&15]+G[n>>>20&15]+G[n>>>16&15]+G[n>>>12&15]+G[n>>>8&15]+G[n>>>4&15]+G[n&15]+G[r>>>28&15]+G[r>>>24&15]+G[r>>>20&15]+G[r>>>16&15]+G[r>>>12&15]+G[r>>>8&15]+G[r>>>4&15]+G[r&15]+G[i>>>28&15]+G[i>>>24&15]+G[i>>>20&15]+G[i>>>16&15]+G[i>>>12&15]+G[i>>>8&15]+G[i>>>4&15]+G[i&15]+G[a>>>28&15]+G[a>>>24&15]+G[a>>>20&15]+G[a>>>16&15]+G[a>>>12&15]+G[a>>>8&15]+G[a>>>4&15]+G[a&15]+G[o>>>28&15]+G[o>>>24&15]+G[o>>>20&15]+G[o>>>16&15]+G[o>>>12&15]+G[o>>>8&15]+G[o>>>4&15]+G[o&15];return this.is224||(c+=G[s>>>28&15]+G[s>>>24&15]+G[s>>>20&15]+G[s>>>16&15]+G[s>>>12&15]+G[s>>>8&15]+G[s>>>4&15]+G[s&15]),c},Kv.prototype.toString=Kv.prototype.hex,Kv.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},Kv.prototype.array=Kv.prototype.digest,Kv.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function qv(e,t,n){var r,i=Iv(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new Kv(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}Kv.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}qv.prototype=new Kv,qv.prototype.finalize=function(){if(Kv.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();Kv.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),Kv.prototype.finalize.call(this)}};var Jv=Uv(),Yv=Uv(!0);Jv.sha256=Jv,Jv.sha224=Yv,Jv.hmac=Gv(),Yv.hmac=Gv(!0);const Xv=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function Zv(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^Xv[(t^e[n])&255];return~t>>>0}const Qv=new TextEncoder;function $v(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function ey(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function ty(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,$v(r,4,20),$v(r,6,2048),$v(r,8,0),$v(r,10,0),$v(r,12,0),ey(r,14,n),ey(r,18,t),ey(r,22,t),$v(r,26,e.length),$v(r,28,0),r.set(e,30),r}function ny(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,$v(i,4,20),$v(i,6,20),$v(i,8,2048),$v(i,10,0),$v(i,12,0),$v(i,14,0),ey(i,16,n),ey(i,20,t),ey(i,24,t),$v(i,28,e.length),$v(i,30,0),$v(i,32,0),$v(i,34,0),$v(i,36,0),ey(i,38,0),ey(i,42,r),i.set(e,46),i}function ry(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,$v(r,4,0),$v(r,6,0),$v(r,8,e),$v(r,10,e),ey(r,12,t),ey(r,16,n),$v(r,20,0),r}function iy(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function ay(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${e.session.title.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)||`transcript`}-${n}.zip`}async function*oy(e,t,n,r,i){if(n?.aborted)throw i(new _(`transfer-aborted`)),new _(`transfer-aborted`);let a=()=>i(new _(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=Jv.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=Qv.encode(`transcript.json`),f=Zv(i),p=ty(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new _(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new _(`transfer-aborted`);let t=Qv.encode(e),i=Zv(r),a=ty(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new _(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new _(`transfer-aborted`);yield*d(ny(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new _(`transfer-aborted`);yield*d(ry(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new _(`transfer-aborted`)))}}function sy(e,t,n){for(let e of t.keys())if(!iy(e))throw new _(`schema-invalid`);if(t.size+1>65535)throw new _(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new _(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:ay(e),chunks:oy(e,t,n,r,i),completion:a}}function cy(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:g},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function ly(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function uy(e){if(!h(e).ok)throw new _(`schema-invalid`)}function dy(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path))if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}return r}async function fy(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function py(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var my=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),uy(i.document),r?.({phase:`packaging`}),sy(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await xv(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=Mv(n.sources),{document:i,bundleFiles:a}=await gv({document:cy(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});uy(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await xv(this.deps.collection,e),r=Mv(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=cy(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),gv({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await tv(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new _(`redaction-unavailable`)}let a=dy(r.attachments,i,e.attachments),o=await fy(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await Wee(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new _(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new _(`session-not-found`)}let{title:a,messages:o}=Uee(i),s=`legacy-cone`,c=ly(o,s),l=py(i),u={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:g},session:{id:e,title:a,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...l,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:s,kind:`cone`,name:a,messages:c}],delegations:[],attachments:[]},d=new Map([[s,o]]);return n?.({phase:`redacting`}),gv({document:u,chatMessagesByConversation:d,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new _(`attachment-unreadable`);return t}};const hy=`/sessions/data`,gy=`document.json`;async function _y(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function vy(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new _(`session-not-found`)}function yy(e){return`${hy}/${e}`}function by(e){return`${hy}/.tmp-${e}`}async function xy(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function Sy(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await Sy(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Cy(e,t,n){await xy(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Cy(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function wy(e,t,n){vy(t);let r=by(t),i=yy(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new _(`schema-invalid`);await Sy(e,i),await xy(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await _y(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${gy}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await xy(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Cy(e,r,i),await e.flush()}catch(t){throw await Sy(e,r),t}await Sy(e,r)}async function Ty(e,t){vy(t);let n=yy(t),r=`${n}/${gy}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new _(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new _(`schema-invalid`)}if(!h(a).ok)throw new _(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new _(`transfer-corrupt`)}if(await _y(i)!==t.sha256)throw new _(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Ey(){throw new _(`redaction-unavailable`)}function Dy(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Ey(),e.texts}function Oy(){return{async redact(e){let t;try{t=await fetch(At(`/api/secrets/redact-export`),{method:`POST`,headers:jt({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Ey()}t.ok||Ey();let n;try{n=await t.json()}catch{Ey()}return Dy(n,e.length)}}}function ky(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Ey()}return typeof t==`object`&&t&&`error`in t&&Ey(),Dy(t,e.length)}}}function Ay(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{Ey()}return t??Ey(),typeof t==`object`&&`error`in t&&Ey(),Dy(t,e.length)}}}function jy(){return{async redact(e){Ey()}}}function My(){let e=Xe();return e===`connect`?jy():e===`extension-direct`?ky():e===`extension-delegate`?Ay():Oy()}const Ny=r(`cone-memory-budget`),Py=Mh.memoryPath,Fy=/^## Auto-extracted/m;function Iy(e){return Math.round(4e3+2e3*Math.log2((Number.isFinite(e)&&e>=0?e:0)+2))}function Ly(e){let t=Fy.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function Ry(e){try{let t=await e.readFile(`/sessions/index.json`,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r.length:0}catch{return 0}}async function zy(e){let{header:t,autoExtracted:n}=Ly(e.currentContent);if(!n.trim())return e.currentContent;let r=`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
|
|
979
|
+
`,1)[0]?.trim()??``).replace(/^`+/,``).replace(/`+$/,``).replace(/^["']/,``).replace(/["']$/,``).trim();return t.length===0?null:t}const h_=r(`sudo-ext`);function g_(e={}){let t=e.suggest??m_;return{async requestApproval(e,n){let r=n?.signal,i;try{i=await t(e,r)}catch{i=e.detail}return r?.aborted?(h_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`}):__({...e,suggestedPattern:i})}}}function __(e){return new Promise(t=>{let n=globalThis.chrome?.runtime;if(!n||typeof n.sendMessage!=`function`){h_.warn(`chrome.runtime.sendMessage unavailable — denying`),t({decision:`deny`});return}let r=r=>{let i=n.lastError;if(i){h_.warn(`sudo relay lastError — denying`,{error:i.message}),t({decision:`deny`});return}if(!r||typeof r!=`object`){h_.warn(`sudo relay empty response — denying`),t({decision:`deny`});return}let a=r;if(!a.ok||!a.decision){h_.warn(`sudo relay error response — denying`,{error:a.error}),t({decision:`deny`});return}t(v_(a.decision,e.suggestedPattern??e.detail))};try{n.sendMessage({source:`offscreen`,payload:{type:`sudo-request`,request:e}},r)}catch(e){h_.warn(`sudo relay threw — denying`,{error:e instanceof Error?e.message:String(e)}),t({decision:`deny`})}})}function v_(e,t){return e.decision===`allow`?{decision:`allow`}:e.decision===`always`?{decision:`always`,pattern:typeof e.pattern==`string`&&e.pattern.trim().length>0?e.pattern.trim():t}:{decision:`deny`}}const y_=r(`sudo-http`);function b_(e={}){let t=e.fetchImpl??globalThis.fetch.bind(globalThis),n=e.path??`/api/sudo-approve`,r=e.suggest??m_;return{async requestApproval(e,i){let a=i?.signal,o;if(e.suggestedPattern)o=e.suggestedPattern;else try{o=await r(e,a)}catch{o=e.detail}if(a?.aborted)return y_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`};try{let r=await t(At(n),{method:`POST`,headers:jt({"Content-Type":`application/json`}),body:JSON.stringify({kind:e.kind,detail:e.detail,suggestedPattern:o}),signal:a});return r.ok?x_(await r.json(),o):(y_.warn(`sudo endpoint returned non-OK status — denying`,{status:r.status}),{decision:`deny`})}catch(e){return y_.warn(`sudo endpoint request failed — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}}}}function x_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e.decision;if(n===`allow`)return{decision:`allow`};if(n===`always`){let n=e.pattern;return{decision:`always`,pattern:typeof n==`string`&&n.trim().length>0?n.trim():t}}return{decision:`deny`}}const S_=r(`sudo-panel-rpc`);function C_(e={}){let t=e.suggest??m_,n=e.timeoutMs??6e5,r=e.getClient??(async()=>{let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);return e()});return{async requestApproval(e,i){let a=i?.signal,o;try{o=await t(e,a)}catch{o=e.detail}let s={...e,suggestedPattern:o},c;try{c=await r()}catch(e){return S_.warn(`panel-RPC client lookup threw — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}if(!c)return S_.warn(`panel-RPC client unavailable in worker realm — denying`),{decision:`deny`};if(a?.aborted)return S_.warn(`sudo approval aborted before prompting — denying`,{detail:e.detail}),{decision:`deny`};try{let{decision:e}=await c.call(`sudo-request`,{request:s},{timeoutMs:n});return w_(e,o)}catch(e){return S_.warn(`sudo panel-RPC relay failed — denying`,{error:e instanceof Error?e.message:String(e)}),{decision:`deny`}}}}}function w_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e.decision;if(n===`allow`)return{decision:`allow`};if(n===`always`){let n=e.pattern;return{decision:`always`,pattern:typeof n==`string`&&n.trim().length>0?n.trim():t}}return{decision:`deny`}}const T_=r(`sudo:tray-first`);function E_(e,t={}){let n=t.suggest??m_,r=t.timeoutMs??6e5,i=t.getClient??(async()=>{let{getPanelRpcClient:e}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);return e()});return{async requestApproval(t,a){if(a?.signal?.aborted)return{decision:`deny`};let o=t.suggestedPattern;if(!o)try{o=await n(t,a?.signal)}catch{o=t.detail}let s={...t,suggestedPattern:o},c=null;try{c=await i()}catch(e){T_.debug?.(`panel-RPC client lookup threw — using native broker`,{error:e instanceof Error?e.message:String(e)})}if(c)try{let e=await c.call(`sudo-request`,{request:s,mode:`tray-first`},{timeoutMs:r});if(e?.handled!==!1)return D_(e?.decision,o)}catch(e){T_.warn(`tray-first sudo probe failed — using native broker`,{error:e instanceof Error?e.message:String(e)})}return e.requestApproval(s,a)}}}function D_(e,t){if(!e||typeof e!=`object`)return{decision:`deny`};let n=e,r=n.attestation===`biometric`||n.attestation===`passcode`||n.attestation===`none`?n.attestation:void 0;return n.decision===`allow`?{decision:`allow`,...r?{attestation:r}:{}}:n.decision===`always`?{decision:`always`,pattern:typeof n.pattern==`string`&&n.pattern.trim().length>0?n.pattern.trim():t,...r?{attestation:r}:{}}:{decision:`deny`}}function O_(e,t){return{requestApproval(n){return t.enqueueSudoRequest(e,n)}}}function k_(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var A_=class{pending=new Map;timeoutMs;newId;setTimer;clearTimer;onAutoSettle;constructor(e={}){this.timeoutMs=e.timeoutMs??3e5,this.newId=e.newId??k_,this.setTimer=e.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=e.clearTimer??(e=>clearTimeout(e)),this.onAutoSettle=e.onAutoSettle??(()=>{})}notifyAutoSettle(e,t){try{this.onAutoSettle(e,t)}catch{}}register(e,t){let n=this.newId();return{id:n,pending:new Promise(r=>{let i=null;Number.isFinite(this.timeoutMs)&&this.timeoutMs>0&&(i=this.setTimer(()=>{let e=this.pending.get(n);e&&(this.pending.delete(n),e.resolve(Fee(`cone-timeout`)),this.notifyAutoSettle(n,`expired`))},this.timeoutMs)),this.pending.set(n,{scoopJid:e,request:t,resolve:r,timerHandle:i})})}}resolve(e,t){let n=this.pending.get(e);return n?(this.pending.delete(e),n.timerHandle!=null&&this.clearTimer(n.timerHandle),n.resolve(t),!0):!1}failScoop(e){let t=0;for(let[n,r]of this.pending)r.scoopJid===e&&(this.pending.delete(n),r.timerHandle!=null&&this.clearTimer(r.timerHandle),r.resolve({decision:`deny`}),this.notifyAutoSettle(n,`scoop-dropped`),t++);return t}failAll(){let e=0;for(let[t,n]of this.pending)n.timerHandle!=null&&this.clearTimer(n.timerHandle),n.resolve({decision:`deny`}),this.notifyAutoSettle(t,`shutdown`),e++;return this.pending.clear(),e}get(e){let t=this.pending.get(e);return t?{id:e,scoopJid:t.scoopJid,request:t.request}:null}list(){let e=[];for(let[t,n]of this.pending)e.push({id:t,scoopJid:n.scoopJid,request:n.request});return e}size(){return this.pending.size}};r(`sudo-panel`),typeof globalThis.confirm==`function`&&globalThis.confirm.bind(globalThis),typeof globalThis.prompt==`function`&&globalThis.prompt.bind(globalThis),r(`sudo:page`),r(`sudo`);function j_(){return Tt()}function M_(){return typeof chrome>`u`&&see()!==null}function N_(){return Lee(P_())}function P_(){return j_()?g_():M_()?C_():E_(b_())}const F_=r(`sudo:manager`);function I_(e){return e===`/etc/sudoers`||e===`/etc/sudoers.d`||e.startsWith(`/etc/sudoers.d/`)}const L_=/^\/scoops\/([^/]+)\/etc\/sudoers$/;function R_(e){return L_.test(e)}function z_(e){return L_.exec(e)?.[1]??null}function B_(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}function V_(e){let t=[`# Per-scoop sudoers — generated from ScoopConfig (sandbox surface).`,`# Writes to this file always require approval (self-protected).`,``],n=e?.allowedCommands;if(n===void 0||n.includes(`*`))t.push(`NOPASSWD Cmnd *`);else for(let e of n){let n=rr(e);n&&(t.push(`NOPASSWD Cmnd ${n}`),t.push(`NOPASSWD Cmnd ${n} *`))}for(let n of e?.writablePaths??[]){let e=rr(n);e&&(t.push(`NOPASSWD Write ${B_(e)}`),t.push(`NOPASSWD Write ${B_(e)}/**`))}for(let n of e?.visiblePaths??[]){let e=rr(n);e&&(t.push(`NOPASSWD Read ${B_(e)}`),t.push(`NOPASSWD Read ${B_(e)}/**`))}return`${t.join(`
|
|
980
|
+
`)}\n`}var H_=class{fs;watcher;broker;onPolicyReload;policy=tr();unwatch=null;scoopUnwatch=null;reloadChain=Promise.resolve();scoopPolicies=new Map;scoopReloadChains=new Map;constructor(e){this.fs=e.fs,this.watcher=e.watcher??null,this.broker=e.broker??N_(),this.onPolicyReload=e.onPolicyReload??(()=>{})}async init(){await this.ensureDefaults(),await this.reload(),this.startWatching()}getBroker(){return this.broker}async approve(e){if(e.kind===`export`&&jee(this.policy,e.detail)===`nopasswd-allow`)return F_.info(`Export pre-granted by sudoers`,{subject:e.detail}),{decision:`allow`};let t=await this.broker.requestApproval(e);if(t.decision===`always`){let n=t.pattern?.trim()||e.suggestedPattern?.trim()||e.detail;try{await this.persistGrant(Iee(e.kind),n)}catch(n){return F_.warn(`Failed to persist "Always" grant; honouring as one-shot allow`,{kind:e.kind,error:n instanceof Error?n.message:String(n)}),{decision:`allow`,attestation:t.attestation}}}return t}getPolicy(){return this.policy}getPolicyForScoop(e){let t=this.scoopPolicies.get(e),n=[kee(),this.policy];return t&&n.push(t),Xn(...n)}async seedScoopSudoers(e,t){let n=Qn(e),r=V_(t??void 0);try{await this.fs.mkdir(`/scoops/${e}/etc`,{recursive:!0})}catch{}await this.fs.writeFile(n,r),await this.reloadScoopPolicy(e),F_.info(`Seeded per-scoop sudoers`,{folder:e,path:n})}async appendScoopRule(e,t,n){let r=rr(n);if(!r)return null;let i=t===`command`?`Cmnd`:t===`read`?`Read`:`Write`,a=Qn(e),o=``;try{if(await this.fs.exists(a)){let e=await this.fs.readFile(a,{encoding:`utf-8`});o=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof $t&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir(`/scoops/${e}/etc`,{recursive:!0})}catch{}let s=o&&!o.endsWith(`
|
|
981
|
+
`)?`${o}\n`:o;return await this.fs.writeFile(a,`${s}NOPASSWD ${i} ${r}\n`),await this.reloadScoopPolicy(e),F_.info(`Appended per-scoop sudoers rule`,{folder:e,kind:t,pattern:r}),r}getShellConfig(e={}){return{getPolicy:()=>this.policy,broker:this.broker,persistCommandGrant:e=>this.persistCommandGrant(e),transparentGating:e.transparentGating??!0}}reload(){return this.reloadChain=this.reloadChain.then(()=>this.doReload()),this.reloadChain}reloadScoopPolicyByFolder(e){return this.reloadScoopPolicy(e)}dispose(){this.unwatch?.(),this.unwatch=null,this.scoopUnwatch?.(),this.scoopUnwatch=null}reloadScoopPolicy(e){let t=(this.scoopReloadChains.get(e)??Promise.resolve()).then(()=>this.doReloadScoopPolicy(e));return this.scoopReloadChains.set(e,t),t}async doReloadScoopPolicy(e){let t=Qn(e);try{if(!await this.fs.exists(t)){this.scoopPolicies.delete(e),this.onPolicyReload(e);return}}catch{this.scoopPolicies.delete(e),this.onPolicyReload(e);return}this.scoopPolicies.set(e,await this.readPolicyFile(t)),this.onPolicyReload(e)}async doReload(){let e=[await this.readPolicyFile(er)];try{let t=(await this.fs.readDir($n)).filter(e=>e.type===`file`).map(e=>e.name).sort();for(let n of t)e.push(await this.readPolicyFile(`${$n}/${n}`))}catch{}this.policy=Xn(...e),this.onPolicyReload()}async readPolicyFile(e){try{if(!await this.fs.exists(e))return tr();let t=await this.fs.readFile(e,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t);return zee(n)}catch(t){return F_.warn(`Failed to read sudoers file; ignoring`,{path:e,error:t instanceof Error?t.message:String(t)}),tr()}}async ensureDefaults(){try{await this.fs.mkdir($n,{recursive:!0})}catch{}try{await this.fs.exists(`/etc/sudoers`)||(await this.fs.writeFile(er,Jre),F_.info(`Seeded default /etc/sudoers template`))}catch(e){F_.warn(`Failed to seed default /etc/sudoers`,{error:e instanceof Error?e.message:String(e)})}}persistCommandGrant(e){return this.persistGrant(`Cmnd`,e)}async persistGrant(e,t){let n=rr(t);if(!n)return;let r=``;try{if(await this.fs.exists(nr)){let e=await this.fs.readFile(nr,{encoding:`utf-8`});r=typeof e==`string`?e:new TextDecoder().decode(e)}}catch(e){if(!(e instanceof $t&&e.code===`ENOENT`))throw e}try{await this.fs.mkdir($n,{recursive:!0})}catch{}let i=r&&!r.endsWith(`
|
|
982
|
+
`)?`${r}\n`:r,a=e===`Cmnd`?` `:` `;await this.fs.writeFile(nr,`${i}NOPASSWD ${e}${a}${n}\n`),await this.reload()}startWatching(){this.watcher&&(this.unwatch||=this.watcher.watch(`/etc`,I_,()=>{this.reload()}),this.scoopUnwatch||=this.watcher.watch(`/scoops`,R_,e=>{let t=new Set;for(let n of e){let e=z_(n.path);e&&t.add(e)}for(let e of t)this.reloadScoopPolicy(e)}))}};let U_=null;function W_(e){return U_=e,()=>{U_===e&&(U_=null)}}function G_(){if(!U_)throw new _(`session-not-found`);return U_}function K_(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function q_(e,t,n){if(typeof e==`string`){n.push({pointer:t,value:e});return}if(Array.isArray(e)){for(let r=0;r<e.length;r++)q_(e[r],`${t}/${r}`,n);return}if(typeof e==`object`&&e)for(let[r,i]of Object.entries(e))q_(i,`${t}/${K_(r)}`,n)}function J_(e,t,n){let r=!1,i=[];for(let a=0;a<e.length;a++){let o=X_(e[a],`${t}/${a}`,n);o!==e[a]&&(r=!0),i.push(o)}return r?i:e}function Y_(e,t,n){let r=!1,i={};for(let[a,o]of Object.entries(e)){let e=X_(o,`${t}/${K_(a)}`,n);e!==o&&(r=!0),i[a]=e}return r?i:e}function X_(e,t,n){return typeof e==`string`?n.get(t)??e:Array.isArray(e)?J_(e,t,n):typeof e==`object`&&e?Y_(e,t,n):e}function Z_(e){let t=new Map;for(let n of e.matchAll(/⟦REDACTED:([^:⟧]+):([^⟧]+)⟧/g)){let e=n[0],r=t.get(e);r?r.count++:t.set(e,{category:n[1],id:n[2],count:1})}return t}async function Q_(e,t,n){let r=[],i=0;for(;i<e.length;){if(n?.aborted)throw new _(`redaction-unavailable`);let a=0,o=i;for(;o<e.length;){let t=e[o].length;if(o>i&&a+t>1048576)break;a+=t,o++}let s=e.slice(i,o),c;try{c=await t.redact(s,n)}catch{throw new _(`redaction-unavailable`)}if(c.length!==s.length)throw new _(`redaction-unavailable`);r.push(...c),i=o}return r}function $_(e,t,n,r){let i=[],a=Z_(e);for(let{category:e,id:t}of a.values())i.push({id:t,category:e,detector:`pre-obfuscated`,target:n});let o=Z_(t);for(let[e,{category:t,id:r,count:s}]of o)s>(a.get(e)?.count??0)&&i.push({id:r,category:t,detector:`known-secret`,target:n});let{text:s,matches:c,nextId:l}=y(t,`r`,r);for(let{id:e,category:t}of c)i.push({id:e,category:t,detector:`credential-pattern`,target:n});return{finalText:s,redactions:i,nextId:l}}function ev(e,t,n){for(let{redactions:r}of e)for(let e of r)t.push(e),n[e.category]=(n[e.category]??0)+1}async function tv(e,t,n,r){if(r?.aborted)throw new _(`redaction-unavailable`);let{privacy:i,...a}=e,o=[];q_(a,``,o);let s=[...t.entries()],c=await Q_([...o.map(e=>e.value),...s.map(([,e])=>e)],n,r),l=[],u={},d=1,f=new Map,p=[];for(let e=0;e<o.length;e++){let t=o[e],n=$_(t.value,c[e],{kind:`json`,pointer:t.pointer},d);d=n.nextId,n.finalText!==t.value&&f.set(t.pointer,n.finalText),p.push(n)}ev(p,l,u);let m=new Map,h=o.length,g=[];for(let e=0;e<s.length;e++){let[t,n]=s[e],r=$_(n,c[h+e],{kind:`attachment`,attachmentId:t},d);d=r.nextId,m.set(t,r.finalText),g.push(r)}ev(g,l,u);let v=X_(e,``,f);return{document:{...v,privacy:{...v.privacy,redactionCounts:u,redactions:l}},textAttachments:m}}function nv(e,t){let n=e.startsWith(`text/`)||e===`application/json`,r=/\.(?:txt|md|json|csv|xml|ya?ml|js|mjs|cjs|ts|tsx|css|html)$/i.test(t);return n||r?`text-redacted`:`binary-unchanged`}async function rv(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const iv={"image/png":`.png`,"image/jpeg":`.jpg`,"image/gif":`.gif`,"image/webp":`.webp`,"image/svg+xml":`.svg`,"image/bmp":`.bmp`,"application/pdf":`.pdf`,"application/zip":`.zip`,"application/gzip":`.gz`,"application/json":`.json`,"text/plain":`.txt`,"text/markdown":`.md`,"text/csv":`.csv`,"text/html":`.html`,"text/xml":`.xml`,"application/xml":`.xml`};function av(e,t){return iv[e]??(t===`text-redacted`?`.txt`:`.bin`)}function ov(e,t,n){return`attachments/att-${String(e+1).padStart(4,`0`)}${av(t,n)}`}function sv(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}function cv(e){let t=[];for(let n of e.conversations){let e=0;for(let r of n.messages){let i=r.role;if(i!==`user`&&i!==`assistant`&&i!==`tool-result`)continue;let a=0;for(let o of r.content)o.type===`attachment-ref`&&(t.push({attachmentId:o.attachmentId,conversationId:n.id,messageId:r.id,role:i,userOrdinal:e,imgIndex:a}),a++);i===`user`&&e++}}return t}async function lv(e,t,n,r,i){let a=nv(e.mimeType,e.name),o={attachmentId:t,originalName:e.name,mimeType:e.mimeType,handling:a,present:!0,sourceConversationId:n,sourceMessageId:r};if(a===`text-redacted`){let t;if(e.text!==void 0)t=e.text;else if(e.data!==void 0)t=new TextDecoder().decode(sv(e.data));else if(e.path!==void 0&&i!==void 0)try{t=new TextDecoder().decode(await i(e.path))}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return t===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawText:t}}let s;if(e.data!==void 0)s=sv(e.data);else if(e.path!==void 0&&i!==void 0)try{s=await i(e.path)}catch{return{...o,present:!1,missingReason:`attachment-file-missing`}}return s===void 0?{...o,present:!1,missingReason:`attachment-file-missing`}:{...o,rawBytes:s}}function uv(e,t,n,r){let i=[],a=new Set,o=new Set;for(let s of e){if(s.role!==`user`){let e=n.get(s.attachmentId);e===void 0?i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId})):i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`image-${s.imgIndex}`,mimeType:e.mimeType,handling:`binary-unchanged`,rawBytes:sv(e.data),present:!0,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let e=(t.get(s.conversationId)??[]).filter(e=>e.role===`user`)[s.userOrdinal];if(e===void 0){a.add(s.conversationId),i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-association-unavailable`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}let c=(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:e})=>e.kind===`image`||e.kind===`file`&&e.data!==void 0)[s.imgIndex];if(c===void 0){i.push(Promise.resolve({attachmentId:s.attachmentId,originalName:`unknown`,mimeType:`application/octet-stream`,handling:`binary-unchanged`,present:!1,missingReason:`attachment-file-missing`,sourceConversationId:s.conversationId,sourceMessageId:s.messageId}));continue}o.add(`${s.conversationId}:${e.id}:${c.i}`),i.push(lv(c.a,s.attachmentId,s.conversationId,s.messageId,r))}return{pendingPromises:i,mismatchedConvIds:a,processedUiPositions:o}}function dv(e,t,n){return(e.attachments??[]).map((e,t)=>({a:e,i:t})).filter(({a:r,i})=>(r.kind===`text`||r.kind===`file`&&(r.data!==void 0||r.path!==void 0))&&!n.has(`${t}:${e.id}:${i}`))}function fv(e,t,n,r,i,a,o){let s=dv(t,n,i),c=[];for(let t=0;t<s.length;t++){let{a:i}=s[t],l=`${e.id}-file-${t}`;r.has(l)||(a.push(lv(i,l,n,e.id,o)),c.push({type:`attachment-ref`,attachmentId:l}))}return c}function pv(e,t,n,r,i){let a=new Map,o=[];for(let s of e.conversations){let e=(t.get(s.id)??[]).filter(e=>e.role===`user`),c=0;for(let t of s.messages){if(t.role!==`user`)continue;let l=e[c];if(c++,l===void 0)continue;let u=fv(t,l,s.id,n,r,o,i);u.length>0&&(a.has(s.id)||a.set(s.id,new Map),a.get(s.id).set(t.id,[...t.content,...u]))}}return{updates:a,additionalPendingPromises:o}}function mv(e,t){let n=new Map,r=0,i=new Map;for(let t of e)t.handling===`text-redacted`&&t.rawText!==void 0&&n.set(t.attachmentId,t.rawText),t.present&&i.set(t.attachmentId,ov(r++,t.mimeType,t.handling));for(let n of e)!n.present&&n.missingReason!==void 0&&t.add(n.missingReason);return{rawAttachments:e.map(e=>e.present?{id:e.attachmentId,path:i.get(e.attachmentId),originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!0}:{id:e.attachmentId,path:``,originalName:e.originalName,mimeType:e.mimeType,byteLength:0,sha256:``,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,handling:e.handling,present:!1,missingReason:e.missingReason??`attachment-file-missing`}),textMap:n}}async function hv(e,t,n,r,i){let{rawAttachments:a,textMap:o}=mv(e,n),s,c;try{let e=await tv({...t,attachments:a},o,r,i);s=e.document,c=e.textAttachments}catch(e){throw e instanceof _?e:new _(`attachment-unreadable`)}let l=new Map;for(let t of e){if(l.has(t.attachmentId))throw new _(`schema-invalid`);l.set(t.attachmentId,t)}let u=new Map,d=await Promise.all(s.attachments.map(async e=>{if(!e.present||!e.path)return e;let t=l.get(e.id);if(t===void 0)throw new _(`schema-invalid`);let n=t.handling===`text-redacted`?new TextEncoder().encode(c.get(t.attachmentId)??t.rawText??``):t.rawBytes,r=await rv(n);return u.set(e.path,n),{...e,byteLength:n.length,sha256:r}}));return{redactedDocument:{...s,attachments:d},bundleFiles:u}}async function gv(e){let{document:t,chatMessagesByConversation:n,knownSecrets:r,signal:i}=e,a=e.canonicalImages??new Map,o=e.vfsReader,s=new Set,{pendingPromises:c,mismatchedConvIds:l,processedUiPositions:u}=uv(cv(t),n,a,o);l.size>0&&s.add(`attachment-association-unavailable`);for(let e of t.conversations)e.messages.filter(e=>e.role===`user`).length>(n.get(e.id)??[]).filter(e=>e.role===`user`).length&&s.add(`attachment-association-unavailable`);let d=await Promise.all(c),{updates:f,additionalPendingPromises:p}=pv(t,n,new Set(d.map(e=>e.attachmentId)),u,o),m=await Promise.all(p),h=[...d,...m],g=t;f.size>0&&(g={...t,conversations:t.conversations.map(e=>{let t=f.get(e.id);return t?{...e,messages:e.messages.map(e=>{let n=t.get(e.id);return n?{...e,content:n}:e})}:e})});let{redactedDocument:_,bundleFiles:v}=await hv(h,g,s,r,i),y=[..._.session.completeness.missing.filter(e=>!s.has(e)),...s];return{document:{..._,session:{..._.session,completeness:{status:y.length>0?`partial`:_.session.completeness.status,missing:y}}},bundleFiles:v}}function _v(e){return mh(e)}function vv(e,t){let n=new Set([t]);for(let t=0;t<e.length;t++){let t=!1;for(let r of e)n.has(r.jid)||r.parentJid!==null&&n.has(r.parentJid)&&(n.add(r.jid),t=!0);if(!t)break}return e.filter(e=>n.has(e.jid))}function yv(e,t){return e.map(e=>{let n=t.isProcessing(e.jid)?`1`:`0`,r=t.getAgentMessages(e.jid);if(r===null)return`${e.jid}:${n}:null`;let i=r.length,a=r[i-1],o=a?.role??``,s=a&&`timestamp`in a?a.timestamp:-1,c=a&&`toolCallId`in a?a.toolCallId:``;return`${e.jid}:${n}:${i}:${o}:${s}:${c}`}).join(`,`)}function bv(e,t,n,r){let i=new Map;for(let e of t)i.set(e.id,e);let a=new Map;for(let e of n)a.set(e.id,e);let o=[],s=new Map;for(let t of e){let e=r.getAgentMessages(t.jid)??i.get(t.jid)?.messages??[],n={id:t.jid,kind:rh(t)?`cone`:`scoop`,name:t.name,...t.folder&&!rh(t)?{folder:t.folder}:{},...t.parentJid?{parentConversationId:t.parentJid}:{},...t.originToolCallId?{originToolCallId:t.originToolCallId}:{},messages:e};o.push(n);let c=_v(t),l=a.get(c);l&&s.set(t.jid,l.messages)}return{sources:o,chatMessagesByConversation:s}}async function xv(e,t,n={}){let r=e=>n.rootJid===void 0?e:vv(e,n.rootJid);for(;;){let n=r(e.listScoops());for(;n.some(t=>e.isProcessing(t.jid));)if(t?.aborted||(await e.wait(50,t),t?.aborted))throw new _(`transfer-aborted`);let i=yv(n,e),[a,o]=await Promise.all([e.loadPersistedSessions(),e.loadUiChatSessions()]);if(t?.aborted)throw new _(`transfer-aborted`);let s=r(e.listScoops());if(i===yv(s,e))return bv(s,a,o,e)}}function Sv(e,t){return`${e}-msg-${t.toString().padStart(6,`0`)}`}function Cv(e,t){return{type:`attachment-ref`,attachmentId:`${e}-img-${t}`}}function wv(e,t){if(typeof e==`string`)return e?[{type:`text`,text:e}]:[];let n=[],r=0;for(let i of e)i.type===`text`?i.text&&n.push({type:`text`,text:i.text}):i.type===`image`&&n.push(Cv(t,r++));return n}function Tv(e,t){let n=[],r=new Map,i=0,a=0;for(let o of e)if(o.type===`thinking`)i+=1;else if(o.type===`text`)o.text&&n.push({type:`text`,text:o.text});else if(o.type===`toolCall`)n.push({type:`tool-call`,id:o.id??``,name:o.name??``,input:o.arguments??{}});else if(o.type===`image`){let e=Cv(t,a++);n.push(e),o.data&&o.mimeType&&r.set(e.attachmentId,{data:o.data,mimeType:o.mimeType})}return{blocks:n,excluded:i,images:r}}function Ev(e,t){let n=[],r=new Map,i=0;for(let a of e)if(a.type===`text`)a.text&&n.push({type:`text`,text:a.text});else if(a.type===`image`){let e=Cv(t,i++);n.push(e),a.data&&a.mimeType&&r.set(e.attachmentId,{data:a.data,mimeType:a.mimeType})}return{blocks:n,images:r}}function Dv(e,t,n){let r=Sv(t,n),i=wv(e.content,r);return{message:{id:r,sequence:n,role:`user`,timestamp:new Date(e.timestamp).toISOString(),content:i},excludedReasoningBlocks:0,images:new Map}}function Ov(e,t,n){let r=Sv(t,n),{blocks:i,excluded:a,images:o}=Tv(e.content,r);return{message:{id:r,sequence:n,role:`assistant`,timestamp:new Date(e.timestamp).toISOString(),content:i,model:{provider:e.provider,id:e.model,api:e.api},usage:e.usage,stopReason:e.stopReason,...e.errorMessage?{error:e.errorMessage}:{}},excludedReasoningBlocks:a,images:o}}function kv(e,t,n){let r=Sv(t,n),{blocks:i,images:a}=Ev(e.content,r);return{message:{id:r,sequence:n,role:`tool-result`,timestamp:new Date(e.timestamp).toISOString(),content:i,toolCallId:e.toolCallId,isError:e.isError},excludedReasoningBlocks:0,images:a}}function Av(e,t,n){return e.role===`user`?Dv(e,t,n):e.role===`assistant`?Ov(e,t,n):e.role===`toolResult`?kv(e,t,n):{message:null,excludedReasoningBlocks:0,images:new Map}}function jv(e){let t=[];for(let n of e){if(!n.parentConversationId)continue;let e={sourceConversationId:n.parentConversationId,targetConversationId:n.id};n.originToolCallId&&(e.toolCallId=n.originToolCallId),t.push(e)}return t}function Mv(e){let t=0,n=new Map;return{conversations:e.map(e=>{let r=e.messages.flatMap((r,i)=>{let a=Av(r,e.id,i+1);t+=a.excludedReasoningBlocks;for(let[e,t]of a.images)n.set(e,t);return a.message?[a.message]:[]});return{id:e.id,kind:e.kind,name:e.name,...e.folder?{folder:e.folder}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.createdAt?{createdAt:e.createdAt}:{},...e.updatedAt?{updatedAt:e.updatedAt}:{},messages:r}}),delegations:jv(e),excludedReasoningBlocks:t,canonicalImages:n}}var Nv=`input is invalid type`,Pv=`finalize already called`,Fv=typeof ArrayBuffer<`u`,Iv=function(e){if(typeof e==`string`)return[e,!0];if(Array.isArray(e))return[e,!1];if(Fv&&e){if(e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(ArrayBuffer.isView(e))return[e,!1]}throw Error(Nv)},G=`0123456789abcdef`.split(``),Lv=[-2147483648,8388608,32768,128],Rv=[24,16,8,0],zv=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Bv=[`hex`,`array`,`digest`,`arrayBuffer`],Vv=[],Hv=function(e,t){return function(n){return new Kv(t,!0).update(n)[e]()}},Uv=function(e){var t=Hv(`hex`,e);t.create=function(){return new Kv(e)},t.update=function(e){return t.create().update(e)};for(var n=0;n<Bv.length;++n){var r=Bv[n];t[r]=Hv(r,e)}return t},Wv=function(e,t){return function(n,r){return new qv(n,t,!0).update(r)[e]()}},Gv=function(e){var t=Wv(`hex`,e);t.create=function(t){return new qv(t,e)},t.update=function(e,n){return t.create(e).update(n)};for(var n=0;n<Bv.length;++n){var r=Bv[n];t[r]=Wv(r,e)}return t};function Kv(e,t){t?(Vv[0]=Vv[16]=Vv[1]=Vv[2]=Vv[3]=Vv[4]=Vv[5]=Vv[6]=Vv[7]=Vv[8]=Vv[9]=Vv[10]=Vv[11]=Vv[12]=Vv[13]=Vv[14]=Vv[15]=0,this.blocks=Vv):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Kv.prototype.update=function(e){if(this.finalized)throw Error(Pv);var t=Iv(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<Rv[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<Rv[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<Rv[a++&3],s[a>>>2]|=(128|r>>>12&63)<<Rv[a++&3],s[a>>>2]|=(128|r>>>6&63)<<Rv[a++&3],s[a>>>2]|=(128|r&63)<<Rv[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<Rv[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},Kv.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Lv[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},Kv.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+zv[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=s&i^~s&a,p=o+d+h+zv[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=o&s^~o&i,p=a+d+h+zv[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+zv[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},Kv.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=G[e>>>28&15]+G[e>>>24&15]+G[e>>>20&15]+G[e>>>16&15]+G[e>>>12&15]+G[e>>>8&15]+G[e>>>4&15]+G[e&15]+G[t>>>28&15]+G[t>>>24&15]+G[t>>>20&15]+G[t>>>16&15]+G[t>>>12&15]+G[t>>>8&15]+G[t>>>4&15]+G[t&15]+G[n>>>28&15]+G[n>>>24&15]+G[n>>>20&15]+G[n>>>16&15]+G[n>>>12&15]+G[n>>>8&15]+G[n>>>4&15]+G[n&15]+G[r>>>28&15]+G[r>>>24&15]+G[r>>>20&15]+G[r>>>16&15]+G[r>>>12&15]+G[r>>>8&15]+G[r>>>4&15]+G[r&15]+G[i>>>28&15]+G[i>>>24&15]+G[i>>>20&15]+G[i>>>16&15]+G[i>>>12&15]+G[i>>>8&15]+G[i>>>4&15]+G[i&15]+G[a>>>28&15]+G[a>>>24&15]+G[a>>>20&15]+G[a>>>16&15]+G[a>>>12&15]+G[a>>>8&15]+G[a>>>4&15]+G[a&15]+G[o>>>28&15]+G[o>>>24&15]+G[o>>>20&15]+G[o>>>16&15]+G[o>>>12&15]+G[o>>>8&15]+G[o>>>4&15]+G[o&15];return this.is224||(c+=G[s>>>28&15]+G[s>>>24&15]+G[s>>>20&15]+G[s>>>16&15]+G[s>>>12&15]+G[s>>>8&15]+G[s>>>4&15]+G[s&15]),c},Kv.prototype.toString=Kv.prototype.hex,Kv.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},Kv.prototype.array=Kv.prototype.digest,Kv.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};function qv(e,t,n){var r,i=Iv(e);if(e=i[0],i[1]){var a=[],o=e.length,s=0,c;for(r=0;r<o;++r)c=e.charCodeAt(r),c<128?a[s++]=c:c<2048?(a[s++]=192|c>>>6,a[s++]=128|c&63):c<55296||c>=57344?(a[s++]=224|c>>>12,a[s++]=128|c>>>6&63,a[s++]=128|c&63):(c=65536+((c&1023)<<10|e.charCodeAt(++r)&1023),a[s++]=240|c>>>18,a[s++]=128|c>>>12&63,a[s++]=128|c>>>6&63,a[s++]=128|c&63);e=a}e.length>64&&(e=new Kv(t,!0).update(e).array());var l=[],u=[];for(r=0;r<64;++r){var d=e[r]||0;l[r]=92^d,u[r]=54^d}Kv.call(this,t,n),this.update(u),this.oKeyPad=l,this.inner=!0,this.sharedMemory=n}qv.prototype=new Kv,qv.prototype.finalize=function(){if(Kv.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();Kv.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(e),Kv.prototype.finalize.call(this)}};var Jv=Uv(),Yv=Uv(!0);Jv.sha256=Jv,Jv.sha224=Yv,Jv.hmac=Gv(),Yv.hmac=Gv(!0);const Xv=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})();function Zv(e){let t=-1>>>0;for(let n=0;n<e.length;n++)t=t>>>8^Xv[(t^e[n])&255];return~t>>>0}const Qv=new TextEncoder;function $v(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255}function ey(e,t,n){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255}function ty(e,t,n){let r=new Uint8Array(30+e.length);return r[0]=80,r[1]=75,r[2]=3,r[3]=4,$v(r,4,20),$v(r,6,2048),$v(r,8,0),$v(r,10,0),$v(r,12,0),ey(r,14,n),ey(r,18,t),ey(r,22,t),$v(r,26,e.length),$v(r,28,0),r.set(e,30),r}function ny(e,t,n,r){let i=new Uint8Array(46+e.length);return i[0]=80,i[1]=75,i[2]=1,i[3]=2,$v(i,4,20),$v(i,6,20),$v(i,8,2048),$v(i,10,0),$v(i,12,0),$v(i,14,0),ey(i,16,n),ey(i,20,t),ey(i,24,t),$v(i,28,e.length),$v(i,30,0),$v(i,32,0),$v(i,34,0),$v(i,36,0),ey(i,38,0),ey(i,42,r),i.set(e,46),i}function ry(e,t,n){let r=new Uint8Array(22);return r[0]=80,r[1]=75,r[2]=5,r[3]=6,$v(r,4,0),$v(r,6,0),$v(r,8,e),$v(r,10,e),ey(r,12,t),ey(r,16,n),$v(r,20,0),r}function iy(e){if(!e||e.startsWith(`/`)||e.includes(`\0`)||e.includes(`\\`))return!1;for(let t of e.split(`/`))if(t===``||t===`.`||t===`..`)return!1;return!0}function ay(e){let t=e.export.generatedAt.slice(0,10),n=e.export.id.slice(0,8);return`slicc-${t}-${e.session.title.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,40)||`transcript`}-${n}.zip`}async function*oy(e,t,n,r,i){if(n?.aborted)throw i(new _(`transfer-aborted`)),new _(`transfer-aborted`);let a=()=>i(new _(`transfer-aborted`));n?.addEventListener(`abort`,a,{once:!0});let o=Jv.create(),s=0,c=0,l=[],u=!1;function*d(e){o.update(e),s+=e.byteLength,c+=e.byteLength,yield e}try{let i=new TextEncoder().encode(JSON.stringify(e,null,2)),a=Qv.encode(`transcript.json`),f=Zv(i),p=ty(a,i.length,f);if(l.push({nameBytes:a,size:i.length,crc:f,localOffset:c}),n?.aborted||(yield*d(p),n?.aborted))throw new _(`transfer-aborted`);yield*d(i);for(let[e,r]of t){if(n?.aborted)throw new _(`transfer-aborted`);let t=Qv.encode(e),i=Zv(r),a=ty(t,r.length,i);if(l.push({nameBytes:t,size:r.length,crc:i,localOffset:c}),yield*d(a),n?.aborted)throw new _(`transfer-aborted`);yield*d(r)}let m=c;for(let e of l){if(n?.aborted)throw new _(`transfer-aborted`);yield*d(ny(e.nameBytes,e.size,e.crc,e.localOffset))}if(n?.aborted)throw new _(`transfer-aborted`);yield*d(ry(l.length,c-m,m)),u=!0,r({byteLength:s,sha256:o.hex()})}catch(e){throw u=!0,i(e),e}finally{n?.removeEventListener(`abort`,a),u||(u=!0,i(new _(`transfer-aborted`)))}}function sy(e,t,n){for(let e of t.keys())if(!iy(e))throw new _(`schema-invalid`);if(t.size+1>65535)throw new _(`schema-invalid`);for(let e of t.values())if(e.byteLength>4294967295)throw new _(`schema-invalid`);let r,i,a=new Promise((e,t)=>{r=e,i=t});return{filename:ay(e),chunks:oy(e,t,n,r,i),completion:a}}function cy(e,t,n,r,i,a={}){return{schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:i},format:g},session:{id:e,title:t,state:n,completeness:{status:`complete`,missing:[]},...a},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:r.excludedReasoningBlocks,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:r.conversations,delegations:r.delegations,attachments:[]}}function ly(e,t){let n=[],r=1;for(let i of e){if(i.role!==`user`&&i.role!==`assistant`)continue;let e=`${t}-msg-${String(r).padStart(6,`0`)}`;n.push({id:e,sequence:r++,role:i.role,timestamp:new Date(i.timestamp||0).toISOString(),content:i.content?[{type:`text`,text:i.content}]:[]})}return n}function uy(e){if(!h(e).ok)throw new _(`schema-invalid`)}function dy(e,t,n){let r=new Map;for(let i of e)if(!(!i.present||!i.path))if(i.handling===`text-redacted`){let e=t.get(i.id);e!==void 0&&r.set(i.path,new TextEncoder().encode(e))}else{let e=n.get(i.path);e&&r.set(i.path,e)}return r}async function fy(e,t){return Promise.all(e.map(async e=>{if(!e.present||!e.path||e.handling!==`text-redacted`)return e;let n=t.get(e.path);if(!n)return e;let r=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=await crypto.subtle.digest(`SHA-256`,r),a=Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,`0`)).join(``);return{...e,byteLength:n.length,sha256:a}}))}function py(e){let t=e.match(/^---\n([\s\S]*?)\n---\n/);if(!t)return{};let n=t[1],r={},i=n.match(/^createdAt:\s*(\d+)\s*$/m),a=n.match(/^updatedAt:\s*(\d+)\s*$/m);return i&&(r.createdAt=new Date(Number(i[1])).toISOString()),a&&(r.updatedAt=new Date(Number(a[1])).toISOString()),r}var my=class{deps;constructor(e){this.deps=e}async export(e,t={}){let{signal:n,onProgress:r}=t,i;return i=e.kind===`active`?await this.buildActiveSnapshot(n,r):await this.buildFrozenSnapshot(e.sessionId,n,r),uy(i.document),r?.({phase:`packaging`}),sy(i.document,i.bundleFiles,n)}async captureFrozen(e,t){let n=await xv(this.deps.collection,t,{...e.rootJid?{rootJid:e.rootJid}:{}});if(e.rootJid&&n.sources.length===0)return;let r=Mv(n.sources),{document:i,bundleFiles:a}=await gv({document:cy(e.sessionId,e.title,`frozen`,r,this.deps.version,{frozenAt:e.frozenAt,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}),chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:t});uy(i),await this.deps.snapshotStore.write(e.sessionId,{document:i,attachments:a})}async buildActiveSnapshot(e,t){t?.({phase:`waiting-for-conversations`}),t?.({phase:`collecting`});let n=await xv(this.deps.collection,e),r=Mv(n.sources),{id:i,title:a}=this.deps.getActiveSessionInfo(),o=cy(i,a,`active`,r,this.deps.version);return t?.({phase:`redacting`}),gv({document:o,chatMessagesByConversation:n.chatMessagesByConversation,knownSecrets:this.deps.knownSecrets,canonicalImages:r.canonicalImages,vfsReader:e=>this.readBinaryFromVfs(e),signal:e})}async buildFrozenSnapshot(e,t,n){let r=await this.deps.snapshotStore.read(e);return r?(n?.({phase:`redacting`}),this.reredactStoredSnapshot(r,t)):this.buildLegacyPartial(e,t,n)}async reredactStoredSnapshot(e,t){let n=new Map;for(let t of e.document.attachments){if(t.handling!==`text-redacted`||!t.present||!t.path)continue;let r=e.attachments.get(t.path);r&&n.set(t.id,new TextDecoder().decode(r))}let r,i;try{let a=await tv(e.document,n,this.deps.knownSecrets,t);r=a.document,i=a.textAttachments}catch{throw new _(`redaction-unavailable`)}let a=dy(r.attachments,i,e.attachments),o=await fy(r.attachments,a);return{document:{...r,attachments:o},bundleFiles:a}}async buildLegacyPartial(e,t,n){let r=(await Uee(this.deps.vfs)).find(t=>t.sessionId===e||!t.sessionId&&t.filename===e);if(!r)throw new _(`session-not-found`);let i;try{let e=await this.deps.vfs.readFile(`/sessions/${r.filename}`,{encoding:`utf-8`});i=typeof e==`string`?e:new TextDecoder().decode(e)}catch{throw new _(`session-not-found`)}let{title:a,messages:o}=Hee(i),s=`legacy-cone`,c=ly(o,s),l=py(i),u={schemaVersion:1,export:{id:crypto.randomUUID(),generatedAt:new Date().toISOString(),producer:{application:`slicc`,version:this.deps.version},format:g},session:{id:e,title:a,state:`frozen`,...r.frozenAt?{frozenAt:r.frozenAt}:{},...l,completeness:{status:`partial`,missing:[`complete-snapshot-unavailable`,`canonical-agent-history-unavailable`]}},privacy:{reasoningExcluded:!0,excludedReasoningBlocks:0,binaryAttachments:`included-unchanged`,redactionCounts:{},redactions:[]},conversations:[{id:s,kind:`cone`,name:a,messages:c}],delegations:[],attachments:[]},d=new Map([[s,o]]);return n?.({phase:`redacting`}),gv({document:u,chatMessagesByConversation:d,knownSecrets:this.deps.knownSecrets,vfsReader:e=>this.readBinaryFromVfs(e),signal:t})}async readBinaryFromVfs(e){let t=await this.deps.vfs.readFile(e,{encoding:`binary`});if(!(t instanceof Uint8Array))throw new _(`attachment-unreadable`);return t}};const hy=`/sessions/data`,gy=`document.json`;async function _y(e){let t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function vy(e){if(e.length===0||/[/\\\x00]/.test(e)||e===`..`||e===`.`||e.includes(`..`)||!/^[a-zA-Z0-9._-]+$/.test(e))throw new _(`session-not-found`)}function yy(e){return`${hy}/${e}`}function by(e){return`${hy}/.tmp-${e}`}async function xy(e,t){try{await e.mkdir(t,{recursive:!0})}catch{}}async function Sy(e,t){let n;try{n=await e.readDir(t)}catch{return}for(let r of n){let n=`${t}/${r.name}`;r.type===`directory`&&await Sy(e,n);try{await e.rm(n)}catch{}}try{await e.rm(t)}catch{}}async function Cy(e,t,n){await xy(e,n);let r=await e.readDir(t);for(let i of r){let r=`${t}/${i.name}`,a=`${n}/${i.name}`;if(i.type===`directory`)await Cy(e,r,a);else{let t=await e.readFile(r,{encoding:`binary`});await e.writeFile(a,t)}}}async function wy(e,t,n){vy(t);let r=by(t),i=yy(t),a=new Map(n.document.attachments.filter(e=>e.present&&e.path).map(e=>[e.path,e]));for(let[e]of n.attachments)if(!a.has(e))throw new _(`schema-invalid`);await Sy(e,i),await xy(e,r);try{let t=[...n.document.attachments];for(let[e,r]of n.attachments){let n=await _y(r),i=a.get(e);if(i!==void 0){let e=t.indexOf(i);e!==-1&&(t[e]={...i,sha256:n,byteLength:r.length})}}let o={...n.document,attachments:t},s=JSON.stringify(o,null,2);if(await e.writeFile(`${r}/${gy}`,s),n.attachments.size>0)for(let[t,i]of n.attachments){let n=`${r}/${t}`,a=t.lastIndexOf(`/`);a!==-1&&await xy(e,`${r}/${t.slice(0,a)}`),await e.writeFile(n,i)}await e.flush(),await Cy(e,r,i),await e.flush()}catch(t){throw await Sy(e,r),t}await Sy(e,r)}async function Ty(e,t){vy(t);let n=yy(t),r=`${n}/${gy}`,i;try{let t=await e.readFile(r,{encoding:`utf-8`});i=typeof t==`string`?t:new TextDecoder().decode(t)}catch{throw new _(`session-not-found`)}let a;try{a=JSON.parse(i)}catch{throw new _(`schema-invalid`)}if(!h(a).ok)throw new _(`schema-invalid`);let o=new Map;for(let t of a.attachments){if(!t.present||!t.path)continue;let r=`${n}/${t.path}`,i;try{let t=await e.readFile(r,{encoding:`binary`});i=t instanceof Uint8Array?t:new TextEncoder().encode(t)}catch{throw new _(`transfer-corrupt`)}if(await _y(i)!==t.sha256)throw new _(`transfer-corrupt`);o.set(t.path,i)}return{document:a,attachments:o}}function Ey(){throw new _(`redaction-unavailable`)}function Dy(e,t){return(typeof e!=`object`||!e||!Array.isArray(e.texts)||e.texts.length!==t)&&Ey(),e.texts}function Oy(){return{async redact(e){let t;try{t=await fetch(At(`/api/secrets/redact-export`),{method:`POST`,headers:jt({"content-type":`application/json`}),body:JSON.stringify({texts:e})})}catch{Ey()}t.ok||Ey();let n;try{n=await t.json()}catch{Ey()}return Dy(n,e.length)}}}function ky(){return{async redact(e){let t;try{t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.redact-export`,texts:e},e=>{chrome.runtime.lastError,t(e??null)})})}catch{Ey()}return typeof t==`object`&&t&&`error`in t&&Ey(),Dy(t,e.length)}}}function Ay(){return{async redact(e){let t;try{t=await ot(`secrets.redact-export`,{texts:e})}catch{Ey()}return t??Ey(),typeof t==`object`&&`error`in t&&Ey(),Dy(t,e.length)}}}function jy(){return{async redact(e){Ey()}}}function My(){let e=Xe();return e===`connect`?jy():e===`extension-direct`?ky():e===`extension-delegate`?Ay():Oy()}const Ny=r(`cone-memory-budget`),Py=Mh.memoryPath,Fy=/^## Auto-extracted/m;function Iy(e){return Math.round(4e3+2e3*Math.log2((Number.isFinite(e)&&e>=0?e:0)+2))}function Ly(e){let t=Fy.exec(e);if(!t)return{header:e,autoExtracted:``};let n=t.index;return{header:e.slice(0,n),autoExtracted:e.slice(n)}}async function Ry(e){try{let t=await e.readFile(`/sessions/index.json`,{encoding:`utf-8`}),n=typeof t==`string`?t:new TextDecoder().decode(t),r=JSON.parse(n);return Array.isArray(r)?r.length:0}catch{return 0}}async function zy(e){let{header:t,autoExtracted:n}=Ly(e.currentContent);if(!n.trim())return e.currentContent;let r=`You are a memory consolidation assistant. You are given a markdown file's "auto-extracted" section — a list of memory bullets accumulated across sessions of an AI coding assistant. Your job is to rewrite that section as a tighter, deduplicated set of durable memories that fits well within ${e.budget} characters.
|
|
983
983
|
|
|
984
984
|
<auto-extracted>
|
|
985
985
|
${n}
|
|
@@ -994,7 +994,7 @@ Rules:
|
|
|
994
994
|
`).trim();if(!o)throw Error(`Restructure call returned empty content`);return`${t}${t.length===0||t.endsWith(`
|
|
995
995
|
`)?``:`
|
|
996
996
|
`}${o}\n`}async function By(e){if(!e.model||!e.apiKey)return{restructured:!1,reason:`no-llm`};let t=e.memoryPath??Py,n=``;try{let r=await e.vfs.readFile(t,{encoding:`utf-8`});n=typeof r==`string`?r:new TextDecoder().decode(r)}catch{return{restructured:!1,reason:`missing-file`}}let r=await Ry(e.vfs),i=Iy(r),a=i*1.25;if(n.length<=a)return{restructured:!1,reason:`under-threshold`};Ny.info(`Cone memory over threshold — restructuring`,{size:n.length,budget:i,threshold:a,sessionCount:r});try{let r=await zy({currentContent:n,budget:i,model:e.model,apiKey:e.apiKey,headers:e.headers,signal:e.signal});return await e.vfs.writeFile(t,r),Ny.info(`Cone memory restructured`,{before:n.length,after:r.length}),{restructured:!0}}catch(e){return Ny.warn(`Cone memory restructure failed — leaving appended content in place`,{error:e instanceof Error?e.message:String(e)}),{restructured:!1,reason:`error`}}}const Vy=`focus`,Hy={type:`leaf`,surfaceId:`chat`};function Uy(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}const Wy={focus:{name:`focus`,tree:Uy({left:Hy},{left:3,middle:1})}};function Gy(e){return Wy[e]??null}const Ky=r(`skills`),qy=Object.assign({"/packages/vfs-root/AGENTS.md":()=>import(`./CLAUDE-4LHXSyPA.js`).then(e=>e.default),"/packages/vfs-root/CLAUDE.md":()=>import(`./CLAUDE-4LHXSyPA.js`).then(e=>e.default),"/packages/vfs-root/shared/CLAUDE.md":()=>import(`./CLAUDE-Bio4HPGK.js`).then(e=>e.default),"/packages/vfs-root/shared/MEMORY.md":()=>import(`./MEMORY-6FXnIBfJ.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/connect-llm.shtml":()=>import(`./connect-llm-FevTa-aV.js`).then(e=>e.default),"/packages/vfs-root/shared/sprinkles/welcome/welcome.shtml":()=>import(`./welcome-CyCMJDqG.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/automation/SKILL.md":()=>import(`./SKILL-DLXzwsY4.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/biome/SKILL.md":()=>import(`./SKILL-BcELX5TL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/cherry/SKILL.md":()=>import(`./SKILL-Ckg2XbSL.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/delegation/SKILL.md":()=>import(`./SKILL-BKUxKc7f.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/SKILL.md":()=>import(`./SKILL-FnBxPcDX.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dips/patterns.md":()=>import(`./patterns-ChiGbijt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/dns/SKILL.md":()=>import(`./SKILL-BKyxMoME.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/handoff/SKILL.md":()=>import(`./SKILL-oOIS8LAm.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/image-processing/SKILL.md":()=>import(`./SKILL-Bd5ykLEh.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/meminfo/SKILL.md":()=>import(`./SKILL-DXIigmDy.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/mount/SKILL.md":()=>import(`./SKILL-D4YtbN6n.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/package-execution/SKILL.md":()=>import(`./SKILL-CNdAIhbb.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/playwright-cli/SKILL.md":()=>import(`./SKILL-DhKtVqb-.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/SKILL.md":()=>import(`./SKILL-HEHb9hIB.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/skill-authoring/jsh-runtime-extensions.md":()=>import(`./jsh-runtime-extensions-DpVq60Gw.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/SKILL.md":()=>import(`./SKILL-Ch-cOl61.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/icon-example.md":()=>import(`./icon-example-LUkiEXyS.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/sprinkles/style-guide.md":()=>import(`./style-guide-Bgzsk7bf.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/ssh/SKILL.md":()=>import(`./SKILL-DJ815vTN.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/theme/SKILL.md":()=>import(`./SKILL-DfSluXpV.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/transcript-export/SKILL.md":()=>import(`./SKILL-CkfptFag.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/upgrade/SKILL.md":()=>import(`./SKILL-CcMg6eqt.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/v86/SKILL.md":()=>import(`./SKILL-DFKKFkzD.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/welcome/SKILL.md":()=>import(`./SKILL-D40-t9w0.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/workflows/SKILL.md":()=>import(`./SKILL-Bt-RhG0L.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/SKILL.md":()=>import(`./SKILL-CED8RXQP.js`).then(e=>e.default),"/packages/vfs-root/workspace/skills/x-search/x_search.jsh":()=>import(`./x_search-C-5p00-C.js`).then(e=>e.default)}),Jy=Object.assign({"/packages/vfs-root/shared/sounds/chime.mp3":()=>import(`./chime-CPc6qSh5.js`).then(e=>e.default)});function Yy(e){let t=e.split(`,`)[1],n=atob(t),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}const Xy={};function Zy(){let e={};for(let[t,n]of Object.entries(qy))e[t]=n;for(let[t,n]of Object.entries(Jy))e[t]=async()=>Yy(await n());for(let[t,n]of Object.entries(Xy)){let r=t.replace(`/packages/dev-tools/vfs-dev-skills/`,`/packages/vfs-root/workspace/skills/`);e[r]=()=>Promise.resolve(n)}return e}function Qy(e){let t=new Map;for(let n of e){if(t.has(n.metadata.name)){Ky.debug(`Skipped shadowed runtime skill`,{name:n.metadata.name,path:n.path,winnerPath:t.get(n.metadata.name)?.path});continue}t.set(n.metadata.name,n)}return Array.from(t.values())}function $y(e){let t=e.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!t)return{metadata:{},body:e};let[,n,r]=t,i={};for(let e of n.split(`
|
|
997
|
-
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break;case`layout`:i.layout=a;break;case`theme`:i.theme=a}}return{metadata:i,body:r}}async function eb(e,t){let n=await tb(e,t),r=await nb(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Qy([...i,...r,...a]);return Ky.info(`Skills loaded`,{count:o.length,dir:t}),o}async function tb(e,t){let n=await
|
|
997
|
+
`)){let t=e.match(/^(\w[\w-]*):\s*(.*)$/);if(!t)continue;let[,n,r]=t,a=r.trim();switch(n){case`name`:i.name=a;break;case`description`:i.description=a;break;case`allowed-tools`:i.allowedTools=a.split(`,`).map(e=>e.trim());break;case`layout`:i.layout=a;break;case`theme`:i.theme=a}}return{metadata:i,body:r}}async function eb(e,t){let n=await tb(e,t),r=await nb(e,t),i=n.filter(e=>e.source===`native`),a=n.filter(e=>e.source!==`native`),o=Qy([...i,...r,...a]);return Ky.info(`Skills loaded`,{count:o.length,dir:t}),o}async function tb(e,t){let n=await Pee(e,t),r=[];for(let t of n)if(t.skillFilePath)try{let{metadata:n,body:i}=$y(await e.readTextFile(t.skillFilePath)),a=n.name||t.name;r.push({metadata:{name:a,description:n.description||t.description||``,allowedTools:n.allowedTools},content:i,path:t.skillFilePath,source:t.source}),Ky.debug(`Loaded discovered skill`,{name:a,path:t.skillFilePath,source:t.source})}catch{Ky.debug(`Failed to load discovered skill`,{name:t.name,path:t.skillFilePath})}return r}async function nb(e,t){let n=[];try{let r=await e.readDir(t);for(let i of r)if(i.type===`file`&&i.name.endsWith(`.md`)){let r=`${t}/${i.name}`;try{let t=await e.readFile(r,{encoding:`utf-8`}),{metadata:a,body:o}=$y(typeof t==`string`?t:new TextDecoder().decode(t)),s=a.name||i.name.replace(`.md`,``);n.push({metadata:{name:s,description:a.description||``,allowedTools:a.allowedTools},content:o,path:r}),Ky.debug(`Loaded standalone skill`,{name:s,path:r})}catch{}}}catch{Ky.debug(`Standalone skills directory not found`,{dir:t})}return n}function rb(e){return e.length===0?``:`
|
|
998
998
|
---
|
|
999
999
|
AVAILABLE SKILLS
|
|
1000
1000
|
|
|
@@ -1015,8 +1015,8 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
|
|
|
1015
1015
|
`)+`
|
|
1016
1016
|
`;await e.writeFile(`/workspace/CLAUDE.md`,l);let u=a.length;for(;u>0&&a[u-1]===``;)u--;let d=u===0?``:a.slice(0,u).join(`
|
|
1017
1017
|
`)+`
|
|
1018
|
-
`;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),sb.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function ub(e){if(e.kind===`local`)return`mount ${
|
|
1019
|
-
`)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await qre(r,t.hostname);return this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:i,message:i?`Dismissed — ${t.hostname} was added to /etc/llmstxtignore.`:`Dismissed — ${t.hostname} is already ignored.`}}async runUpgrade(e){let t=this.deps.getConeShell();if(!t)return`upgrade could not run: no cone shell available.`;let n=`upgrade apply --from=${
|
|
1018
|
+
`;await e.writeFile(`/shared/CLAUDE.md`,d),this.globalMemoryCache=d,await this.writeMigrationSentinel(t),sb.info(`Migrated legacy cone memory from /shared/CLAUDE.md to /workspace/CLAUDE.md`,{blockCount:i.length})}async writeMigrationSentinel(e){let t=this.deps.getSharedFs();if(t){try{await t.mkdir(`/workspace`,{recursive:!0})}catch{}await t.writeFile(e,`Migration completed at ${new Date().toISOString()}\n`)}}};function ub(e){if(e.kind===`local`)return`mount ${ln(e.path)}`;let t=e.profile==="default"?``:` --profile ${ln(e.profile)}`;return`mount --source ${ln(e.source)}${t} ${ln(e.path)}`}function db(){return`lick-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}var fb=class{deps;entries=new Map;constructor(e){this.deps=e}hasHandoff(e){return this.entries.get(e)?.kind===`navigate-handoff`}registerNavigate(e){let t=db(),n=e.body??{},r=typeof n.verb==`string`?n.verb:void 0,i=typeof n.target==`string`?n.target:void 0;return r===`upskill`&&i?this.entries.set(t,{kind:`navigate-upskill`,target:i,branch:typeof n.branch==`string`?n.branch:void 0,path:typeof n.path==`string`?n.path:void 0}):r===`handoff`&&this.entries.set(t,{kind:`navigate-handoff`}),t}registerSessionReload(e){let t=db(),n=e.body??{},r=Array.isArray(n.mounts)?n.mounts:[];return n.reason===`mount-recovery`?r.length>0&&this.entries.set(t,{kind:`session-reload-mount`,mounts:r}):this.entries.set(t,{kind:`session-reload-plain`}),t}registerUpgrade(e){let t=db(),n=e.upgradeFromVersion??`unknown`,r=e.upgradeToVersion??`unknown`;return this.entries.set(t,{kind:`upgrade`,from:n,to:r}),t}registerDiscovery(e){if(e.discoveryKind!==`llms-txt`)return null;let t=u_(e.discoveryOrigin,e.discoveryUrl);if(!t)return null;let n=db();return this.entries.set(n,{kind:`discovery-llms-txt`,hostname:t}),n}async resolve(e,t){let n=this.entries.get(e);if(!n)return null;switch(n.kind){case`navigate-upskill`:return this.resolveUpskill(e,n,t);case`session-reload-mount`:return this.resolveMountRecovery(e,n,t);case`session-reload-plain`:return this.resolveSessionReloadPlain(e,t);case`upgrade`:return this.resolveUpgrade(e,n,t);case`discovery-llms-txt`:return this.resolveDiscovery(e,n,t);case`navigate-handoff`:return null}}async resolveHandoffByHuman(e,t){return this.hasHandoff(e)?(this.entries.delete(e),await this.deps.persistLickDecision(e,t?`allow`:`deny`),!0):!1}async resolveUpskill(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runUpskillInstall(t)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runUpskillInstall(e){let t=this.deps.getConeShell();if(!t)return`upskill could not run: no cone shell available.`;let n=e=>`'${e.replace(/'/g,`'\\''`)}'`,r=[`upskill`];e.branch&&r.push(`--branch`,n(e.branch)),e.path&&r.push(`--path`,n(e.path)),r.push(n(e.target));try{let e=await t.executeCommand(r.join(` `)),n=`${e.stdout}${e.stderr}`.trim();return n.length>0?n:`upskill exited ${e.exitCode}.`}catch(e){return`upskill failed: ${e instanceof Error?e.message:String(e)}`}}async resolveMountRecovery(e,t,n){this.entries.delete(e);let r;return n.decision!==`deny`&&(r=await this.runMountRecovery(t.mounts)),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async runMountRecovery(e){let t=this.deps.getConeShell();if(!t)return`mount recovery could not run: no cone shell available.`;let n=[];for(let r of e){let e=ub(r);try{let r=await t.executeCommand(e),i=`${r.stdout}${r.stderr}`.trim();n.push(i.length>0?i:`${e} exited ${r.exitCode}.`)}catch(t){n.push(`${e} failed: ${t instanceof Error?t.message:String(t)}`)}}return n.join(`
|
|
1019
|
+
`)}async resolveSessionReloadPlain(e,t){return t.decision===`deny`?(this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:!1,message:`Session-reload notice acknowledged.`}):{settled:!0,persisted:!1,message:`Nothing to confirm — the reload already completed. Use lick_dismiss to acknowledge and clear this notice.`}}async resolveUpgrade(e,t,n){this.entries.delete(e);let r;return r=n.decision===`deny`?`Upgrade dismissed — workspace files were left unchanged.`:await this.runUpgrade(t),await this.deps.persistLickDecision(e,n.decision),{settled:!0,persisted:!1,message:r}}async resolveDiscovery(e,t,n){if(n.decision!==`deny`)return{settled:!0,persisted:!1,message:`Nothing to confirm — use lick_dismiss to ignore this llms.txt host.`};let r=this.deps.getConeFs();if(!r)throw Error(`llms.txt dismissal could not persist: cone filesystem unavailable.`);let i=await qre(r,t.hostname);return this.entries.delete(e),await this.deps.persistLickDecision(e,`deny`),{settled:!0,persisted:i,message:i?`Dismissed — ${t.hostname} was added to /etc/llmstxtignore.`:`Dismissed — ${t.hostname} is already ignored.`}}async runUpgrade(e){let t=this.deps.getConeShell();if(!t)return`upgrade could not run: no cone shell available.`;let n=`upgrade apply --from=${ln(e.from)} --to=${ln(e.to)}`;try{let e=await t.executeCommand(n),r=`${e.stdout}${e.stderr}`.trim();return r.length>0?r:`upgrade exited ${e.exitCode}.`}catch(e){return`upgrade failed: ${e instanceof Error?e.message:String(e)}`}}},pb=`# /etc/models — which models a scoop may be spawned with
|
|
1020
1020
|
#
|
|
1021
1021
|
# \`agent --model\` and \`scoop_scoop\` accept a \`provider:model\` id, so a scoop can
|
|
1022
1022
|
# run on a provider OTHER than the selected one. That moves spend onto another
|
|
@@ -1049,17 +1049,17 @@ ${e.map(e=>{let t=e.metadata.allowedTools?` Allowed tools: ${e.metadata.allowed
|
|
|
1049
1049
|
# openrouter:*
|
|
1050
1050
|
# -openrouter:openai/o3-pro
|
|
1051
1051
|
# -adobe:claude-opus-5
|
|
1052
|
-
`;const mb=r(`model-policy-file`);var hb=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(R,pb),mb.info(`Seeded default /etc/models policy`))}catch(e){mb.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(R,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);be(Ae(t))}catch(e){be(De()),mb.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function gb(){try{let e=E();if(!e||!Ke(e))return;let t=de().id;return t?{provider:e,id:t}:void 0}catch{return}}async function _b(e,t,n={}){if(!t)return e();let r=n.intervalMs??5e3,i=n.maxBeats??24;t(`shared-fs-mount:start`);let a=0,o=setInterval(()=>{if(a+=1,a>i){clearInterval(o);return}t(`shared-fs-mount:${a}`)},r);try{return await e()}finally{clearInterval(o)}}const vb=r(`scheduler`);var yb=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.checkTasks(),6e4),this.checkTasks(),vb.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,vb.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await
|
|
1052
|
+
`;const mb=r(`model-policy-file`);var hb=class{fs;watcher;unwatch=null;constructor(e,t=null){this.fs=e,this.watcher=t}async init(){await this.ensureDefault(),await this.reload(),this.unwatch=this.watcher?.watch(`/etc`,e=>e===`/etc/models`,()=>void this.reload())??null}dispose(){this.unwatch?.(),this.unwatch=null}async ensureDefault(){try{await this.fs.mkdir(`/etc`,{recursive:!0}),await this.fs.exists(`/etc/models`)||(await this.fs.writeFile(R,pb),mb.info(`Seeded default /etc/models policy`))}catch(e){mb.warn(`Failed to seed default model policy`,{error:e instanceof Error?e.message:String(e)})}}async reload(){try{let e=await this.fs.readFile(R,{encoding:`utf-8`}),t=typeof e==`string`?e:new TextDecoder().decode(e);be(Ae(t))}catch(e){be(De()),mb.warn(`Failed to read model policy; falling back to own-catalogue-only`,{error:e instanceof Error?e.message:String(e)})}}};function gb(){try{let e=E();if(!e||!Ke(e))return;let t=de().id;return t?{provider:e,id:t}:void 0}catch{return}}async function _b(e,t,n={}){if(!t)return e();let r=n.intervalMs??5e3,i=n.maxBeats??24;t(`shared-fs-mount:start`);let a=0,o=setInterval(()=>{if(a+=1,a>i){clearInterval(o);return}t(`shared-fs-mount:${a}`)},r);try{return await e()}finally{clearInterval(o)}}const vb=r(`scheduler`);var yb=class{callbacks;pollInterval=null;running=!1;constructor(e){this.callbacks=e}start(){this.running||(this.running=!0,this.pollInterval=setInterval(()=>this.checkTasks(),6e4),this.checkTasks(),vb.info(`Scheduler started`))}stop(){this.pollInterval&&=(clearInterval(this.pollInterval),null),this.running=!1,vb.info(`Scheduler stopped`)}async createTask(e,t,n,r){let i={id:`task-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,groupFolder:e,prompt:t,scheduleType:n,scheduleValue:r,status:`active`,nextRun:this.calculateNextRun(n,r),lastRun:null,createdAt:new Date().toISOString()};return await Mn(i),vb.info(`Task created`,{id:i.id,groupFolder:e,scheduleType:n}),i}async updateTask(e,t){let n=await yn(e);if(!n)return null;let r={...n,...t};return(t.scheduleType||t.scheduleValue)&&(r.nextRun=this.calculateNextRun(r.scheduleType,r.scheduleValue)),await Mn(r),vb.info(`Task updated`,{id:e,updates:Object.keys(t)}),r}async pauseTask(e){return await this.updateTask(e,{status:`paused`})!==null}async resumeTask(e){return await yn(e)?(await this.updateTask(e,{status:`active`}),!0):!1}async deleteTask(e){return await yn(e)?(await kn(e),vb.info(`Task deleted`,{id:e}),!0):!1}async getTasksByScoop(e){return(await Sn()).filter(t=>t.groupFolder===e)}async getAllTasks(){return Sn()}async checkTasks(){let e=await Sn(),t=new Date;for(let n of e)n.status===`active`&&n.nextRun&&(new Date(n.nextRun)>t||await this.runTask(n))}async runTask(e){let t=this.callbacks.getScoop(e.groupFolder);if(!t){vb.warn(`Task scoop not found`,{taskId:e.id,groupFolder:e.groupFolder});return}vb.info(`Running task`,{id:e.id,groupFolder:e.groupFolder});try{let n=new Date().toISOString(),r=this.calculateNextRun(e.scheduleType,e.scheduleValue),i=e.scheduleType===`once`?`completed`:e.status;await Mn({...e,lastRun:n,nextRun:r,status:i}),await this.callbacks.onTaskRun(e,t),vb.info(`Task completed`,{id:e.id})}catch(t){vb.error(`Task execution failed`,{id:e.id,error:t instanceof Error?t.message:String(t)})}}calculateNextRun(e,t){let n=new Date;switch(e){case`cron`:return vee(t,n)?.toISOString()??null;case`interval`:{let e=parseInt(t,10);return isNaN(e)||e<=0?null:new Date(n.getTime()+e).toISOString()}case`once`:return new Date(t)>n?t:null;default:return null}}};const bb=r(`scoop-approval-router`);var xb=class{deps;registry;constructor(e){this.deps=e,this.registry=new A_({onAutoSettle:(e,t)=>this.handleAutoSettle(e,t)})}handleAutoSettle(e,t){bb.info(`Sudo request auto-settled fail-closed; retiring lick card`,{id:e,reason:t}),this.persistLickDecision(e,`deny`).catch(n=>{bb.warn(`Failed to persist auto-settled lick decision`,{id:e,reason:t,error:n instanceof Error?n.message:String(n)})})}getConeSudoBroker(e){return O_(e,this)}listPendingSudoRequests(){return this.registry.list()}failScoop(e){return this.registry.failScoop(e)}failAll(){return this.registry.failAll()}async enqueueSudoRequest(e,t){let n=this.deps.getScoops(),r=this.deps.findApprover(e);if(!r)return bb.warn(`Sudo request received but no approver is registered — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};if(!n.has(e))return bb.warn(`Sudo request from unknown scoop — failing closed`,{scoopJid:e,kind:t.kind}),{decision:`deny`};let{id:i,pending:a}=this.registry.register(e,t);bb.info(`Sudo request enqueued for cone`,{id:i,scoopJid:e,kind:t.kind,detailPreview:t.detail.slice(0,80)});let o=n.get(e);this.deps.getLickManager()?.emitEvent({type:`sudo-request`,lickId:i,sudoKind:t.kind,sudoDetail:t.detail,sudoScoopName:o?.assistantLabel??o?.name??e,sudoSuggestedPattern:t.suggestedPattern,targetScoop:r.name,timestamp:new Date().toISOString(),body:{requestId:i,kind:t.kind,detail:t.detail,suggestedPattern:t.suggestedPattern,scoopJid:e}});try{await this.deliverSudoRequestToCone(r,e,i,t)}catch(t){let n=t instanceof Error?t.message:String(t);bb.error(`Failed to deliver sudo request to cone — failing closed`,{id:i,scoopJid:e,error:n}),this.registry.resolve(i,{decision:`deny`})}return a}resolveSudoRequest(e,t){let n=this.registry.resolve(e,t);return n?bb.info(`Sudo request resolved by cone`,{id:e,decision:t.decision}):bb.warn(`Sudo request resolve: unknown / already-settled id`,{id:e,decision:t.decision}),n}async resolveSudoRequestAndPersist(e,t){let n=this.registry.get(e);if(!n)return{settled:!1,persisted:!1};let r=this.resolveSudoRequest(e,t);if(!r)return{settled:!1,persisted:!1};let i=this.deps.getScoops().get(n.scoopJid),a=n.request.kind,o=i?.folder,s=this.deps.getSudoManager(),c=!1,l,u;if(t.decision===`always`&&s&&i&&i.parentJid!==null)if(a===`command`||a===`read`||a===`write`){let r=t.pattern?.trim()||n.request.suggestedPattern?.trim()||n.request.detail.trim();try{let e=await s.appendScoopRule(i.folder,a,r);e?(c=!0,l=e):u=`pattern collapsed to empty after sanitization`}catch(t){u=t instanceof Error?t.message:String(t),bb.warn(`Failed to persist always grant`,{id:e,folder:i.folder,kind:a,error:u})}}else u=`cannot persist always grant for kind "${a}" (no matching sudoers directive)`;return await this.persistLickDecision(e,t.decision),{settled:r,persisted:c,persistedPattern:l,persistError:u,scoopFolder:o,kind:a}}async persistLickDecision(e,t){let n=t===`deny`?`dismissed`:`confirmed`,r=this.deps.findApprover(this.registry.get(e)?.scoopJid);if(r)try{let t=(await this.deps.getMessagesForScoop(r.jid)).find(t=>t.lickId===e||t.id===`sudo-request-${e}`);if(!t){bb.warn(`Lick decision: no stored message found to flip`,{lickId:e});return}t.lickState=n,await this.deps.saveMessage(t),this.deps.onMessageUpdate(r.jid,{messageId:t.id,lickId:e,lickState:n})}catch(t){bb.warn(`Failed to persist lick decision`,{lickId:e,error:t instanceof Error?t.message:String(t)})}}async deliverSudoRequestToCone(e,t,n,r){let i=this.deps.getScoops().get(t),a=i?.assistantLabel??t,o=i?.folder??t,s=Sb(a,n,r),c={id:`sudo-request-${n}`,chatJid:e.jid,senderId:o,senderName:a,content:s,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sudo-request`,lickId:n,lickState:`pending`};await this.deps.handleMessage(c)}};function Sb(e,t,n){let r=[`[@${e} sudo-request]`,`Lick ID: ${t}`,`Kind: ${n.kind}`,`Detail: ${n.detail}`];return n.suggestedPattern&&r.push(`Suggested pattern: ${n.suggestedPattern}`),r.push(``,`Use the lick_confirm tool with lick_id="${t}" to approve (or always-approve with a pattern), or lick_dismiss with lick_id="${t}" to deny.`),r.join(`
|
|
1053
1053
|
`)}const Cb=r(`scoop-completion-service`),wb=`/shared/scoop-notifications`,Tb=1e3,Eb=2e4;function Db(e){let t=e.replace(/\r\n?/g,`
|
|
1054
1054
|
`);if(t.length===0)return 0;let n=1;for(let e=0;e<t.length;e++)t[e]===`
|
|
1055
1055
|
`&&n++;return t.endsWith(`
|
|
1056
1056
|
`)?n-1:n}function Ob(e){return e.length>Eb?e.slice(0,Eb)+`
|
|
1057
|
-
... (truncated)`:e}var kb=class{scoopResponseBuffer=new Map;mutedScoops=new Set;pendingCompletions=new Map;completionWaiters=new Map;deps;constructor(e){this.deps=e}appendResponseChunk(e,t){let n=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,n+t)}setResponseFull(e,t){this.scoopResponseBuffer.set(e,t)}clearResponse(e){this.scoopResponseBuffer.delete(e)}muteScoops(e){for(let t of e)this.mutedScoops.add(t);Cb.info(`Scoops muted`,{count:e.length})}isScoopMuted(e){return this.mutedScoops.has(e)}forgetScoop(e,t){this.scoopResponseBuffer.delete(e),this.mutedScoops.delete(e),this.pendingCompletions.delete(e);let n=this.completionWaiters.get(e);if(n&&n.length>0){this.completionWaiters.delete(e);for(let r of n)try{r(null)}catch(n){Cb.warn(`completion waiter threw on cleanup`,{jid:e,reason:t,error:n instanceof Error?n.message:String(n)})}}}shutdown(){for(let e of this.completionWaiters.values())for(let t of e)try{t(null)}catch(e){Cb.warn(`completion waiter threw during shutdown`,{error:e instanceof Error?e.message:String(e)})}this.completionWaiters.clear(),this.mutedScoops.clear(),this.pendingCompletions.clear(),this.scoopResponseBuffer.clear()}async notifyCompletion(e){let t=this.deps.getScoop(e);if(!t||t.parentJid===null)return;
|
|
1057
|
+
... (truncated)`:e}var kb=class{scoopResponseBuffer=new Map;mutedScoops=new Set;pendingCompletions=new Map;completionWaiters=new Map;deps;constructor(e){this.deps=e}appendResponseChunk(e,t){let n=this.scoopResponseBuffer.get(e)??``;this.scoopResponseBuffer.set(e,n+t)}setResponseFull(e,t){this.scoopResponseBuffer.set(e,t)}clearResponse(e){this.scoopResponseBuffer.delete(e)}muteScoops(e){for(let t of e)this.mutedScoops.add(t);Cb.info(`Scoops muted`,{count:e.length})}isScoopMuted(e){return this.mutedScoops.has(e)}forgetScoop(e,t){this.scoopResponseBuffer.delete(e),this.mutedScoops.delete(e),this.pendingCompletions.delete(e);let n=this.completionWaiters.get(e);if(n&&n.length>0){this.completionWaiters.delete(e);for(let r of n)try{r(null)}catch(n){Cb.warn(`completion waiter threw on cleanup`,{jid:e,reason:t,error:n instanceof Error?n.message:String(n)})}}}shutdown(){for(let e of this.completionWaiters.values())for(let t of e)try{t(null)}catch(e){Cb.warn(`completion waiter threw during shutdown`,{error:e instanceof Error?e.message:String(e)})}this.completionWaiters.clear(),this.mutedScoops.clear(),this.pendingCompletions.clear(),this.scoopResponseBuffer.clear()}async notifyCompletion(e){let t=this.deps.getScoop(e);if(!t||t.parentJid===null)return;ir(`complete`,t.folder);let n=this.scoopResponseBuffer.get(e);if(this.scoopResponseBuffer.delete(e),!n||t.notifyOnComplete===!1)return;let r=this.completionWaiters.get(e);if(r&&r.length>0){this.completionWaiters.delete(e);let t=Ob(n);for(let n of r)try{n(t)}catch(t){Cb.warn(`completion waiter threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}return}if(this.mutedScoops.has(e)){this.pendingCompletions.set(e,{responseText:n,timestamp:new Date().toISOString()}),Cb.info(`Scoop completion stashed (muted)`,{scoop:t.folder,responseLength:n.length});return}await this.deliverCompletionToParent(t,n)}async deliverCompletionToParent(e,t){let n=this.deps.findParent(e.jid);if(!n)return;let r=Db(t),i=t.slice(0,Tb),a,o=null,s=null;try{s=await this.writeScoopCompletionArtifact(e,t),Cb.info(`Routing scoop completion to cone`,{scoop:e.folder,responseLength:t.length,lineCount:r,notificationPath:s})}catch(t){o=t instanceof Error?t.message:String(t),Cb.warn(`Failed to persist scoop completion artifact, falling back to inline preview`,{scoop:e.folder,error:o})}a=o===null?Ab(e.assistantLabel,s??`unavailable`,r,i):jb(e.assistantLabel,r,i,o);let c={id:`scoop-done-${e.jid}-${Date.now()}`,chatJid:n.jid,senderId:e.folder,senderName:e.assistantLabel,content:a,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-notify`};try{this.deps.notifyIncomingMessage(n.jid,c)}catch(t){Cb.warn(`onIncomingMessage for scoop-notify threw`,{scoop:e.folder,error:t instanceof Error?t.message:String(t)})}try{await this.deps.handleMessage(c)}catch(t){let r=t instanceof Error?t.message:String(t);Cb.error(`Failed to route scoop completion to cone`,{scoop:e.folder,error:r}),this.deps.reportError(n.jid,`Scoop ${e.folder} completed but notification failed: ${r}`)}}async writeScoopCompletionArtifact(e,t){let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);await n.mkdir(wb,{recursive:!0}),await this.pruneScoopCompletionArtifacts(199);let r=new Date().toISOString().replace(/[:.]/g,`-`),i=Math.random().toString(36).slice(2,8),a=`${wb}/${r}-${e.folder}-${i}.md`;return await n.writeFile(a,t),await this.pruneScoopCompletionArtifacts(),a}async pruneScoopCompletionArtifacts(e=200){let t=this.deps.getSharedFs();if(!t)return;let n;try{n=await t.readDir(wb)}catch{return}let r=n.filter(e=>e.type===`file`).map(e=>e.name).sort(),i=r.length-e;if(!(i<=0))for(let e of r.slice(0,i)){let n=`${wb}/${e}`;try{await t.rm(n)}catch(e){Cb.warn(`Failed to prune scoop completion artifact`,{path:n,error:e instanceof Error?e.message:String(e)})}}}async unmuteScoops(e){let t=[],n=[];for(let r of e){this.mutedScoops.delete(r);let e=this.pendingCompletions.get(r);if(!e)continue;this.pendingCompletions.delete(r);let i=this.deps.getScoop(r);if(!i||i.parentJid===null)continue;let a={jid:r,summary:Ob(e.responseText),timestamp:e.timestamp,notificationPath:null};t.push(a),n.push(this.writeScoopCompletionArtifact(i,e.responseText).then(e=>{a.notificationPath=e}).catch(e=>{Cb.warn(`unmute artifact persist failed`,{jid:r,error:e instanceof Error?e.message:String(e)})}))}return await Promise.all(n),Cb.info(`Scoops unmuted`,{count:e.length,consumed:t.length}),t}async waitForScoops(e,t){if(e.length===0)return[];let n=Array.from(new Set(e)),r=new Map,i=[];for(let e of n)this.mutedScoops.has(e)||(this.mutedScoops.add(e),i.push(e));this.claimPendingSummaries(n,r);let a=n.filter(e=>!r.has(e)),o=a.filter(e=>this.deps.hasScoop(e)),s=a.filter(e=>!this.deps.hasScoop(e));for(let e of s)r.set(e,{summary:null,timedOut:!0});let c=[],l=o.map(e=>new Promise(t=>{let n=n=>{r.has(e)||(r.set(e,{summary:n,timedOut:n===null}),t())};c.push({jid:e,waiter:n});let i=this.completionWaiters.get(e);i||(i=[],this.completionWaiters.set(e,i)),i.push(n)}));try{await this.awaitScoopWaiters(l,t)}finally{this.removeCompletionWaiters(c);for(let e of i)this.mutedScoops.delete(e)}for(let e of o)r.has(e)||r.set(e,{summary:null,timedOut:!0});return e.map(e=>{let t=r.get(e)??{summary:null,timedOut:!0};return{jid:e,summary:t.summary,timedOut:t.timedOut}})}claimPendingSummaries(e,t){for(let n of e){let e=this.pendingCompletions.get(n);e&&(this.pendingCompletions.delete(n),t.set(n,{summary:Ob(e.responseText),timedOut:!1}))}}async awaitScoopWaiters(e,t){if(e.length===0)return;if(t==null||t<0){await Promise.all(e);return}let n=null;try{await Promise.race([Promise.all(e),new Promise(e=>{n=setTimeout(()=>e(),t)})])}finally{n&&clearTimeout(n)}}removeCompletionWaiters(e){for(let{jid:t,waiter:n}of e){let e=this.completionWaiters.get(t);if(!e)continue;let r=e.indexOf(n);r!==-1&&e.splice(r,1),e.length===0&&this.completionWaiters.delete(t)}}scheduleScoopWait(e,t){let n=Array.from(new Set(e)),r=n.filter(e=>this.deps.hasScoop(e)),i=n.filter(e=>!this.deps.hasScoop(e));return this.waitForScoops(r,t).then(e=>this.deliverWaitResultsToCone(e)).catch(e=>{Cb.error(`scheduleScoopWait failed`,{error:e instanceof Error?e.message:String(e)})}),{scheduled:r,unknown:i}}async deliverWaitResultsToCone(e){if(e.length===0)return;let t=new Map;for(let n of e){let e=this.deps.findParent(n.jid);if(!e)continue;let r=t.get(e.jid)??{parent:e,results:[]};r.results.push(n),t.set(e.jid,r)}for(let{parent:e,results:n}of t.values())await this.deliverWaitResultsTo(e,n)}async deliverWaitResultsTo(e,t){let n=[`[scoop_wait completed]`],r=0,i=0;for(let e of t){let t=this.deps.getScoop(e.jid)?.folder??e.jid;e.timedOut?(r+=1,n.push(`--- ${t} (timed out) ---`)):(i+=1,n.push(`--- ${t} ---`),n.push(e.summary??`(no output)`))}let a=`${i} completed, ${r} timed out`;n.splice(1,0,a);let o={id:`scoop-wait-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,chatJid:e.jid,senderId:`scoop-wait`,senderName:`scoop-wait`,content:n.join(`
|
|
1058
1058
|
`),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-wait`};try{this.deps.notifyIncomingMessage(e.jid,o)}catch(e){Cb.warn(`onIncomingMessage for scoop-wait threw`,{error:e instanceof Error?e.message:String(e)})}try{await this.deps.handleMessage(o)}catch(t){let n=t instanceof Error?t.message:String(t);Cb.error(`Failed to route scoop-wait result to cone`,{error:n}),this.deps.reportError(e.jid,`scoop_wait completed but notification failed: ${n}`)}}};function Ab(e,t,n,r){return[`[@${e} completed]`,`VFS path: ${t}`,`Total lines: ${n}`,`Preview (up to ${Tb} chars):`,r].join(`
|
|
1059
1059
|
`)}function jb(e,t,n,r){return[`[@${e} completed]`,`VFS path: unavailable`,`Artifact persistence error: ${r}`,`Total lines: ${t}`,`Preview (up to ${Tb} chars):`,n].join(`
|
|
1060
|
-
`)}const Mb=9e5,Nb=36e5;function Pb(e,t,n=`live`){let r=t.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)return null;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map,o=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1),o.set(e.model,(o.get(e.model)??0)+e.usage.cost.total);let s=``,c=0;for(let[e,t]of a)t>c&&(s=e,c=t);let l=r.map(e=>e.timestamp).sort((e,t)=>e-t),u=l[0],d=l[l.length-1],f=d-u,p=Math.max(1,Math.ceil(f/Mb))*Mb;return{name:e.assistantLabel,type:rh(e)?`cone`:`scoop`,model:s,models:[...o.entries()].sort(([,e],[,t])=>t-e).map(([e])=>e),source:n,usage:i,turns:r.length,firstActivity:u,lastActivity:d,activeTimeMs:p}}var Fb=class{dropped=[];droppedMessages=[];deps;constructor(e){this.deps=e}snapshot(e){let t=this.deps.getScoops().get(e),n=this.deps.getContexts().get(e);if(!t||!n)return;let r=Pb(t,n,`dropped`);r&&this.dropped.push(r);let i=n.getAgentMessages().filter(e=>e.role===`assistant`);i.length>0&&this.droppedMessages.push(i)}getSessionCosts(e={}){let t=[],n=this.deps.getContexts();for(let e of this.deps.getScoops().values()){let r=n.get(e.jid);if(!r)continue;let i=Pb(e,r);i&&t.push(i)}return e.includeDropped&&t.push(...this.dropped),t}getBurnRate(e=Date.now()){let t=this.droppedMessages.flat();for(let e of this.deps.getContexts().values())for(let n of e.getAgentMessages())n.role===`assistant`&&t.push(n);if(t.length===0)return 0;let n=t[0].timestamp;for(let e of t)n=Math.min(n,e.timestamp);let r=Math.max(e-n,6e4),i=Math.min(9e5,r),a=Math.min(36e5,r),o=e-i,s=e-a,c=0,l=0,u=0;for(let e of t){let t=e.usage.cost.total;u+=t,e.timestamp>=o&&(c+=t),e.timestamp>=s&&(l+=t)}let d=c*Nb/i,f=l*Nb/a,p=u*Nb/r,m=d*.5+f*.3+p*.2;return Math.max(m,p)}getContextFills(){return[...this.deps.getContexts().entries()].map(([e,t])=>({jid:e,fill:t.getContextFill()}))}getModelCosts(e={}){let t=new Map,n=this.deps.getContexts();for(let e of n.values()){let n=e.getAgentMessages().filter(e=>e.role===`assistant`);this.aggregateMessages(n,t)}if(e.includeDropped)for(let e of this.droppedMessages)this.aggregateMessages(e,t);return Array.from(t.values()).sort((e,t)=>t.cost-e.cost)}aggregateMessages(e,t){for(let n of e){let e=t.get(n.model);e?(e.input+=n.usage.input,e.output+=n.usage.output,e.cacheRead+=n.usage.cacheRead,e.cacheWrite+=n.usage.cacheWrite,e.cost+=n.usage.cost.total,e.turns+=1):t.set(n.model,{model:n.model,input:n.usage.input,output:n.usage.output,cacheRead:n.usage.cacheRead,cacheWrite:n.usage.cacheWrite,cost:n.usage.cost.total,turns:1})}}reset(){this.dropped=[],this.droppedMessages=[]}};const Ib=r(`scoop-idle-timers`);var Lb=class{deps;timers=new Map;constructor(e){this.deps=e}start(e){if(this.clear(e),this.deps.getTabs().get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.timers.delete(e),this.fire(e)},12e4);this.timers.set(e,t)}clear(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.keys())this.clear(e)}fire(e){let t=this.deps.getScoops().get(e);if(!t||t.parentJid===null||this.deps.getTabs().get(e)?.status!==`ready`)return;let n=this.deps.findParent(e);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Ib.info(`Scoop idle timeout`,{jid:e,scoop:t.folder});try{this.deps.notifyIncomingMessage(n.jid,r)}catch(t){Ib.warn(`onIncomingMessage for scoop-idle threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}this.deps.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Ib.error(`Failed to send idle notification`,{jid:e,error:n})})}};const Rb=r(`work-unit`),zb={initializing:new Set([`ready`,`error`]),ready:new Set([`processing`,`error`,`initializing`]),processing:new Set([`ready`,`error`]),error:new Set([`initializing`,`ready`,`processing`])};var Bb=class{id;deps;tab=null;context=null;observers=new Set;closed=!1;constructor(e,t){this.id=e,this.deps=t}get descriptor(){let e=this.deps.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);let t=Fh(e,this.tab??void 0);return this.closed?{...t,status:`closed`}:t}get status(){return this.closed?`closed`:kh(this.tab?.status)}get isClosed(){return this.closed}transition(e,t={}){if(this.closed)return Rb.debug(`ignoring transition on closed unit`,{jid:this.id,next:e}),!1;let n=this.tab?.status;if(n!==void 0&&n!==e&&!zb[n].has(e))return Rb.warn(`illegal work-unit transition ignored`,{jid:this.id,from:n,to:e}),!1;let r=new Date().toISOString();return this.tab={jid:this.id,contextId:this.tab?.contextId??`scoop-${this.id}`,...this.tab,...t,status:e,lastActivity:t.lastActivity??r},e!==`error`&&delete this.tab.error,!0}touch(){this.tab&&={...this.tab,lastActivity:new Date().toISOString()}}attachContext(e,t){if(this.closed)throw Error(`Cannot attach a context to closed unit ${this.id}`);this.context=e,this.tab={jid:this.id,contextId:t,status:`initializing`,lastActivity:new Date().toISOString()}}detachContext(){this.deps.clearIdleTimer(this.id),this.context?.stop(),this.context=null}disposeContext(){this.deps.clearIdleTimer(this.id),this.context?.dispose(),this.context=null,this.tab=null}observe(e){return this.closed?()=>{}:(this.observers.add(e),()=>{this.observers.delete(e)})}get observerCount(){return this.observers.size}dispatch(e,...t){for(let n of this.observers){let r=n[e];if(r)try{r(...t)}catch(t){Rb.warn(`scoop observer threw`,{jid:this.id,event:e,error:t instanceof Error?t.message:String(t)})}}}send(e){if(this.closed)return Promise.reject(Error(`Work unit is closed: ${this.id}`));let t=this.deps.getScoop(this.id);return this.deps.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t?.assistantLabel??this.id,e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.observe({onStatusChange:t=>e({type:`status`,status:kh(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.context?.stop()}close(){return this.closed?Promise.resolve():this.deps.unregister(this.id)}async teardown(){if(this.closed)return;this.closed=!0,this.deps.clearIdleTimer(this.id);let e=this.context;this.context=null;try{e?.stop(),e?.dispose()}catch(e){Rb.warn(`context dispose threw during close`,{jid:this.id,error:e instanceof Error?e.message:String(e)})}this.observers.clear(),this.deps.forgetCompletion(this.id,`close`),Rb.info(`Work unit closed`,{jid:this.id})}async snapshot(){return{descriptor:this.descriptor,messages:this.context?this.context.getAgentMessages():[],contextFill:this.context?this.context.getContextFill():0}}};function Vb(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 Hb(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 Ub(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 Wb(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function Gb(e,t,n){let r=e[e.length-1];if(r){let i=r.role===`assistant`?r.errorMessage:void 0;if(i){if(Kb(i,e,t,n))return}else t.imageRecovery.markSettled(),t.overflow.markSettled(),r.role===`assistant`&&t.overflow.markAssistantSucceeded()}t.persist(e)}function Kb(e,t,n,r){let i=n.imageRecovery.isActive||n.overflow.isActive;return!i&&Vb(e)?(n.imageRecovery.recover(t),!0):n.overflow.shouldRecover(t[t.length-1])?(n.overflow.recover(t,r),!0):!i&&n.isProcessing()&&!n.didStreamDeltas()?(n.latchStreamError(e),!0):(n.imageRecovery.markSettled(),n.overflow.markSettled(),ir(`llm`,e),n.onError(e),!1)}function qb(e,t,n){switch(e.type){case`message_update`:{let n=e.assistantMessageEvent;n.type===`text_delta`&&t.textDelta(n.delta);break}case`tool_execution_start`:t.toolStart(e.toolName,e.args,e.toolCallId);break;case`tool_execution_update`:Jb(e,t);break;case`tool_execution_end`:Yb(e,t),t.checkpoint();break;case`message_end`:e.message.role===`assistant`&&t.assistantMessageEnd(e.message),t.checkpoint();break;case`turn_start`:t.turnStart();break;case`turn_end`:if(t.turnCompleted(),e.message.role===`assistant`&&To(e.message))break;t.responseDone();break;case`agent_end`:t.agentEnd(e.messages,n)}}function Jb(e,t){let n=e.partialResult;for(let r of n?.content??[])r.type===`tool_ui`&&r.requestId&&r.html?t.toolUI(e.toolName,r.requestId,r.html):r.type===`tool_ui_done`&&r.requestId?t.toolUIDone(r.requestId):r.type===`progress`&&r.progress&&t.toolProgress(e.toolName,r.progress,e.toolCallId)}function Yb(e,t){let n=e.result,r=[];for(let e of n?.content??[])e.type===`text`&&e.text&&r.push(e.text),e.type===`image`&&e.data&&e.mimeType&&r.push(`<img:data:${e.mimeType};base64,${e.data}>`);let i=r.join(`
|
|
1060
|
+
`)}const Mb=9e5,Nb=36e5;function Pb(e,t,n=`live`){let r=t.getAgentMessages().filter(e=>e.role===`assistant`);if(r.length===0)return null;let i={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},a=new Map,o=new Map;for(let e of r)i.input+=e.usage.input,i.output+=e.usage.output,i.cacheRead+=e.usage.cacheRead,i.cacheWrite+=e.usage.cacheWrite,i.totalTokens+=e.usage.totalTokens,i.cost.input+=e.usage.cost.input,i.cost.output+=e.usage.cost.output,i.cost.cacheRead+=e.usage.cost.cacheRead,i.cost.cacheWrite+=e.usage.cost.cacheWrite,i.cost.total+=e.usage.cost.total,a.set(e.model,(a.get(e.model)??0)+1),o.set(e.model,(o.get(e.model)??0)+e.usage.cost.total);let s=``,c=0;for(let[e,t]of a)t>c&&(s=e,c=t);let l=r.map(e=>e.timestamp).sort((e,t)=>e-t),u=l[0],d=l[l.length-1],f=d-u,p=Math.max(1,Math.ceil(f/Mb))*Mb;return{name:e.assistantLabel,type:rh(e)?`cone`:`scoop`,model:s,models:[...o.entries()].sort(([,e],[,t])=>t-e).map(([e])=>e),source:n,usage:i,turns:r.length,firstActivity:u,lastActivity:d,activeTimeMs:p}}var Fb=class{dropped=[];droppedMessages=[];deps;constructor(e){this.deps=e}snapshot(e){let t=this.deps.getScoops().get(e),n=this.deps.getContexts().get(e);if(!t||!n)return;let r=Pb(t,n,`dropped`);r&&this.dropped.push(r);let i=n.getAgentMessages().filter(e=>e.role===`assistant`);i.length>0&&this.droppedMessages.push(i)}getSessionCosts(e={}){let t=[],n=this.deps.getContexts();for(let e of this.deps.getScoops().values()){let r=n.get(e.jid);if(!r)continue;let i=Pb(e,r);i&&t.push(i)}return e.includeDropped&&t.push(...this.dropped),t}getBurnRate(e=Date.now()){let t=this.droppedMessages.flat();for(let e of this.deps.getContexts().values())for(let n of e.getAgentMessages())n.role===`assistant`&&t.push(n);if(t.length===0)return 0;let n=t[0].timestamp;for(let e of t)n=Math.min(n,e.timestamp);let r=Math.max(e-n,6e4),i=Math.min(9e5,r),a=Math.min(36e5,r),o=e-i,s=e-a,c=0,l=0,u=0;for(let e of t){let t=e.usage.cost.total;u+=t,e.timestamp>=o&&(c+=t),e.timestamp>=s&&(l+=t)}let d=c*Nb/i,f=l*Nb/a,p=u*Nb/r,m=d*.5+f*.3+p*.2;return Math.max(m,p)}getContextFills(){return[...this.deps.getContexts().entries()].map(([e,t])=>({jid:e,fill:t.getContextFill()}))}getModelCosts(e={}){let t=new Map,n=this.deps.getContexts();for(let e of n.values()){let n=e.getAgentMessages().filter(e=>e.role===`assistant`);this.aggregateMessages(n,t)}if(e.includeDropped)for(let e of this.droppedMessages)this.aggregateMessages(e,t);return Array.from(t.values()).sort((e,t)=>t.cost-e.cost)}aggregateMessages(e,t){for(let n of e){let e=t.get(n.model);e?(e.input+=n.usage.input,e.output+=n.usage.output,e.cacheRead+=n.usage.cacheRead,e.cacheWrite+=n.usage.cacheWrite,e.cost+=n.usage.cost.total,e.turns+=1):t.set(n.model,{model:n.model,input:n.usage.input,output:n.usage.output,cacheRead:n.usage.cacheRead,cacheWrite:n.usage.cacheWrite,cost:n.usage.cost.total,turns:1})}}reset(){this.dropped=[],this.droppedMessages=[]}};const Ib=r(`scoop-idle-timers`);var Lb=class{deps;timers=new Map;constructor(e){this.deps=e}start(e){if(this.clear(e),this.deps.getTabs().get(e)?.status===`processing`)return;let t=setTimeout(()=>{this.timers.delete(e),this.fire(e)},12e4);this.timers.set(e,t)}clear(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.keys())this.clear(e)}fire(e){let t=this.deps.getScoops().get(e);if(!t||t.parentJid===null||this.deps.getTabs().get(e)?.status!==`ready`)return;let n=this.deps.findParent(e);if(!n)return;let r={id:`scoop-idle-${e}-${Date.now()}`,chatJid:n.jid,senderId:t.folder,senderName:t.assistantLabel,content:`[@${t.assistantLabel} idle]: Scoop "${t.name}" has been ready for 2 minutes without receiving any work. This is expected if the scoop is waiting for webhooks or cron tasks. If you intended to delegate work, use feed_scoop to send a prompt.`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-idle`};Ib.info(`Scoop idle timeout`,{jid:e,scoop:t.folder});try{this.deps.notifyIncomingMessage(n.jid,r)}catch(t){Ib.warn(`onIncomingMessage for scoop-idle threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}this.deps.handleMessage(r).catch(t=>{let n=t instanceof Error?t.message:String(t);Ib.error(`Failed to send idle notification`,{jid:e,error:n})})}};const Rb=r(`work-unit`),zb={initializing:new Set([`ready`,`error`]),ready:new Set([`processing`,`error`,`initializing`]),processing:new Set([`ready`,`error`]),error:new Set([`initializing`,`ready`,`processing`])};var Bb=class{id;deps;tab=null;context=null;observers=new Set;closed=!1;constructor(e,t){this.id=e,this.deps=t}get descriptor(){let e=this.deps.getScoop(this.id);if(!e)throw Error(`Work unit not found: ${this.id}`);let t=Fh(e,this.tab??void 0);return this.closed?{...t,status:`closed`}:t}get status(){return this.closed?`closed`:kh(this.tab?.status)}get isClosed(){return this.closed}transition(e,t={}){if(this.closed)return Rb.debug(`ignoring transition on closed unit`,{jid:this.id,next:e}),!1;let n=this.tab?.status;if(n!==void 0&&n!==e&&!zb[n].has(e))return Rb.warn(`illegal work-unit transition ignored`,{jid:this.id,from:n,to:e}),!1;let r=new Date().toISOString();return this.tab={jid:this.id,contextId:this.tab?.contextId??`scoop-${this.id}`,...this.tab,...t,status:e,lastActivity:t.lastActivity??r},e!==`error`&&delete this.tab.error,!0}touch(){this.tab&&={...this.tab,lastActivity:new Date().toISOString()}}attachContext(e,t){if(this.closed)throw Error(`Cannot attach a context to closed unit ${this.id}`);this.context=e,this.tab={jid:this.id,contextId:t,status:`initializing`,lastActivity:new Date().toISOString()}}detachContext(){this.deps.clearIdleTimer(this.id),this.context?.stop(),this.context=null}disposeContext(){this.deps.clearIdleTimer(this.id),this.context?.dispose(),this.context=null,this.tab=null}observe(e){return this.closed?()=>{}:(this.observers.add(e),()=>{this.observers.delete(e)})}get observerCount(){return this.observers.size}dispatch(e,...t){for(let n of this.observers){let r=n[e];if(r)try{r(...t)}catch(t){Rb.warn(`scoop observer threw`,{jid:this.id,event:e,error:t instanceof Error?t.message:String(t)})}}}send(e){if(this.closed)return Promise.reject(Error(`Work unit is closed: ${this.id}`));let t=this.deps.getScoop(this.id);return this.deps.sendPrompt(this.id,e.text,e.senderId??`user`,e.senderName??t?.assistantLabel??this.id,e.steer===void 0?void 0:{steer:e.steer})}subscribe(e){return this.observe({onStatusChange:t=>e({type:`status`,status:kh(t)}),onResponse:(t,n)=>e({type:`response`,text:t,isPartial:n}),onSendMessage:t=>e({type:`send-message`,text:t}),onError:t=>e({type:`error`,error:t})})}async abort(e){this.context?.stop()}close(){return this.closed?Promise.resolve():this.deps.unregister(this.id)}async teardown(){if(this.closed)return;this.closed=!0,this.deps.clearIdleTimer(this.id);let e=this.context;this.context=null;try{e?.stop(),e?.dispose()}catch(e){Rb.warn(`context dispose threw during close`,{jid:this.id,error:e instanceof Error?e.message:String(e)})}this.observers.clear(),this.deps.forgetCompletion(this.id,`close`),Rb.info(`Work unit closed`,{jid:this.id})}async snapshot(){return{descriptor:this.descriptor,messages:this.context?this.context.getAgentMessages():[],contextFill:this.context?this.context.getContextFill():0}}};function Vb(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 Hb(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 Ub(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 Wb(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}function Gb(e,t,n){let r=e[e.length-1];if(r){let i=r.role===`assistant`?r.errorMessage:void 0;if(i){if(Kb(i,e,t,n))return}else t.imageRecovery.markSettled(),t.overflow.markSettled(),r.role===`assistant`&&t.overflow.markAssistantSucceeded()}t.persist(e)}function Kb(e,t,n,r){let i=n.imageRecovery.isActive||n.overflow.isActive;return!i&&Vb(e)?(n.imageRecovery.recover(t),!0):n.overflow.shouldRecover(t[t.length-1])?(n.overflow.recover(t,r),!0):!i&&n.isProcessing()&&!n.didStreamDeltas()?(n.latchStreamError(e),!0):(n.imageRecovery.markSettled(),n.overflow.markSettled(),ar(`llm`,e),n.onError(e),!1)}function qb(e,t,n){switch(e.type){case`message_update`:{let n=e.assistantMessageEvent;n.type===`text_delta`&&t.textDelta(n.delta);break}case`tool_execution_start`:t.toolStart(e.toolName,e.args,e.toolCallId);break;case`tool_execution_update`:Jb(e,t);break;case`tool_execution_end`:Yb(e,t),t.checkpoint();break;case`message_end`:e.message.role===`assistant`&&t.assistantMessageEnd(e.message),t.checkpoint();break;case`turn_start`:t.turnStart();break;case`turn_end`:if(t.turnCompleted(),e.message.role===`assistant`&&To(e.message))break;t.responseDone();break;case`agent_end`:t.agentEnd(e.messages,n)}}function Jb(e,t){let n=e.partialResult;for(let r of n?.content??[])r.type===`tool_ui`&&r.requestId&&r.html?t.toolUI(e.toolName,r.requestId,r.html):r.type===`tool_ui_done`&&r.requestId?t.toolUIDone(r.requestId):r.type===`progress`&&r.progress&&t.toolProgress(e.toolName,r.progress,e.toolCallId)}function Yb(e,t){let n=e.result,r=[];for(let e of n?.content??[])e.type===`text`&&e.text&&r.push(e.text),e.type===`image`&&e.data&&e.mimeType&&r.push(`<img:data:${e.mimeType};base64,${e.data}>`);let i=r.join(`
|
|
1061
1061
|
`);if(e.isError){let t=r.filter(e=>!e.startsWith(`<img:`)).join(`
|
|
1062
|
-
`);
|
|
1062
|
+
`);ar(`tool`,`${e.toolName}: ${t}`)}t.toolResult(e.toolName,i,e.isError,e.toolCallId)}const Xb=r(`scoop-context`);var Zb=class{deps;livePids=new Set;constructor(e){this.deps=e}spawn(e){let t=this.deps.processManager;if(!t)return null;let n=e=>{this.livePids.delete(e)},r=t.spawn({kind:`shell`,argv:[`bash`,`-c`,e],cwd:this.deps.cwd,owner:this.deps.owner,ppid:this.deps.getTurnPid()});return this.livePids.add(r.pid),{pid:r.pid,signal:r.abort.signal,kill:()=>{n(r.pid),t.signal(r.pid,`SIGKILL`)},exit:e=>{n(r.pid),t.exit(r.pid,e)}}}reapAll(){let e=this.deps.processManager;if(!e||this.livePids.size===0)return;let t=[...this.livePids];this.livePids.clear(),Xb.info(`Reaping background bash jobs on dispose`,{folder:this.deps.folder,pids:t});for(let n of t)e.signal(n,`SIGKILL`)}};const Qb=r(`scoop-context`);var $b=class{deps;active=!1;constructor(e){this.deps=e}get isActive(){return this.active}markSettled(){this.active=!1}recover(e){let t=this.deps.getAgent();if(t){Qb.warn(`Image processing error detected, attempting recovery`,{folder:this.deps.folder,messageCount:e.length}),this.active=!0,this.deps.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let n=e.slice(0,-1),r=ex(n);t.state.messages=n;let i=`[System: An image was rejected by the API and has been removed from the conversation (${r} message(s) affected). The conversation continues without the image.]`;t.prompt(i).catch(e=>{Qb.error(`Image recovery re-prompt failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)})}catch(e){Qb.error(`Image recovery failed`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.fail(e)}}}fail(e){this.active=!1,this.deps.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}};function ex(e){let t=0,n=Math.max(0,e.length-10);for(let r=e.length-1;r>=n;r--){let n=e[r];if(!Array.isArray(n.content)||!n.content.some(e=>e.type===`image`))continue;let i=n.content.filter(e=>e.type!==`image`);i.length===0?e[r]={...n,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:e[r]={...n,content:i},t++}return t}async function tx(e,t){try{let n=await e.readFile(t,{encoding:`utf-8`});return typeof n==`string`?n:new TextDecoder().decode(n)}catch{return``}}async function nx(e,t,n){let r=await tx(e,t.workspace.memoryPath),i=await n();if(i&&t.policy.canWriteSharedMemory)try{await(`getUnderlyingFS`in e?e.getUnderlyingFS():e).writeFile(`/shared/CLAUDE.md`,i)}catch{}return{scoopMemory:r,globalMemory:i}}const rx=r(`scoop-context`);function ix(e){let t=Sh(e);return t?Ke(t):rt()}function ax(e){let t=xh(e);return t?N(t,Sh(e)):de()}function ox(e,t){let n=xh(e),r=Sh(e),i=ax(e),a=t.display.role===`primary`?`Cone`:`Scoop "${e.name}"`;if(console.log(`[model] ${a} using model: ${i.id} (provider: ${i.provider})`),r&&(i.id!==n||!A(i,r)))throw Error(`Configured model ${r}:${n} resolved to ${i.provider}:${i.id}; refusing to run on a different model`);return!r&&n&&i.id!==n&&rx.warn(`Configured scoop model did not resolve; using resolved model instead`,{folder:e.folder,configuredModelId:n,resolvedModelId:i.id}),i}function sx(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role!==`assistant`||!r.usage)continue;let i=r.usage.input+r.usage.cacheRead+r.usage.output,a=2e5;try{let e=ax(t);typeof e.contextWindow==`number`&&e.contextWindow>0&&(a=e.contextWindow)}catch{}return Math.min(1,i/a)}return 0}function cx(e){let t=Sh(e)??``;try{t||=E()}catch{}return t?`No API key configured for provider "${t}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`}function lx(e,t,n,r,i){let a=e.config?.assistantName||e.assistantLabel,o=t.display.role===`primary`,{policy:s,workspace:c}=t,l=`# ${a}
|
|
1063
1063
|
|
|
1064
1064
|
You are ${a}, ${o?`the main assistant (cone)`:`a scoop assistant`} in SLICC (Self-Licking Ice Cream Cone).
|
|
1065
1065
|
|
|
@@ -1140,14 +1140,14 @@ Created: ${new Date().toISOString()}
|
|
|
1140
1140
|
|
|
1141
1141
|
## Context
|
|
1142
1142
|
(Add important context here)
|
|
1143
|
-
`;try{await e.writeFile(i,r)}catch(e){if(e?.code===`EACCES`)xx.debug(`Skipping default memory write (sandbox is read-only)`,{folder:t.folder,path:i});else throw e}}}async function Cx(e,t){let n=await
|
|
1143
|
+
`;try{await e.writeFile(i,r)}catch(e){if(e?.code===`EACCES`)xx.debug(`Skipping default memory write (sandbox is read-only)`,{folder:t.folder,path:i});else throw e}}}async function Cx(e,t){let n=await Vee(t.scoop,t.coneJid),r=(e,r,i)=>{let a=t.getEffortOverride(),o=a?{...i,effort:a}:i;return e.provider===`adobe`?It(e,r,{...o,headers:{...i?.headers,"X-Session-Id":n}}):It(e,r,o)},i=e.provider===`adobe`?{"X-Session-Id":n}:void 0,a=()=>t.getModelApiKey()??void 0,o=t.appendConeMemory,s=t.unit.policy.canWriteSharedMemory&&o?n=>o(n,{source:`compaction`,model:e,apiKey:t.getModelApiKey()??void 0,headers:i}):void 0;return{streamWithSessionId:r,compactFn:Fe({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:a,headers:i,onMemoryUpdates:s,shouldExtractMemories:()=>!ea(`agentic-memory`),onCompactionStateChange:e=>{t.onCompactionStateChange?.(e)}}),getCompactionApiKey:a}}function wx(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}const Tx=r(`secret-env`);function Ex(e){let t={},n;for(let r of e)!r?.name||!r?.maskedValue||(r.name===`oauth.github.token`&&(n=r.maskedValue),wx(r.name)&&(t[r.name]=r.maskedValue));return n&&(t.GITHUB_TOKEN===void 0&&(t.GITHUB_TOKEN=n),t.GH_TOKEN===void 0&&(t.GH_TOKEN=n)),t}async function Dx(){let e=Xe();if(e===`extension-direct`)return new Promise(e=>{chrome.runtime.sendMessage({type:`secrets.list-masked-entries`},t=>{let n=Ex(t?.entries??[]);Object.keys(n).length>0&&Tx.info(`Loaded masked secrets into shell env from SW`,{count:Object.keys(n).length}),e(n)})});if(e===`extension-delegate`)try{let e=Ex((await ot(`secrets.list-masked-entries`))?.entries??[]);return Object.keys(e).length>0&&Tx.info(`Loaded masked secrets into shell env from bridge`,{count:Object.keys(e).length}),e}catch(e){return Tx.debug(`Bridge list-masked-entries failed`,{error:e instanceof Error?e.message:String(e)}),{}}if(e===`connect`)return{};try{let e=await fetch(At(`/api/secrets/masked`),{headers:jt()});if(!e.ok)return Tx.warn(`Failed to fetch masked secrets`,{status:e.status}),{};let t=await e.json();if(!Array.isArray(t)||t.length===0)return{};let n=Ex(t);return Object.keys(n).length>0&&Tx.info(`Loaded masked secrets into shell env`,{count:Object.keys(n).length}),n}catch(e){return Tx.debug(`Could not fetch masked secrets (server may be unavailable)`,{error:e instanceof Error?e.message:String(e)}),{}}}function Ox(e){let t={positional:[],noProbe:!1,clearCache:!1,bodies:!1};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--source`)t.source=e[++n];else if(r===`--profile`)t.profile=e[++n];else if(r===`--backend`){let r=e[++n];r===`da`||r===`aem`?t.backend=r:t.backendError=r}else r===`--no-probe`?t.noProbe=!0:r===`--max-body-mb`?t.maxBodyMb=Number(e[++n]):r===`--clear-cache`?t.clearCache=!0:r===`--bodies`?t.bodies=!0:t.positional.push(r)}return t}function kx(e){let t=e.match(/^(da|aem):\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);return t?{scheme:t[1],org:t[2],name:t[3],path:(t[4]??``).replace(/^\/+/,``).replace(/\/+$/,``)}:null}function Ax(e){return`aem://${e.org}/${e.name}${e.path?`/${e.path}`:``}`}var jx=class{options;signedFetchS3;signedFetchDa;constructor(e){this.options=e,this.signedFetchS3=e.signedFetchS3,this.signedFetchDa=e.signedFetchDa}async execute(e,t,n){let r=e[0];if(r===`--help`||r===`-h`)return this.help();if(r===`unmount`||r===`-u`)return this.handleUnmount(e.slice(1),t);if(r===`list`||r===`-l`||r===`--list`)return this.handleList();if(r===`refresh`)return this.handleRefresh(e.slice(1),t,n);let i=Ox(e);if(i.positional.length===0)return this.usageError(`mount: mount point required`);let a=this.resolvePath(i.positional[0],t);return i.backendError===void 0?i.source?i.source.startsWith(`s3://`)?this.mountS3(a,i):i.source.startsWith(`da://`)||i.source.startsWith(`aem://`)?this.mountAdobe(a,i):this.usageError(`mount: invalid source '${i.source}' — expected s3://..., da://... or aem://...`):this.mountLocal(a,n):this.usageError(`mount: invalid --backend '${i.backendError}' — expected 'da' or 'aem'`)}async mountLocal(e,t){try{let n=this.options.isScoop??(()=>!1),r=Ht();if(!r){let n=await Mx(e);if(n)return await this.options.fs.mount(e,n,{env:t}),{stdout:`Mounted '${n.describe().displayName}' → ${e}\nIndexing in background for fast file discovery.\nNote: External changes are not auto-detected — use 'mount refresh ${e}' after modifying files outside the browser.\n`,stderr:``,exitCode:0}}let i=await Qt.create({mountId:sn(),isScoop:n,toolContext:r??void 0,isExtension:Tt(),targetPath:e});return await this.options.fs.mount(e,i,{env:t}),{stdout:`Mounted '${i.describe().displayName}' → ${e}\nIndexing in background for fast file discovery.\nNote: External changes are not auto-detected — use 'mount refresh ${e}' after modifying files outside the browser.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async mountS3(e,t){if(!t.source)return this.usageError(`mount: --source required`);let n=t.profile??`default`,r=sn(),i=new cn({mountId:r,ttlMs:3e4}),a=new tn({source:t.source,profile:n,cache:i,maxBodyBytes:t.maxBodyMb?t.maxBodyMb*1024*1024:void 0,mountId:r,signedFetch:this.signedFetchS3??an(n)});if(!t.noProbe)try{await a.readDir(`/`)}catch(e){return await a.close(),{stdout:``,stderr:`mount: probe failed for ${t.source} — ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return await this.options.fs.mount(e,a),{stdout:`Mounted '${a.describe().displayName}' → ${e} (profile: ${n})\n`,stderr:``,exitCode:0}}async mountAdobe(e,t){if(!t.source)return this.usageError(`mount: --source required`);let n=t.profile??`default`,r=this.signedFetchDa??nn(),i=kx(t.source);if(!i)return this.usageError(`mount: invalid source '${t.source}' — expected da://org/repo or aem://org/site`);let a=i.scheme===`aem`?`aem`:`da`,o=``;if(t.backend)a=t.backend;else if(i.scheme===`da`)try{a=(await xg(i.org,i.name,r)).backend,a===`aem`&&(o=`mount: ${i.org}/${i.name} is on Helix 6 — its content lives in the Source Bus at https://api.aem.live/${i.org}/sites/${i.name}/source, not admin.da.live. Mounting through aem://${i.org}/${i.name}. Pass --backend da to force the old endpoint.\n`)}catch(e){return{stdout:``,stderr:`mount: could not determine the content source for ${t.source} — ${e instanceof Error?e.message:String(e)}. Pass --backend da or --backend aem to skip this probe.\n`,exitCode:1}}let s=sn(),c=new cn({mountId:s,ttlMs:3e4}),l={source:a===`aem`?Ax(i):`da://${i.org}/${i.name}${i.path?`/${i.path}`:``}`,profile:n,cache:c,maxBodyBytes:t.maxBodyMb?t.maxBodyMb*1024*1024:void 0,mountId:s,signedFetch:r},u=a===`aem`?new on(l):new en(l);if(!t.noProbe)try{await u.readDir(`/`)}catch(e){return await u.close(),{stdout:``,stderr:o+`mount: probe failed for ${l.source} — ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return await this.options.fs.mount(e,u),{stdout:`Mounted '${u.describe().displayName}' → ${e} (profile: ${n})\n`,stderr:o,exitCode:0}}async handleUnmount(e,t){let n=Ox(e);if(n.positional.length===0)return{stdout:``,stderr:`mount unmount: path required
|
|
1144
1144
|
`,exitCode:1};let r=this.resolvePath(n.positional[0],t);try{let e,t;if(n.clearCache){let{getAllMountEntries:n}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),i=(await n()).find(e=>e.targetPath===r),a=i?.descriptor.kind;i&&(a===`s3`||a===`da`||a===`aem`)&&(e=i.descriptor.mountId,t=i.descriptor.kind)}await this.options.fs.unmount(r);let i=``;if(n.clearCache&&e&&t){let{RemoteMountCache:t}=await import(`./remote-cache-JAv9sQH_.js`).then(e=>e.n);await new t({mountId:e,ttlMs:3e4}).clearMount(),i=` (cache cleared)`}else n.clearCache&&(i=` (no remote cache to clear)`);return{stdout:`Unmounted ${r}${i}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount unmount: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async handleList(){try{let e=this.options.fs.listMounts();if(e.length===0)return{stdout:`No active mounts
|
|
1145
1145
|
`,stderr:``,exitCode:0};let t=this.options.fs.getMountIndex();return{stdout:e.map(e=>{let n=t.getState(e);if(!n)return e;if(n.status===`ready`)return`${e} (indexed: ${n.indexed} entries)`;if(n.status===`indexing`)return`${e} (indexing: ${n.indexed} entries...)`;if(n.status===`error`)switch(n.abortCause){case`depth-exceeded`:return`${e} (index skipped: directory nesting exceeded the depth limit — reads use the slow path; raise SLICC_MOUNT_INDEX_MAX_DEPTH or 'mount unmount ${e}')`;case`entries-exceeded`:return`${e} (index skipped: mounted tree is too large — reads use the slow path; raise SLICC_MOUNT_INDEX_MAX_ENTRIES or 'mount unmount ${e}')`;case`cycle-detected`:return`${e} (index skipped: self-referential mount cycle detected — run 'mount unmount ${e}' to remove it)`;default:return`${e} (index error: ${n.error})`}return`${e} (pending index)`}).join(`
|
|
1146
1146
|
`)+`
|
|
1147
1147
|
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`mount list: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async handleRefresh(e,t,n){let r=Ox(e);if(r.positional.length===0)return{stdout:``,stderr:`mount refresh: path required
|
|
1148
1148
|
`,exitCode:1};let i=this.resolvePath(r.positional[0],t);try{let e=await this.options.fs.refreshMount(i,{bodies:r.bodies,env:n});return{stdout:`Refreshed ${i}: +${e.added.length} -${e.removed.length} ~${e.changed.length} (${e.unchanged} unchanged, ${e.errors.length} errors)\n`,stderr:e.errors.map(e=>` ${e.path}: ${e.message}\n`).join(``),exitCode:+(e.errors.length>0)}}catch(e){return{stdout:``,stderr:`mount refresh: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}resolvePath(e,t){let n;return n=e.startsWith(`/`)?e:`${t.replace(/\/$/,``)}/${e}`,n.length>1&&(n=n.replace(/\/+$/,``)),n}usageError(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}help(){return{stdout:[`Usage: mount [OPTIONS] <target-path>`,` mount unmount [--clear-cache] <path>`,` mount list`,` mount --list`,` mount refresh [--bodies] <path>`,``,`Mount a local directory, S3 bucket, or AEM authoring source into the`,`virtual filesystem.`,``,`Without --source, opens a directory picker (local mount). With --source, mounts`,`a remote source (S3-compatible, da.live, or the Helix 6 Source Bus).`,``,`A da:// source is checked against the site config first: sites upgraded to`,`Helix 6 are re-routed to the Source Bus, because admin.da.live no longer`,`holds their content. Use --backend to force either endpoint.`,``,`Options:`,` --source <url> Remote source: s3://bucket[/prefix], da://org/repo,`,` or aem://org/site`,` --profile <name> Profile name (default: "default")`,` --backend <da|aem> Force the Adobe backend instead of probing the site config`,` --no-probe Skip the root-level probe on mount`,` --max-body-mb <n> Override body size limit (MB)`,``,`Sub-commands:`,` unmount [--clear-cache] <path> Remove a mount point`,` list, --list, -l Show active mount points`,` refresh [--bodies] <path> Re-index or revalidate a mount`,``,`Examples:`,` mount /mnt/myapp`,` mount --source s3://my-bucket --profile default /mnt/s3`,` mount --source da://my-org/my-repo /mnt/da`,` mount --source aem://my-org/my-site /mnt/aem`,` mount list`,` mount refresh /mnt/myapp`,` mount unmount /mnt/myapp`].join(`
|
|
1149
1149
|
`)+`
|
|
1150
|
-
`,stderr:``,exitCode:0}}};async function Mx(e){let t=`pendingMount:term:${e}`,n;try{n=await pee(t)}catch{return null}if(!n)return null;try{await mee(n)}catch{return null}return Qt.fromHandle(n,{mountId:on()})}var Nx=ar();globalThis.Buffer===void 0&&(globalThis.Buffer=Nx.Buffer);var Px=n(((e,t)=>{t.exports=typeof Object.create==`function`?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Fx=n(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Ix=n(((e,t)=>{t.exports=TypeError})),Lx=n(((e,t)=>{t.exports=Object})),Rx=n(((e,t)=>{t.exports=Error})),zx=n(((e,t)=>{t.exports=EvalError})),Bx=n(((e,t)=>{t.exports=RangeError})),Vx=n(((e,t)=>{t.exports=ReferenceError})),Hx=n(((e,t)=>{t.exports=SyntaxError})),Ux=n(((e,t)=>{t.exports=URIError})),Wx=n(((e,t)=>{t.exports=Math.abs})),Gx=n(((e,t)=>{t.exports=Math.floor})),Kx=n(((e,t)=>{t.exports=Math.max})),qx=n(((e,t)=>{t.exports=Math.min})),Jx=n(((e,t)=>{t.exports=Math.pow})),Yx=n(((e,t)=>{t.exports=Math.round})),Xx=n(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Zx=n(((e,t)=>{var n=Xx();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Qx=n(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),$x=n(((e,t)=>{var n=Qx();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),eS=n(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),tS=n(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),nS=n(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=tS();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),rS=n(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),iS=n(((e,t)=>{t.exports=Lx().getPrototypeOf||null})),aS=n(((e,t)=>{var n=Object.prototype.toString,r=Math.max,i=`[object Function]`,a=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},o=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},s=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||n.apply(t)!==i)throw TypeError(`Function.prototype.bind called on incompatible `+t);for(var c=o(arguments,1),l,u=function(){if(this instanceof l){var n=t.apply(this,a(c,arguments));return Object(n)===n?n:this}return t.apply(e,a(c,arguments))},d=r(0,t.length-c.length),f=[],p=0;p<d;p++)f[p]=`$`+p;if(l=Function(`binder`,`return function (`+s(f,`,`)+`){ return binder.apply(this,arguments); }`)(u),t.prototype){var m=function(){};m.prototype=t.prototype,l.prototype=new m,m.prototype=null}return l}})),oS=n(((e,t)=>{var n=aS();t.exports=Function.prototype.bind||n})),sS=n(((e,t)=>{t.exports=Function.prototype.call})),cS=n(((e,t)=>{t.exports=Function.prototype.apply})),lS=n(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),uS=n(((e,t)=>{var n=oS(),r=cS(),i=sS();t.exports=lS()||n.call(i,r)})),dS=n(((e,t)=>{var n=oS(),r=Ix(),i=sS(),a=uS();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),fS=n(((e,t)=>{var n=dS(),r=$x(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`&&function(e){return s(e==null?e:o(e))}})),pS=n(((e,t)=>{var n=rS(),r=iS(),i=fS();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),mS=n(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=oS().call(n,r)})),hS=n(((e,t)=>{var n,r=Lx(),i=Rx(),a=zx(),o=Bx(),s=Vx(),c=Hx(),l=Ix(),u=Ux(),d=Wx(),f=Gx(),p=Kx(),m=qx(),h=Jx(),g=Yx(),_=Zx(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=$x(),x=eS(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=nS()(),T=pS(),E=iS(),D=rS(),ee=cS(),te=sS(),ne={},re=typeof Uint8Array>`u`||!T?n:T(Uint8Array),O={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ne,"%AsyncGenerator%":ne,"%AsyncGeneratorFunction%":ne,"%AsyncIteratorPrototype%":ne,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ne,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":re,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":te,"%Function.prototype.apply%":ee,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){O[`%Error.prototype%`]=T(T(e))}var ie=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return O[t]=n,n},ae={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},oe=oS(),se=mS(),ce=oe.call(te,Array.prototype.concat),le=oe.call(ee,Array.prototype.splice),ue=oe.call(te,String.prototype.replace),de=oe.call(te,String.prototype.slice),k=oe.call(te,RegExp.prototype.exec),fe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,A=/\\(\\)?/g,j=function(e){var t=de(e,0,1),n=de(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return ue(e,fe,function(e,t,n,i){r[r.length]=n?ue(i,A,`$1`):t||e}),r},pe=function(e,t){var n=e,r;if(se(ae,n)&&(r=ae[n],n=`%`+r[0]+`%`),se(O,n)){var i=O[n];if(i===ne&&(i=ie(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(k(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=j(e),r=n.length>0?n[0]:``,i=pe(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],le(n,ce([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=de(p,0,1),h=de(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,se(O,a))o=O[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=se(o,p),o=o[p];f&&!s&&(O[a]=o)}}return o}})),gS=n(((e,t)=>{var n=hS(),r=dS(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),_S=n(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},"length",{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return!s(e)&&(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),vS=n(((e,t)=>{var n=_S(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),yS=n(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),bS=n(((e,t)=>{var n=yS(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),xS=n(((e,t)=>{var n=eS(),r=Hx(),i=Ix(),a=$x();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),SS=n(((e,t)=>{var n=eS(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),CS=n(((e,t)=>{var n=hS(),r=xS(),i=SS()(),a=$x(),o=Ix(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),wS=n(((e,t)=>{var n=oS(),r=cS(),i=uS();t.exports=function(){return i(n,r,arguments)}})),TS=n(((e,t)=>{var n=CS(),r=eS(),i=dS(),a=wS();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),ES=n(((e,t)=>{var n=tS();t.exports=function(){return n()&&!!Symbol.toStringTag}})),DS=n(((e,t)=>{var n=vS(),r=bS(),i=TS(),a=gS(),o=$x(),s=pS(),c=a(`Object.prototype.toString`),l=ES()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`&&g(e)}return o?h(e):null}})),OS=n(((e,t)=>{var n=DS();t.exports=function(e){return!!n(e)}})),kS=n(((e,t)=>{var n=Ix(),r=gS()(`TypedArray.prototype.buffer`,!0),i=OS();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),AS=n(((e,t)=>{var n=or().Buffer,r=Fx(),i=kS(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),jS=n(((e,t)=>{var n=or().Buffer,r=AS();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),MS=n(((e,t)=>{var n=Px(),r=jS(),i=or().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),NS=n(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,this.maxPending=e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?e.maxPending:n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),PS=n(((e,t)=>{t.exports=NS()})),FS=n((e=>{
|
|
1150
|
+
`,stderr:``,exitCode:0}}};async function Mx(e){let t=`pendingMount:term:${e}`,n;try{n=await pee(t)}catch{return null}if(!n)return null;try{await mee(n)}catch{return null}return Qt.fromHandle(n,{mountId:sn()})}var Nx=or();globalThis.Buffer===void 0&&(globalThis.Buffer=Nx.Buffer);var Px=n(((e,t)=>{t.exports=typeof Object.create==`function`?function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}})),Fx=n(((e,t)=>{var n={}.toString;t.exports=Array.isArray||function(e){return n.call(e)==`[object Array]`}})),Ix=n(((e,t)=>{t.exports=TypeError})),Lx=n(((e,t)=>{t.exports=Object})),Rx=n(((e,t)=>{t.exports=Error})),zx=n(((e,t)=>{t.exports=EvalError})),Bx=n(((e,t)=>{t.exports=RangeError})),Vx=n(((e,t)=>{t.exports=ReferenceError})),Hx=n(((e,t)=>{t.exports=SyntaxError})),Ux=n(((e,t)=>{t.exports=URIError})),Wx=n(((e,t)=>{t.exports=Math.abs})),Gx=n(((e,t)=>{t.exports=Math.floor})),Kx=n(((e,t)=>{t.exports=Math.max})),qx=n(((e,t)=>{t.exports=Math.min})),Jx=n(((e,t)=>{t.exports=Math.pow})),Yx=n(((e,t)=>{t.exports=Math.round})),Xx=n(((e,t)=>{t.exports=Number.isNaN||function(e){return e!==e}})),Zx=n(((e,t)=>{var n=Xx();t.exports=function(e){return n(e)||e===0?e:e<0?-1:1}})),Qx=n(((e,t)=>{t.exports=Object.getOwnPropertyDescriptor})),$x=n(((e,t)=>{var n=Qx();if(n)try{n([],`length`)}catch{n=null}t.exports=n})),eS=n(((e,t)=>{var n=Object.defineProperty||!1;if(n)try{n({},`a`,{value:1})}catch{n=!1}t.exports=n})),tS=n(((e,t)=>{t.exports=function(){if(typeof Symbol!=`function`||typeof Object.getOwnPropertySymbols!=`function`)return!1;if(typeof Symbol.iterator==`symbol`)return!0;var e={},t=Symbol(`test`),n=Object(t);if(typeof t==`string`||Object.prototype.toString.call(t)!==`[object Symbol]`||Object.prototype.toString.call(n)!==`[object Symbol]`)return!1;var r=42;for(var i in e[t]=r,e)return!1;if(typeof Object.keys==`function`&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames==`function`&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==t||!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if(typeof Object.getOwnPropertyDescriptor==`function`){var o=Object.getOwnPropertyDescriptor(e,t);if(o.value!==r||o.enumerable!==!0)return!1}return!0}})),nS=n(((e,t)=>{var n=typeof Symbol<`u`&&Symbol,r=tS();t.exports=function(){return typeof n!=`function`||typeof Symbol!=`function`||typeof n(`foo`)!=`symbol`||typeof Symbol(`bar`)!=`symbol`?!1:r()}})),rS=n(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect.getPrototypeOf||null})),iS=n(((e,t)=>{t.exports=Lx().getPrototypeOf||null})),aS=n(((e,t)=>{var n=Object.prototype.toString,r=Math.max,i=`[object Function]`,a=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n},o=function(e,t){for(var n=[],r=t||0,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n},s=function(e,t){for(var n=``,r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=t);return n};t.exports=function(e){var t=this;if(typeof t!=`function`||n.apply(t)!==i)throw TypeError(`Function.prototype.bind called on incompatible `+t);for(var c=o(arguments,1),l,u=function(){if(this instanceof l){var n=t.apply(this,a(c,arguments));return Object(n)===n?n:this}return t.apply(e,a(c,arguments))},d=r(0,t.length-c.length),f=[],p=0;p<d;p++)f[p]=`$`+p;if(l=Function(`binder`,`return function (`+s(f,`,`)+`){ return binder.apply(this,arguments); }`)(u),t.prototype){var m=function(){};m.prototype=t.prototype,l.prototype=new m,m.prototype=null}return l}})),oS=n(((e,t)=>{var n=aS();t.exports=Function.prototype.bind||n})),sS=n(((e,t)=>{t.exports=Function.prototype.call})),cS=n(((e,t)=>{t.exports=Function.prototype.apply})),lS=n(((e,t)=>{t.exports=typeof Reflect<`u`&&Reflect&&Reflect.apply})),uS=n(((e,t)=>{var n=oS(),r=cS(),i=sS();t.exports=lS()||n.call(i,r)})),dS=n(((e,t)=>{var n=oS(),r=Ix(),i=sS(),a=uS();t.exports=function(e){if(e.length<1||typeof e[0]!=`function`)throw new r(`a function is required`);return a(n,i,e)}})),fS=n(((e,t)=>{var n=dS(),r=$x(),i;try{i=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!=`object`||!(`code`in e)||e.code!==`ERR_PROTO_ACCESS`)throw e}var a=!!i&&r&&r(Object.prototype,`__proto__`),o=Object,s=o.getPrototypeOf;t.exports=a&&typeof a.get==`function`?n([a.get]):typeof s==`function`&&function(e){return s(e==null?e:o(e))}})),pS=n(((e,t)=>{var n=rS(),r=iS(),i=fS();t.exports=n?function(e){return n(e)}:r?function(e){if(!e||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`getProto: not an object`);return r(e)}:i?function(e){return i(e)}:null})),mS=n(((e,t)=>{var n=Function.prototype.call,r=Object.prototype.hasOwnProperty;t.exports=oS().call(n,r)})),hS=n(((e,t)=>{var n,r=Lx(),i=Rx(),a=zx(),o=Bx(),s=Vx(),c=Hx(),l=Ix(),u=Ux(),d=Wx(),f=Gx(),p=Kx(),m=qx(),h=Jx(),g=Yx(),_=Zx(),v=Function,y=function(e){try{return v(`"use strict"; return (`+e+`).constructor;`)()}catch{}},b=$x(),x=eS(),S=function(){throw new l},C=b?function(){try{return arguments.callee,S}catch{try{return b(arguments,`callee`).get}catch{return S}}}():S,w=nS()(),T=pS(),E=iS(),D=rS(),ee=cS(),te=sS(),ne={},re=typeof Uint8Array>`u`||!T?n:T(Uint8Array),O={__proto__:null,"%AggregateError%":typeof AggregateError>`u`?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>`u`?n:ArrayBuffer,"%ArrayIteratorPrototype%":w&&T?T([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":ne,"%AsyncGenerator%":ne,"%AsyncGeneratorFunction%":ne,"%AsyncIteratorPrototype%":ne,"%Atomics%":typeof Atomics>`u`?n:Atomics,"%BigInt%":typeof BigInt>`u`?n:BigInt,"%BigInt64Array%":typeof BigInt64Array>`u`?n:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>`u`?n:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>`u`?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":a,"%Float16Array%":typeof Float16Array>`u`?n:Float16Array,"%Float32Array%":typeof Float32Array>`u`?n:Float32Array,"%Float64Array%":typeof Float64Array>`u`?n:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>`u`?n:FinalizationRegistry,"%Function%":v,"%GeneratorFunction%":ne,"%Int8Array%":typeof Int8Array>`u`?n:Int8Array,"%Int16Array%":typeof Int16Array>`u`?n:Int16Array,"%Int32Array%":typeof Int32Array>`u`?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&T?T(T([][Symbol.iterator]())):n,"%JSON%":typeof JSON==`object`?JSON:n,"%Map%":typeof Map>`u`?n:Map,"%MapIteratorPrototype%":typeof Map>`u`||!w||!T?n:T(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":r,"%Object.getOwnPropertyDescriptor%":b,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>`u`?n:Promise,"%Proxy%":typeof Proxy>`u`?n:Proxy,"%RangeError%":o,"%ReferenceError%":s,"%Reflect%":typeof Reflect>`u`?n:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>`u`?n:Set,"%SetIteratorPrototype%":typeof Set>`u`||!w||!T?n:T(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>`u`?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&T?T(``[Symbol.iterator]()):n,"%Symbol%":w?Symbol:n,"%SyntaxError%":c,"%ThrowTypeError%":C,"%TypedArray%":re,"%TypeError%":l,"%Uint8Array%":typeof Uint8Array>`u`?n:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>`u`?n:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>`u`?n:Uint16Array,"%Uint32Array%":typeof Uint32Array>`u`?n:Uint32Array,"%URIError%":u,"%WeakMap%":typeof WeakMap>`u`?n:WeakMap,"%WeakRef%":typeof WeakRef>`u`?n:WeakRef,"%WeakSet%":typeof WeakSet>`u`?n:WeakSet,"%Function.prototype.call%":te,"%Function.prototype.apply%":ee,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":d,"%Math.floor%":f,"%Math.max%":p,"%Math.min%":m,"%Math.pow%":h,"%Math.round%":g,"%Math.sign%":_,"%Reflect.getPrototypeOf%":D};if(T)try{null.error}catch(e){O[`%Error.prototype%`]=T(T(e))}var ie=function e(t){var n;if(t===`%AsyncFunction%`)n=y(`async function () {}`);else if(t===`%GeneratorFunction%`)n=y(`function* () {}`);else if(t===`%AsyncGeneratorFunction%`)n=y(`async function* () {}`);else if(t===`%AsyncGenerator%`){var r=e(`%AsyncGeneratorFunction%`);r&&(n=r.prototype)}else if(t===`%AsyncIteratorPrototype%`){var i=e(`%AsyncGenerator%`);i&&T&&(n=T(i.prototype))}return O[t]=n,n},ae={__proto__:null,"%ArrayBufferPrototype%":[`ArrayBuffer`,`prototype`],"%ArrayPrototype%":[`Array`,`prototype`],"%ArrayProto_entries%":[`Array`,`prototype`,`entries`],"%ArrayProto_forEach%":[`Array`,`prototype`,`forEach`],"%ArrayProto_keys%":[`Array`,`prototype`,`keys`],"%ArrayProto_values%":[`Array`,`prototype`,`values`],"%AsyncFunctionPrototype%":[`AsyncFunction`,`prototype`],"%AsyncGenerator%":[`AsyncGeneratorFunction`,`prototype`],"%AsyncGeneratorPrototype%":[`AsyncGeneratorFunction`,`prototype`,`prototype`],"%BooleanPrototype%":[`Boolean`,`prototype`],"%DataViewPrototype%":[`DataView`,`prototype`],"%DatePrototype%":[`Date`,`prototype`],"%ErrorPrototype%":[`Error`,`prototype`],"%EvalErrorPrototype%":[`EvalError`,`prototype`],"%Float32ArrayPrototype%":[`Float32Array`,`prototype`],"%Float64ArrayPrototype%":[`Float64Array`,`prototype`],"%FunctionPrototype%":[`Function`,`prototype`],"%Generator%":[`GeneratorFunction`,`prototype`],"%GeneratorPrototype%":[`GeneratorFunction`,`prototype`,`prototype`],"%Int8ArrayPrototype%":[`Int8Array`,`prototype`],"%Int16ArrayPrototype%":[`Int16Array`,`prototype`],"%Int32ArrayPrototype%":[`Int32Array`,`prototype`],"%JSONParse%":[`JSON`,`parse`],"%JSONStringify%":[`JSON`,`stringify`],"%MapPrototype%":[`Map`,`prototype`],"%NumberPrototype%":[`Number`,`prototype`],"%ObjectPrototype%":[`Object`,`prototype`],"%ObjProto_toString%":[`Object`,`prototype`,`toString`],"%ObjProto_valueOf%":[`Object`,`prototype`,`valueOf`],"%PromisePrototype%":[`Promise`,`prototype`],"%PromiseProto_then%":[`Promise`,`prototype`,`then`],"%Promise_all%":[`Promise`,`all`],"%Promise_reject%":[`Promise`,`reject`],"%Promise_resolve%":[`Promise`,`resolve`],"%RangeErrorPrototype%":[`RangeError`,`prototype`],"%ReferenceErrorPrototype%":[`ReferenceError`,`prototype`],"%RegExpPrototype%":[`RegExp`,`prototype`],"%SetPrototype%":[`Set`,`prototype`],"%SharedArrayBufferPrototype%":[`SharedArrayBuffer`,`prototype`],"%StringPrototype%":[`String`,`prototype`],"%SymbolPrototype%":[`Symbol`,`prototype`],"%SyntaxErrorPrototype%":[`SyntaxError`,`prototype`],"%TypedArrayPrototype%":[`TypedArray`,`prototype`],"%TypeErrorPrototype%":[`TypeError`,`prototype`],"%Uint8ArrayPrototype%":[`Uint8Array`,`prototype`],"%Uint8ClampedArrayPrototype%":[`Uint8ClampedArray`,`prototype`],"%Uint16ArrayPrototype%":[`Uint16Array`,`prototype`],"%Uint32ArrayPrototype%":[`Uint32Array`,`prototype`],"%URIErrorPrototype%":[`URIError`,`prototype`],"%WeakMapPrototype%":[`WeakMap`,`prototype`],"%WeakSetPrototype%":[`WeakSet`,`prototype`]},oe=oS(),se=mS(),ce=oe.call(te,Array.prototype.concat),le=oe.call(ee,Array.prototype.splice),ue=oe.call(te,String.prototype.replace),de=oe.call(te,String.prototype.slice),k=oe.call(te,RegExp.prototype.exec),fe=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,A=/\\(\\)?/g,j=function(e){var t=de(e,0,1),n=de(e,-1);if(t===`%`&&n!==`%`)throw new c("invalid intrinsic syntax, expected closing `%`");if(n===`%`&&t!==`%`)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return ue(e,fe,function(e,t,n,i){r[r.length]=n?ue(i,A,`$1`):t||e}),r},pe=function(e,t){var n=e,r;if(se(ae,n)&&(r=ae[n],n=`%`+r[0]+`%`),se(O,n)){var i=O[n];if(i===ne&&(i=ie(n)),i===void 0&&!t)throw new l(`intrinsic `+e+` exists, but is not available. Please file an issue!`);return{alias:r,name:n,value:i}}throw new c(`intrinsic `+e+` does not exist!`)};t.exports=function(e,t){if(typeof e!=`string`||e.length===0)throw new l(`intrinsic name must be a non-empty string`);if(arguments.length>1&&typeof t!=`boolean`)throw new l(`"allowMissing" argument must be a boolean`);if(k(/^%?[^%]*%?$/,e)===null)throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=j(e),r=n.length>0?n[0]:``,i=pe(`%`+r+`%`,t),a=i.name,o=i.value,s=!1,u=i.alias;u&&(r=u[0],le(n,ce([0,1],u)));for(var d=1,f=!0;d<n.length;d+=1){var p=n[d],m=de(p,0,1),h=de(p,-1);if((m===`"`||m===`'`||m==="`"||h===`"`||h===`'`||h==="`")&&m!==h)throw new c(`property names with quotes must have matching quotes`);if((p===`constructor`||!f)&&(s=!0),r+=`.`+p,a=`%`+r+`%`,se(O,a))o=O[a];else if(o!=null){if(!(p in o)){if(!t)throw new l(`base intrinsic for `+e+` exists, but the property is not available.`);return}if(b&&d+1>=n.length){var g=b(o,p);f=!!g,o=f&&`get`in g&&!(`originalValue`in g.get)?g.get:o[p]}else f=se(o,p),o=o[p];f&&!s&&(O[a]=o)}}return o}})),gS=n(((e,t)=>{var n=hS(),r=dS(),i=r([n(`%String.prototype.indexOf%`)]);t.exports=function(e,t){var a=n(e,!!t);return typeof a==`function`&&i(e,`.prototype.`)>-1?r([a]):a}})),_S=n(((e,t)=>{var n=Function.prototype.toString,r=typeof Reflect==`object`&&Reflect!==null&&Reflect.apply,i,a;if(typeof r==`function`&&typeof Object.defineProperty==`function`)try{i=Object.defineProperty({},"length",{get:function(){throw a}}),a={},r(function(){throw 42},null,i)}catch(e){e!==a&&(r=null)}else r=null;var o=/^\s*class\b/,s=function(e){try{var t=n.call(e);return o.test(t)}catch{return!1}},c=function(e){try{return!s(e)&&(n.call(e),!0)}catch{return!1}},l=Object.prototype.toString,u=`[object Object]`,d=`[object Function]`,f=`[object GeneratorFunction]`,p=`[object HTMLAllCollection]`,m=`[object HTML document.all class]`,h=`[object HTMLCollection]`,g=typeof Symbol==`function`&&!!Symbol.toStringTag,_=!(0 in[,]),v=function(){return!1};if(typeof document==`object`){var y=document.all;l.call(y)===l.call(document.all)&&(v=function(e){if((_||!e)&&(e===void 0||typeof e==`object`))try{var t=l.call(e);return(t===p||t===m||t===h||t===u)&&e(``)==null}catch{}return!1})}t.exports=r?function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;try{r(e,null,i)}catch(e){if(e!==a)return!1}return!s(e)&&c(e)}:function(e){if(v(e))return!0;if(!e||typeof e!=`function`&&typeof e!=`object`)return!1;if(g)return c(e);if(s(e))return!1;var t=l.call(e);return t!==d&&t!==f&&!/^\[object HTML/.test(t)?!1:c(e)}})),vS=n(((e,t)=>{var n=_S(),r=Object.prototype.toString,i=Object.prototype.hasOwnProperty,a=function(e,t,n){for(var r=0,a=e.length;r<a;r++)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))},o=function(e,t,n){for(var r=0,i=e.length;r<i;r++)n==null?t(e.charAt(r),r,e):t.call(n,e.charAt(r),r,e)},s=function(e,t,n){for(var r in e)i.call(e,r)&&(n==null?t(e[r],r,e):t.call(n,e[r],r,e))};function c(e){return r.call(e)===`[object Array]`}t.exports=function(e,t,r){if(!n(t))throw TypeError(`iterator must be a function`);var i;arguments.length>=3&&(i=r),c(e)?a(e,t,i):typeof e==`string`?o(e,t,i):s(e,t,i)}})),yS=n(((e,t)=>{t.exports=[`Float16Array`,`Float32Array`,`Float64Array`,`Int8Array`,`Int16Array`,`Int32Array`,`Uint8Array`,`Uint8ClampedArray`,`Uint16Array`,`Uint32Array`,`BigInt64Array`,`BigUint64Array`]})),bS=n(((e,t)=>{var n=yS(),r=globalThis;t.exports=function(){for(var e=[],t=0;t<n.length;t++)typeof r[n[t]]==`function`&&(e[e.length]=n[t]);return e}})),xS=n(((e,t)=>{var n=eS(),r=Hx(),i=Ix(),a=$x();t.exports=function(e,t,o){if(!e||typeof e!=`object`&&typeof e!=`function`)throw new i("`obj` must be an object or a function`");if(typeof t!=`string`&&typeof t!=`symbol`)throw new i("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=`boolean`&&arguments[3]!==null)throw new i("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=`boolean`&&arguments[4]!==null)throw new i("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=`boolean`&&arguments[5]!==null)throw new i("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=`boolean`)throw new i("`loose`, if provided, must be a boolean");var s=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,u=arguments.length>6&&arguments[6],d=!!a&&a(e,t);if(n)n(e,t,{configurable:l===null&&d?d.configurable:!l,enumerable:s===null&&d?d.enumerable:!s,value:o,writable:c===null&&d?d.writable:!c});else if(u||!s&&!c&&!l)e[t]=o;else throw new r(`This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.`)}})),SS=n(((e,t)=>{var n=eS(),r=function(){return!!n};r.hasArrayLengthDefineBug=function(){if(!n)return null;try{return n([],`length`,{value:1}).length!==1}catch{return!0}},t.exports=r})),CS=n(((e,t)=>{var n=hS(),r=xS(),i=SS()(),a=$x(),o=Ix(),s=n(`%Math.floor%`);t.exports=function(e,t){if(typeof e!=`function`)throw new o("`fn` is not a function");if(typeof t!=`number`||t<0||t>4294967295||s(t)!==t)throw new o("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],c=!0,l=!0;if(`length`in e&&a){var u=a(e,`length`);u&&!u.configurable&&(c=!1),u&&!u.writable&&(l=!1)}return(c||l||!n)&&(i?r(e,`length`,t,!0,!0):r(e,`length`,t)),e}})),wS=n(((e,t)=>{var n=oS(),r=cS(),i=uS();t.exports=function(){return i(n,r,arguments)}})),TS=n(((e,t)=>{var n=CS(),r=eS(),i=dS(),a=wS();t.exports=function(e){var t=i(arguments),r=e.length-(arguments.length-1);return n(t,1+(r>0?r:0),!0)},r?r(t.exports,`apply`,{value:a}):t.exports.apply=a})),ES=n(((e,t)=>{var n=tS();t.exports=function(){return n()&&!!Symbol.toStringTag}})),DS=n(((e,t)=>{var n=vS(),r=bS(),i=TS(),a=gS(),o=$x(),s=pS(),c=a(`Object.prototype.toString`),l=ES()(),u=globalThis,d=r(),f=a(`String.prototype.slice`),p=a(`Array.prototype.indexOf`,!0)||function(e,t){for(var n=0;n<e.length;n+=1)if(e[n]===t)return n;return-1},m={__proto__:null};l&&o&&s?n(d,function(e){var t=new u[e];if(Symbol.toStringTag in t&&s){var n=s(t),r=o(n,Symbol.toStringTag);if(!r&&n&&(r=o(s(n),Symbol.toStringTag)),r&&r.get){var a=i(r.get);m[`$`+e]=a}}}):n(d,function(e){var t=new u[e],n=t.slice||t.set;if(n){var r=i(n);m[`$`+e]=r}});var h=function(e){var t=!1;return n(m,function(n,r){if(!t)try{`$`+n(e)===r&&(t=f(r,1))}catch{}}),t},g=function(e){var t=!1;return n(m,function(n,r){if(!t)try{n(e),t=f(r,1)}catch{}}),t};t.exports=function(e){if(!e||typeof e!=`object`)return!1;if(!l){var t=f(c(e),8,-1);return p(d,t)>-1?t:t===`Object`&&g(e)}return o?h(e):null}})),OS=n(((e,t)=>{var n=DS();t.exports=function(e){return!!n(e)}})),kS=n(((e,t)=>{var n=Ix(),r=gS()(`TypedArray.prototype.buffer`,!0),i=OS();t.exports=r||function(e){if(!i(e))throw new n(`Not a Typed Array`);return e.buffer}})),AS=n(((e,t)=>{var n=sr().Buffer,r=Fx(),i=kS(),a=ArrayBuffer.isView||function(e){try{return i(e),!0}catch{return!1}},o=typeof Uint8Array<`u`,s=typeof ArrayBuffer<`u`&&typeof Uint8Array<`u`,c=s&&(n.prototype instanceof Uint8Array||n.TYPED_ARRAY_SUPPORT);t.exports=function(e,t){if(n.isBuffer(e))return e.constructor&&!(`isBuffer`in e)?n.from(e):e;if(typeof e==`string`)return n.from(e,t);if(s&&a(e)){if(e.byteLength===0)return n.alloc(0);if(c){var i=n.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var l=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),u=n.from(l);if(u.length===e.byteLength)return u}if(o&&e instanceof Uint8Array)return n.from(e);var d=r(e);if(d)for(var f=0;f<e.length;f+=1){var p=e[f];if(typeof p!=`number`||p<0||p>255||~~p!==p)throw RangeError(`Array items must be numbers in the range 0-255.`)}if(d||n.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer==`function`&&e.constructor.isBuffer(e))return n.from(e);throw TypeError(`The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.`)}})),jS=n(((e,t)=>{var n=sr().Buffer,r=AS();function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){e=r(e,t||`utf8`);for(var n=this._block,i=this._blockSize,a=e.length,o=this._len,s=0;s<a;){for(var c=o%i,l=Math.min(a-s,i-c),u=0;u<l;u++)n[c+u]=e[s+u];o+=l,s+=l,o%i===0&&this._update(n)}return this._len+=a,this},i.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var n=this._len*8;if(n<=4294967295)this._block.writeUInt32BE(n,this._blockSize-4);else{var r=(n&4294967295)>>>0,i=(n-r)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(r,this._blockSize-4)}this._update(this._block);var a=this._hash();return e?a.toString(e):a},i.prototype._update=function(){throw Error(`_update must be implemented by subclass`)},t.exports=i})),MS=n(((e,t)=>{var n=Px(),r=jS(),i=sr().Buffer,a=[1518500249,1859775393,-1894007588,-899497514],o=Array(80);function s(){this.init(),this._w=o,r.call(this,64,56)}n(s,r),s.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function c(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function d(e,t,n,r){return e===0?t&n|~t&r:e===2?t&n|t&r|n&r:t^n^r}s.prototype._update=function(e){for(var t=this._w,n=this._a|0,r=this._b|0,i=this._c|0,o=this._d|0,s=this._e|0,f=0;f<16;++f)t[f]=e.readInt32BE(f*4);for(;f<80;++f)t[f]=c(t[f-3]^t[f-8]^t[f-14]^t[f-16]);for(var p=0;p<80;++p){var m=~~(p/20),h=l(n)+d(m,r,i,o)+s+t[p]+a[m]|0;s=o,o=i,i=u(r),r=n,n=h}this._a=n+this._a|0,this._b=r+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},s.prototype._hash=function(){var e=i.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e},t.exports=s})),NS=n(((e,t)=>{var n=function(e){if(e||={},this.Promise=e.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=e.domainReentrant||!1,this.domainReentrant){if(typeof process>`u`||process.domain===void 0)throw Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=e.timeout||n.DEFAULT_TIMEOUT,this.maxOccupationTime=e.maxOccupationTime||n.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=e.maxExecutionTime||n.DEFAULT_MAX_EXECUTION_TIME,this.maxPending=e.maxPending===1/0||Number.isInteger(e.maxPending)&&e.maxPending>=0?e.maxPending:n.DEFAULT_MAX_PENDING};n.DEFAULT_TIMEOUT=0,n.DEFAULT_MAX_OCCUPATION_TIME=0,n.DEFAULT_MAX_EXECUTION_TIME=0,n.DEFAULT_MAX_PENDING=1e3,n.prototype.acquire=function(e,t,n,r){if(Array.isArray(e))return this._acquireBatch(e,t,n,r);if(typeof t!=`function`)throw Error(`You must pass a function to execute`);var i=null,a=null,o=null;typeof n!=`function`&&(r=n,n=null,o=new this.Promise(function(e,t){i=e,a=t})),r||={};var s=!1,c=null,l=null,u=null,d=this,f=function(t,r,c){l&&=(clearTimeout(l),null),u&&=(clearTimeout(u),null),t&&(d.queues[e]&&d.queues[e].length===0&&delete d.queues[e],d.domainReentrant&&delete d.domains[e]),s||=(o?r?a(r):i(c):typeof n==`function`&&n(r,c),!0),t&&d.queues[e]&&d.queues[e].length>0&&d.queues[e].shift()()},p=function(n){if(s)return f(n);c&&=(clearTimeout(c),null),d.domainReentrant&&n&&(d.domains[e]=process.domain);var i=r.maxExecutionTime||d.maxExecutionTime;if(i&&(u=setTimeout(function(){d.queues[e]&&f(n,Error(`Maximum execution time is exceeded `+e))},i)),t.length===1){var a=!1;try{t(function(e,t){a||(a=!0,f(n,e,t))})}catch(e){a||(a=!0,f(n,e))}}else d._promiseTry(function(){return t()}).then(function(e){f(n,void 0,e)},function(e){f(n,e)})};d.domainReentrant&&process.domain&&(p=process.domain.bind(p));var m=r.maxPending||d.maxPending;if(!d.queues[e])d.queues[e]=[],p(!0);else if(d.domainReentrant&&process.domain&&process.domain===d.domains[e])p(!1);else if(d.queues[e].length>=m)f(!1,Error(`Too many pending tasks in queue `+e));else{var h=function(){p(!0)};r.skipQueue?d.queues[e].unshift(h):d.queues[e].push(h);var g=r.timeout||d.timeout;g&&(c=setTimeout(function(){c=null,f(!1,Error(`async-lock timed out in queue `+e))},g))}var _=r.maxOccupationTime||d.maxOccupationTime;if(_&&(l=setTimeout(function(){d.queues[e]&&f(!1,Error(`Maximum occupation time is exceeded in queue `+e))},_)),o)return o},n.prototype._acquireBatch=function(e,t,n,r){typeof n!=`function`&&(r=n,n=null);var i=this,a=function(e,t){return function(n){i.acquire(e,t,n,r)}},o=e.reduceRight(function(e,t){return a(t,e)},t);if(typeof n==`function`)o(n);else return new this.Promise(function(e,t){o.length===1?o(function(n,r){n?t(n):e(r)}):e(o())})},n.prototype.isBusy=function(e){return e?!!this.queues[e]:Object.keys(this.queues).length>0},n.prototype._promiseTry=function(e){try{return this.Promise.resolve(e())}catch(e){return this.Promise.reject(e)}},t.exports=n})),PS=n(((e,t)=>{t.exports=NS()})),FS=n((e=>{
|
|
1151
1151
|
/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */
|
|
1152
1152
|
(function(t){typeof DO_NOT_EXPORT_CRC>`u`?typeof e==`object`?t(e):typeof define==`function`&&define.amd?define(function(){var e={};return t(e),e}):t({}):t({})})(function(e){e.version=`1.2.2`;function t(){for(var e=0,t=Array(256),n=0;n!=256;++n)e=n,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,e=e&1?-306674912^e>>>1:e>>>1,t[n]=e;return typeof Int32Array<`u`?new Int32Array(t):t}var n=t();function r(e){var t=0,n=0,r=0,i=typeof Int32Array<`u`?new Int32Array(4096):Array(4096);for(r=0;r!=256;++r)i[r]=e[r];for(r=0;r!=256;++r)for(n=e[r],t=256+r;t<4096;t+=256)n=i[t]=n>>>8^e[n&255];var a=[];for(r=1;r!=16;++r)a[r-1]=typeof Int32Array<`u`?i.subarray(r*256,r*256+256):i.slice(r*256,r*256+256);return a}var i=r(n),a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14];function b(e,t){for(var r=t^-1,i=0,a=e.length;i<a;)r=r>>>8^n[(r^e.charCodeAt(i++))&255];return~r}function x(e,t){for(var r=t^-1,i=e.length-15,b=0;b<i;)r=y[e[b++]^r&255]^v[e[b++]^r>>8&255]^_[e[b++]^r>>16&255]^g[e[b++]^r>>>24]^h[e[b++]]^m[e[b++]]^p[e[b++]]^f[e[b++]]^d[e[b++]]^u[e[b++]]^l[e[b++]]^c[e[b++]]^s[e[b++]]^o[e[b++]]^a[e[b++]]^n[e[b++]];for(i+=15;b<i;)r=r>>>8^n[(r^e[b++])&255];return~r}function S(e,t){for(var r=t^-1,i=0,a=e.length,o=0,s=0;i<a;)o=e.charCodeAt(i++),o<128?r=r>>>8^n[(r^o)&255]:o<2048?(r=r>>>8^n[(r^(192|o>>6&31))&255],r=r>>>8^n[(r^(128|o&63))&255]):o>=55296&&o<57344?(o=(o&1023)+64,s=e.charCodeAt(i++)&1023,r=r>>>8^n[(r^(240|o>>8&7))&255],r=r>>>8^n[(r^(128|o>>2&63))&255],r=r>>>8^n[(r^(128|s>>6&15|(o&3)<<4))&255],r=r>>>8^n[(r^(128|s&63))&255]):(r=r>>>8^n[(r^(224|o>>12&15))&255],r=r>>>8^n[(r^(128|o>>6&63))&255],r=r>>>8^n[(r^(128|o&63))&255]);return~r}e.table=n,e.bstr=b,e.buf=x,e.str=S})})),IS=n((e=>{var t=typeof Uint8Array<`u`&&typeof Uint16Array<`u`&&typeof Int32Array<`u`;function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!=`object`)throw TypeError(r+`must be non-object`);for(var i in r)n(r,i)&&(e[i]=r[i])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,n,r,i){if(t.subarray&&e.subarray){e.set(t.subarray(n,n+r),i);return}for(var a=0;a<r;a++)e[i+a]=t[n+a]},flattenChunks:function(e){var t,n,r=0,i,a,o;for(t=0,n=e.length;t<n;t++)r+=e[t].length;for(o=new Uint8Array(r),i=0,t=0,n=e.length;t<n;t++)a=e[t],o.set(a,i),i+=a.length;return o}},i={arraySet:function(e,t,n,r,i){for(var a=0;a<r;a++)e[i+a]=t[n+a]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,r)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,i))},e.setTyped(t)})),LS=n((e=>{var t=IS(),n=4,r=0,i=1,a=2;function o(e){for(var t=e.length;--t>=0;)e[t]=0}var s=0,c=1,l=2,u=3,d=258,f=29,p=256,m=p+1+f,h=30,g=19,_=2*m+1,v=15,y=16,b=7,x=256,S=16,C=17,w=18,T=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],E=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],D=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ee=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],te=512,ne=Array((m+2)*2);o(ne);var re=Array(h*2);o(re);var O=Array(te);o(O);var ie=Array(d-u+1);o(ie);var ae=Array(f);o(ae);var oe=Array(h);o(oe);function se(e,t,n,r,i){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=e&&e.length}var ce,le,ue;function de(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function k(e){return e<256?O[e]:O[256+(e>>>7)]}function fe(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function A(e,t,n){e.bi_valid>y-n?(e.bi_buf|=t<<e.bi_valid&65535,fe(e,e.bi_buf),e.bi_buf=t>>y-e.bi_valid,e.bi_valid+=n-y):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)}function j(e,t,n){A(e,n[t*2],n[t*2+1])}function pe(e,t){var n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1}function me(e){e.bi_valid===16?(fe(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function he(e,t){var n=t.dyn_tree,r=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,u,d,f,p,m,h=0;for(f=0;f<=v;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<_;l++)u=e.heap[l],f=n[n[u*2+1]*2+1]+1,f>c&&(f=c,h++),n[u*2+1]=f,!(u>r)&&(e.bl_count[f]++,p=0,u>=s&&(p=o[u-s]),m=n[u*2],e.opt_len+=m*(f+p),a&&(e.static_len+=m*(i[u*2+1]+p)));if(h!==0){do{for(f=c-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(f=c;f!==0;f--)for(u=e.bl_count[f];u!==0;)d=e.heap[--l],!(d>r)&&(n[d*2+1]!==f&&(e.opt_len+=(f-n[d*2+1])*n[d*2],n[d*2+1]=f),u--)}}function ge(e,t,n){var r=Array(v+1),i=0,a,o;for(a=1;a<=v;a++)r[a]=i=i+n[a-1]<<1;for(o=0;o<=t;o++){var s=e[o*2+1];s!==0&&(e[o*2]=pe(r[s]++,s))}}function _e(){var e,t,n,r,i,a=Array(v+1);for(n=0,r=0;r<f-1;r++)for(ae[r]=n,e=0;e<1<<T[r];e++)ie[n++]=r;for(ie[n-1]=r,i=0,r=0;r<16;r++)for(oe[r]=i,e=0;e<1<<E[r];e++)O[i++]=r;for(i>>=7;r<h;r++)for(oe[r]=i<<7,e=0;e<1<<E[r]-7;e++)O[256+i++]=r;for(t=0;t<=v;t++)a[t]=0;for(e=0;e<=143;)ne[e*2+1]=8,e++,a[8]++;for(;e<=255;)ne[e*2+1]=9,e++,a[9]++;for(;e<=279;)ne[e*2+1]=7,e++,a[7]++;for(;e<=287;)ne[e*2+1]=8,e++,a[8]++;for(ge(ne,m+1,a),e=0;e<h;e++)re[e*2+1]=5,re[e*2]=pe(e,5);ce=new se(ne,T,p+1,m,v),le=new se(re,E,0,h,v),ue=new se([],D,0,g,b)}function ve(e){var t;for(t=0;t<m;t++)e.dyn_ltree[t*2]=0;for(t=0;t<h;t++)e.dyn_dtree[t*2]=0;for(t=0;t<g;t++)e.bl_tree[t*2]=0;e.dyn_ltree[x*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function ye(e){e.bi_valid>8?fe(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function be(e,n,r,i){ye(e),i&&(fe(e,r),fe(e,~r)),t.arraySet(e.pending_buf,e.window,n,r,e.pending),e.pending+=r}function M(e,t,n,r){var i=t*2,a=n*2;return e[i]<e[a]||e[i]===e[a]&&r[t]<=r[n]}function N(e,t,n){for(var r=e.heap[n],i=n<<1;i<=e.heap_len&&(i<e.heap_len&&M(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!M(t,r,e.heap[i],e.depth));)e.heap[n]=e.heap[i],n=i,i<<=1;e.heap[n]=r}function xe(e,t,n){var r,i,a=0,o,s;if(e.last_lit!==0)do r=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],i=e.pending_buf[e.l_buf+a],a++,r===0?j(e,i,t):(o=ie[i],j(e,o+p+1,t),s=T[o],s!==0&&(i-=ae[o],A(e,i,s)),r--,o=k(r),j(e,o,n),s=E[o],s!==0&&(r-=oe[o],A(e,r,s)));while(a<e.last_lit);j(e,x,t)}function Se(e,t){var n=t.dyn_tree,r=t.stat_desc.static_tree,i=t.stat_desc.has_stree,a=t.stat_desc.elems,o,s,c=-1,l;for(e.heap_len=0,e.heap_max=_,o=0;o<a;o++)n[o*2]===0?n[o*2+1]=0:(e.heap[++e.heap_len]=c=o,e.depth[o]=0);for(;e.heap_len<2;)l=e.heap[++e.heap_len]=c<2?++c:0,n[l*2]=1,e.depth[l]=0,e.opt_len--,i&&(e.static_len-=r[l*2+1]);for(t.max_code=c,o=e.heap_len>>1;o>=1;o--)N(e,n,o);l=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],N(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[l*2]=n[o*2]+n[s*2],e.depth[l]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[o*2+1]=n[s*2+1]=l,e.heap[1]=l++,N(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],he(e,t),ge(n,c,e.bl_count)}function P(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)&&(s<l?e.bl_tree[a*2]+=s:a===0?s<=10?e.bl_tree[C*2]++:e.bl_tree[w*2]++:(a!==i&&e.bl_tree[a*2]++,e.bl_tree[S*2]++),s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4))}function Ce(e,t,n){var r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),r=0;r<=n;r++)if(a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)){if(s<l)do j(e,a,e.bl_tree);while(--s!==0);else a===0?s<=10?(j(e,C,e.bl_tree),A(e,s-3,3)):(j(e,w,e.bl_tree),A(e,s-11,7)):(a!==i&&(j(e,a,e.bl_tree),s--),j(e,S,e.bl_tree),A(e,s-3,2));s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4)}}function F(e){var t;for(P(e,e.dyn_ltree,e.l_desc.max_code),P(e,e.dyn_dtree,e.d_desc.max_code),Se(e,e.bl_desc),t=g-1;t>=3&&e.bl_tree[ee[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function we(e,t,n,r){var i;for(A(e,t-257,5),A(e,n-1,5),A(e,r-4,4),i=0;i<r;i++)A(e,e.bl_tree[ee[i]*2+1],3);Ce(e,e.dyn_ltree,t-1),Ce(e,e.dyn_dtree,n-1)}function I(e){var t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return r;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return i;for(n=32;n<p;n++)if(e.dyn_ltree[n*2]!==0)return i;return r}var L=!1;function Te(e){L||=(_e(),!0),e.l_desc=new de(e.dyn_ltree,ce),e.d_desc=new de(e.dyn_dtree,le),e.bl_desc=new de(e.bl_tree,ue),e.bi_buf=0,e.bi_valid=0,ve(e)}function Ee(e,t,n,r){A(e,(s<<1)+ +!!r,3),be(e,t,n,!0)}function De(e){A(e,c<<1,3),j(e,x,ne),me(e)}function Oe(e,t,r,i){var o,s,u=0;e.level>0?(e.strm.data_type===a&&(e.strm.data_type=I(e)),Se(e,e.l_desc),Se(e,e.d_desc),u=F(e),o=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=o&&(o=s)):o=s=r+5,r+4<=o&&t!==-1?Ee(e,t,r,i):e.strategy===n||s===o?(A(e,(c<<1)+ +!!i,3),xe(e,ne,re)):(A(e,(l<<1)+ +!!i,3),we(e,e.l_desc.max_code+1,e.d_desc.max_code+1,u+1),xe(e,e.dyn_ltree,e.dyn_dtree)),ve(e),i&&ye(e)}function R(e,t,n){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=n&255,e.last_lit++,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(ie[n]+p+1)*2]++,e.dyn_dtree[k(t)*2]++),e.last_lit===e.lit_bufsize-1}e._tr_init=Te,e._tr_stored_block=Ee,e._tr_flush_block=Oe,e._tr_tally=R,e._tr_align=De})),RS=n(((e,t)=>{function n(e,t,n,r){for(var i=e&65535|0,a=e>>>16&65535|0,o=0;n!==0;){o=n>2e3?2e3:n,n-=o;do i=i+t[r++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0}t.exports=n})),zS=n(((e,t)=>{function n(){for(var e,t=[],n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t}var r=n();function i(e,t,n,i){var a=r,o=i+n;e^=-1;for(var s=i;s<o;s++)e=e>>>8^a[(e^t[s])&255];return e^-1}t.exports=i})),BS=n(((e,t)=>{t.exports={2:`need dictionary`,1:`stream end`,0:``,"-1":`file error`,"-2":`stream error`,"-3":`data error`,"-4":`insufficient memory`,"-5":`buffer error`,"-6":`incompatible version`}})),VS=n((e=>{var t=IS(),n=LS(),r=RS(),i=zS(),a=BS(),o=0,s=1,c=3,l=4,u=5,d=0,f=1,p=-2,m=-3,h=-5,g=-1,_=1,v=2,y=3,b=4,x=0,S=2,C=8,w=9,T=15,E=8,D=286,ee=30,te=19,ne=2*D+1,re=15,O=3,ie=258,ae=ie+O+1,oe=32,se=42,ce=69,le=73,ue=91,de=103,k=113,fe=666,A=1,j=2,pe=3,me=4,he=3;function ge(e,t){return e.msg=a[t],t}function _e(e){return(e<<1)-(e>4?9:0)}function ve(e){for(var t=e.length;--t>=0;)e[t]=0}function ye(e){var n=e.state,r=n.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(t.arraySet(e.output,n.pending_buf,n.pending_out,r,e.next_out),e.next_out+=r,n.pending_out+=r,e.total_out+=r,e.avail_out-=r,n.pending-=r,n.pending===0&&(n.pending_out=0))}function be(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ye(e.strm)}function M(e,t){e.pending_buf[e.pending++]=t}function N(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function xe(e,n,a,o){var s=e.avail_in;return s>o&&(s=o),s===0?0:(e.avail_in-=s,t.arraySet(n,e.input,e.next_in,s,a),e.state.wrap===1?e.adler=r(e.adler,n,s,a):e.state.wrap===2&&(e.adler=i(e.adler,n,s,a)),e.next_in+=s,e.total_in+=s,s)}function Se(e,t){var n=e.max_chain_length,r=e.strstart,i,a,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-ae?e.strstart-(e.w_size-ae):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+ie,p=l[r+o-1],m=l[r+o];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do{if(i=t,l[i+o]!==m||l[i+o-1]!==p||l[i]!==l[r]||l[++i]!==l[r+1])continue;r+=2,i++;do;while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<f);if(a=ie-(f-r),r=f-ie,a>o){if(e.match_start=t,o=a,a>=s)break;p=l[r+o-1],m=l[r+o]}}while((t=d[t&u])>c&&--n!==0);return o<=e.lookahead?o:e.lookahead}function P(e){var n=e.w_size,r,i,a,o,s;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=n+(n-ae)){t.arraySet(e.window,e.window,n,n,0),e.match_start-=n,e.strstart-=n,e.block_start-=n,i=e.hash_size,r=i;do a=e.head[--r],e.head[r]=a>=n?a-n:0;while(--i);i=n,r=i;do a=e.prev[--r],e.prev[r]=a>=n?a-n:0;while(--i);o+=n}if(e.strm.avail_in===0)break;if(i=xe(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=O)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+O-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<O)););}while(e.lookahead<ae&&e.strm.avail_in!==0)}function Ce(e,t){var n=65535;for(n>e.pending_buf_size-5&&(n=e.pending_buf_size-5);;){if(e.lookahead<=1){if(P(e),e.lookahead===0&&t===o)return A;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+n;if((e.strstart===0||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,be(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-ae&&(be(e,!1),e.strm.avail_out===0))return A}return e.insert=0,t===l?(be(e,!0),e.strm.avail_out===0?pe:me):(e.strstart>e.block_start&&(be(e,!1),e.strm.avail_out),A)}function F(e,t){for(var r,i;;){if(e.lookahead<ae){if(P(e),e.lookahead<ae&&t===o)return A;if(e.lookahead===0)break}if(r=0,e.lookahead>=O&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+O-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-ae&&(e.match_length=Se(e,r)),e.match_length>=O)if(i=n._tr_tally(e,e.strstart-e.match_start,e.match_length-O),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=O){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+O-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(be(e,!1),e.strm.avail_out===0))return A}return e.insert=e.strstart<O-1?e.strstart:O-1,t===l?(be(e,!0),e.strm.avail_out===0?pe:me):e.last_lit&&(be(e,!1),e.strm.avail_out===0)?A:j}function we(e,t){for(var r,i,a;;){if(e.lookahead<ae){if(P(e),e.lookahead<ae&&t===o)return A;if(e.lookahead===0)break}if(r=0,e.lookahead>=O&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+O-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=O-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-ae&&(e.match_length=Se(e,r),e.match_length<=5&&(e.strategy===_||e.match_length===O&&e.strstart-e.match_start>4096)&&(e.match_length=O-1)),e.prev_length>=O&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-O,i=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-O),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+O-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=O-1,e.strstart++,i&&(be(e,!1),e.strm.avail_out===0))return A}else if(e.match_available){if(i=n._tr_tally(e,0,e.window[e.strstart-1]),i&&be(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return A}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&=(i=n._tr_tally(e,0,e.window[e.strstart-1]),0),e.insert=e.strstart<O-1?e.strstart:O-1,t===l?(be(e,!0),e.strm.avail_out===0?pe:me):e.last_lit&&(be(e,!1),e.strm.avail_out===0)?A:j}function I(e,t){for(var r,i,a,s,c=e.window;;){if(e.lookahead<=ie){if(P(e),e.lookahead<=ie&&t===o)return A;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=O&&e.strstart>0&&(a=e.strstart-1,i=c[a],i===c[++a]&&i===c[++a]&&i===c[++a])){s=e.strstart+ie;do;while(i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&i===c[++a]&&a<s);e.match_length=ie-(s-a),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=O?(r=n._tr_tally(e,1,e.match_length-O),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(be(e,!1),e.strm.avail_out===0))return A}return e.insert=0,t===l?(be(e,!0),e.strm.avail_out===0?pe:me):e.last_lit&&(be(e,!1),e.strm.avail_out===0)?A:j}function L(e,t){for(var r;;){if(e.lookahead===0&&(P(e),e.lookahead===0)){if(t===o)return A;break}if(e.match_length=0,r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(be(e,!1),e.strm.avail_out===0))return A}return e.insert=0,t===l?(be(e,!0),e.strm.avail_out===0?pe:me):e.last_lit&&(be(e,!1),e.strm.avail_out===0)?A:j}function Te(e,t,n,r,i){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=i}var Ee=[new Te(0,0,0,0,Ce),new Te(4,4,8,4,F),new Te(4,5,16,8,F),new Te(4,6,32,32,F),new Te(4,4,16,16,we),new Te(8,16,32,32,we),new Te(8,16,128,128,we),new Te(8,32,128,256,we),new Te(32,128,258,1024,we),new Te(32,258,258,4096,we)];function De(e){e.window_size=2*e.w_size,ve(e.head),e.max_lazy_match=Ee[e.level].max_lazy,e.good_match=Ee[e.level].good_length,e.nice_match=Ee[e.level].nice_length,e.max_chain_length=Ee[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=O-1,e.match_available=0,e.ins_h=0}function Oe(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=C,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new t.Buf16(ne*2),this.dyn_dtree=new t.Buf16((2*ee+1)*2),this.bl_tree=new t.Buf16((2*te+1)*2),ve(this.dyn_ltree),ve(this.dyn_dtree),ve(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new t.Buf16(re+1),this.heap=new t.Buf16(2*D+1),ve(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new t.Buf16(2*D+1),ve(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function R(e){var t;return!e||!e.state?ge(e,p):(e.total_in=e.total_out=0,e.data_type=S,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?se:k,e.adler=t.wrap===2?0:1,t.last_flush=o,n._tr_init(t),d)}function ke(e){var t=R(e);return t===d&&De(e.state),t}function Ae(e,t){return!e||!e.state||e.state.wrap!==2?p:(e.state.gzhead=t,d)}function je(e,n,r,i,a,o){if(!e)return p;var s=1;if(n===g&&(n=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),a<1||a>w||r!==C||i<8||i>15||n<0||n>9||o<0||o>b)return ge(e,p);i===8&&(i=9);var c=new Oe;return e.state=c,c.strm=e,c.wrap=s,c.gzhead=null,c.w_bits=i,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=a+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+O-1)/O),c.window=new t.Buf8(c.w_size*2),c.head=new t.Buf16(c.hash_size),c.prev=new t.Buf16(c.w_size),c.lit_bufsize=1<<a+6,c.pending_buf_size=c.lit_bufsize*4,c.pending_buf=new t.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=n,c.strategy=o,c.method=r,ke(e)}function Me(e,t){return je(e,t,C,T,E,x)}function Ne(e,t){var r,a,m,g;if(!e||!e.state||t>u||t<0)return e?ge(e,p):p;if(a=e.state,!e.output||!e.input&&e.avail_in!==0||a.status===fe&&t!==l)return ge(e,e.avail_out===0?h:p);if(a.strm=e,r=a.last_flush,a.last_flush=t,a.status===se)if(a.wrap===2)e.adler=0,M(a,31),M(a,139),M(a,8),a.gzhead?(M(a,+!!a.gzhead.text+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),M(a,a.gzhead.time&255),M(a,a.gzhead.time>>8&255),M(a,a.gzhead.time>>16&255),M(a,a.gzhead.time>>24&255),M(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),M(a,a.gzhead.os&255),a.gzhead.extra&&a.gzhead.extra.length&&(M(a,a.gzhead.extra.length&255),M(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(e.adler=i(e.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=ce):(M(a,0),M(a,0),M(a,0),M(a,0),M(a,0),M(a,a.level===9?2:a.strategy>=v||a.level<2?4:0),M(a,he),a.status=k);else{var _=C+(a.w_bits-8<<4)<<8,b=-1;b=a.strategy>=v||a.level<2?0:a.level<6?1:a.level===6?2:3,_|=b<<6,a.strstart!==0&&(_|=oe),_+=31-_%31,a.status=k,N(a,_),a.strstart!==0&&(N(a,e.adler>>>16),N(a,e.adler&65535)),e.adler=1}if(a.status===ce)if(a.gzhead.extra){for(m=a.pending;a.gzindex<(a.gzhead.extra.length&65535)&&!(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),ye(e),m=a.pending,a.pending===a.pending_buf_size));)M(a,a.gzhead.extra[a.gzindex]&255),a.gzindex++;a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),a.gzindex===a.gzhead.extra.length&&(a.gzindex=0,a.status=le)}else a.status=le;if(a.status===le)if(a.gzhead.name){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),ye(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindex<a.gzhead.name.length?a.gzhead.name.charCodeAt(a.gzindex++)&255:0,M(a,g)}while(g!==0);a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.gzindex=0,a.status=ue)}else a.status=ue;if(a.status===ue)if(a.gzhead.comment){m=a.pending;do{if(a.pending===a.pending_buf_size&&(a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),ye(e),m=a.pending,a.pending===a.pending_buf_size)){g=1;break}g=a.gzindex<a.gzhead.comment.length?a.gzhead.comment.charCodeAt(a.gzindex++)&255:0,M(a,g)}while(g!==0);a.gzhead.hcrc&&a.pending>m&&(e.adler=i(e.adler,a.pending_buf,a.pending-m,m)),g===0&&(a.status=de)}else a.status=de;if(a.status===de&&(a.gzhead.hcrc?(a.pending+2>a.pending_buf_size&&ye(e),a.pending+2<=a.pending_buf_size&&(M(a,e.adler&255),M(a,e.adler>>8&255),e.adler=0,a.status=k)):a.status=k),a.pending!==0){if(ye(e),e.avail_out===0)return a.last_flush=-1,d}else if(e.avail_in===0&&_e(t)<=_e(r)&&t!==l)return ge(e,h);if(a.status===fe&&e.avail_in!==0)return ge(e,h);if(e.avail_in!==0||a.lookahead!==0||t!==o&&a.status!==fe){var x=a.strategy===v?L(a,t):a.strategy===y?I(a,t):Ee[a.level].func(a,t);if((x===pe||x===me)&&(a.status=fe),x===A||x===pe)return e.avail_out===0&&(a.last_flush=-1),d;if(x===j&&(t===s?n._tr_align(a):t!==u&&(n._tr_stored_block(a,0,0,!1),t===c&&(ve(a.head),a.lookahead===0&&(a.strstart=0,a.block_start=0,a.insert=0))),ye(e),e.avail_out===0))return a.last_flush=-1,d}return t===l?a.wrap<=0?f:(a.wrap===2?(M(a,e.adler&255),M(a,e.adler>>8&255),M(a,e.adler>>16&255),M(a,e.adler>>24&255),M(a,e.total_in&255),M(a,e.total_in>>8&255),M(a,e.total_in>>16&255),M(a,e.total_in>>24&255)):(N(a,e.adler>>>16),N(a,e.adler&65535)),ye(e),a.wrap>0&&(a.wrap=-a.wrap),a.pending===0?f:d):d}function Pe(e){var t;return!e||!e.state?p:(t=e.state.status,t!==se&&t!==ce&&t!==le&&t!==ue&&t!==de&&t!==k&&t!==fe?ge(e,p):(e.state=null,t===k?ge(e,m):d))}function Fe(e,n){var i=n.length,a,o,s,c,l,u,f,m;if(!e||!e.state||(a=e.state,c=a.wrap,c===2||c===1&&a.status!==se||a.lookahead))return p;for(c===1&&(e.adler=r(e.adler,n,i,0)),a.wrap=0,i>=a.w_size&&(c===0&&(ve(a.head),a.strstart=0,a.block_start=0,a.insert=0),m=new t.Buf8(a.w_size),t.arraySet(m,n,i-a.w_size,a.w_size,0),n=m,i=a.w_size),l=e.avail_in,u=e.next_in,f=e.input,e.avail_in=i,e.next_in=0,e.input=n,P(a);a.lookahead>=O;){o=a.strstart,s=a.lookahead-(O-1);do a.ins_h=(a.ins_h<<a.hash_shift^a.window[o+O-1])&a.hash_mask,a.prev[o&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=o,o++;while(--s);a.strstart=o,a.lookahead=O-1,P(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=O-1,a.match_available=0,e.next_in=u,e.input=f,e.avail_in=l,a.wrap=c,d}e.deflateInit=Me,e.deflateInit2=je,e.deflateReset=ke,e.deflateResetKeep=R,e.deflateSetHeader=Ae,e.deflate=Ne,e.deflateEnd=Pe,e.deflateSetDictionary=Fe,e.deflateInfo=`pako deflate (from Nodeca project)`})),HS=n((e=>{var t=IS(),n=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch{n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{r=!1}for(var i=new t.Buf8(256),a=0;a<256;a++)i[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;i[254]=i[254]=1,e.string2buf=function(e){var n,r,i,a,o,s=e.length,c=0;for(a=0;a<s;a++)r=e.charCodeAt(a),(r&64512)==55296&&a+1<s&&(i=e.charCodeAt(a+1),(i&64512)==56320&&(r=65536+(r-55296<<10)+(i-56320),a++)),c+=r<128?1:r<2048?2:r<65536?3:4;for(n=new t.Buf8(c),o=0,a=0;o<c;a++)r=e.charCodeAt(a),(r&64512)==55296&&a+1<s&&(i=e.charCodeAt(a+1),(i&64512)==56320&&(r=65536+(r-55296<<10)+(i-56320),a++)),r<128?n[o++]=r:r<2048?(n[o++]=192|r>>>6,n[o++]=128|r&63):r<65536?(n[o++]=224|r>>>12,n[o++]=128|r>>>6&63,n[o++]=128|r&63):(n[o++]=240|r>>>18,n[o++]=128|r>>>12&63,n[o++]=128|r>>>6&63,n[o++]=128|r&63);return n};function o(e,i){if(i<65534&&(e.subarray&&r||!e.subarray&&n))return String.fromCharCode.apply(null,t.shrinkBuf(e,i));for(var a=``,o=0;o<i;o++)a+=String.fromCharCode(e[o]);return a}e.buf2binstring=function(e){return o(e,e.length)},e.binstring2buf=function(e){for(var n=new t.Buf8(e.length),r=0,i=n.length;r<i;r++)n[r]=e.charCodeAt(r);return n},e.buf2string=function(e,t){var n,r,a,s,c=t||e.length,l=Array(c*2);for(r=0,n=0;n<c;){if(a=e[n++],a<128){l[r++]=a;continue}if(s=i[a],s>4){l[r++]=65533,n+=s-1;continue}for(a&=s===2?31:s===3?15:7;s>1&&n<c;)a=a<<6|e[n++]&63,s--;if(s>1){l[r++]=65533;continue}a<65536?l[r++]=a:(a-=65536,l[r++]=55296|a>>10&1023,l[r++]=56320|a&1023)}return o(l,r)},e.utf8border=function(e,t){var n;for(t||=e.length,t>e.length&&(t=e.length),n=t-1;n>=0&&(e[n]&192)==128;)n--;return n<0||n===0?t:n+i[e[n]]>t?n:t}})),US=n(((e,t)=>{function n(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=``,this.state=null,this.data_type=2,this.adler=0}t.exports=n})),WS=n((e=>{var t=VS(),n=IS(),r=HS(),i=BS(),a=US(),o=Object.prototype.toString,s=0,c=4,l=0,u=1,d=2,f=-1,p=0,m=8;function h(e){if(!(this instanceof h))return new h(e);this.options=n.assign({level:f,method:m,chunkSize:16384,windowBits:15,memLevel:8,strategy:p,to:``},e||{});var s=this.options;s.raw&&s.windowBits>0?s.windowBits=-s.windowBits:s.gzip&&s.windowBits>0&&s.windowBits<16&&(s.windowBits+=16),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,s.level,s.method,s.windowBits,s.memLevel,s.strategy);if(c!==l)throw Error(i[c]);if(s.header&&t.deflateSetHeader(this.strm,s.header),s.dictionary){var u=typeof s.dictionary==`string`?r.string2buf(s.dictionary):o.call(s.dictionary)===`[object ArrayBuffer]`?new Uint8Array(s.dictionary):s.dictionary;if(c=t.deflateSetDictionary(this.strm,u),c!==l)throw Error(i[c]);this._dict_set=!0}}h.prototype.push=function(e,i){var a=this.strm,f=this.options.chunkSize,p,m;if(this.ended)return!1;m=i===~~i?i:i===!0?c:s,a.input=typeof e==`string`?r.string2buf(e):o.call(e)===`[object ArrayBuffer]`?new Uint8Array(e):e,a.next_in=0,a.avail_in=a.input.length;do{if(a.avail_out===0&&(a.output=new n.Buf8(f),a.next_out=0,a.avail_out=f),p=t.deflate(a,m),p!==u&&p!==l)return this.onEnd(p),this.ended=!0,!1;(a.avail_out===0||a.avail_in===0&&(m===c||m===d))&&(this.options.to===`string`?this.onData(r.buf2binstring(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((a.avail_in>0||a.avail_out===0)&&p!==u);return m===c?(p=t.deflateEnd(this.strm),this.onEnd(p),this.ended=!0,p===l):m!==d||(this.onEnd(l),a.avail_out=0,!0)},h.prototype.onData=function(e){this.chunks.push(e)},h.prototype.onEnd=function(e){e===l&&(this.result=this.options.to===`string`?this.chunks.join(``):n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function g(e,t){var n=new h(t);if(n.push(e,!0),n.err)throw n.msg||i[n.err];return n.result}function _(e,t){return t||={},t.raw=!0,g(e,t)}function v(e,t){return t||={},t.gzip=!0,g(e,t)}e.Deflate=h,e.deflate=g,e.deflateRaw=_,e.gzip=v})),GS=n(((e,t)=>{t.exports=function(e,t){var n=e.state,r=e.next_in,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T=e.input,E;i=r+(e.avail_in-5),a=e.next_out,E=e.output,o=a-(t-e.avail_out),s=a+(e.avail_out-257),c=n.dmax,l=n.wsize,u=n.whave,d=n.wnext,f=n.window,p=n.hold,m=n.bits,h=n.lencode,g=n.distcode,_=(1<<n.lenbits)-1,v=(1<<n.distbits)-1;top:do{m<15&&(p+=T[r++]<<m,m+=8,p+=T[r++]<<m,m+=8),y=h[p&_];dolen:for(;;){if(b=y>>>24,p>>>=b,m-=b,b=y>>>16&255,b===0)E[a++]=y&65535;else if(b&16){x=y&65535,b&=15,b&&(m<b&&(p+=T[r++]<<m,m+=8),x+=p&(1<<b)-1,p>>>=b,m-=b),m<15&&(p+=T[r++]<<m,m+=8,p+=T[r++]<<m,m+=8),y=g[p&v];dodist:for(;;){if(b=y>>>24,p>>>=b,m-=b,b=y>>>16&255,b&16){if(S=y&65535,b&=15,m<b&&(p+=T[r++]<<m,m+=8,m<b&&(p+=T[r++]<<m,m+=8)),S+=p&(1<<b)-1,S>c){e.msg=`invalid distance too far back`,n.mode=30;break top}if(p>>>=b,m-=b,b=a-o,S>b){if(b=S-b,b>u&&n.sane){e.msg=`invalid distance too far back`,n.mode=30;break top}if(C=0,w=f,d===0){if(C+=l-b,b<x){x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}}else if(d<b){if(C+=l+d-b,b-=d,b<x){x-=b;do E[a++]=f[C++];while(--b);if(C=0,d<x){b=d,x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}}}else if(C+=d-b,b<x){x-=b;do E[a++]=f[C++];while(--b);C=a-S,w=E}for(;x>2;)E[a++]=w[C++],E[a++]=w[C++],E[a++]=w[C++],x-=3;x&&(E[a++]=w[C++],x>1&&(E[a++]=w[C++]))}else{C=a-S;do E[a++]=E[C++],E[a++]=E[C++],E[a++]=E[C++],x-=3;while(x>2);x&&(E[a++]=E[C++],x>1&&(E[a++]=E[C++]))}}else if(b&64){e.msg=`invalid distance code`,n.mode=30;break top}else{y=g[(y&65535)+(p&(1<<b)-1)];continue dodist}break}}else if(!(b&64)){y=h[(y&65535)+(p&(1<<b)-1)];continue dolen}else if(b&32){n.mode=12;break top}else{e.msg=`invalid literal/length code`,n.mode=30;break top}break}}while(r<i&&a<s);x=m>>3,r-=x,m-=x<<3,p&=(1<<m)-1,e.next_in=r,e.next_out=a,e.avail_in=r<i?5+(i-r):5-(r-i),e.avail_out=a<s?257+(s-a):257-(a-s),n.hold=p,n.bits=m}})),KS=n(((e,t)=>{var n=IS(),r=15,i=852,a=592,o=0,s=1,c=2,l=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],u=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],d=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],f=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,p,m,h,g,_,v){var y=v.bits,b=0,x=0,S=0,C=0,w=0,T=0,E=0,D=0,ee=0,te=0,ne,re,O,ie,ae,oe=null,se=0,ce,le=new n.Buf16(r+1),ue=new n.Buf16(r+1),de=null,k=0,fe,A,j;for(b=0;b<=r;b++)le[b]=0;for(x=0;x<m;x++)le[t[p+x]]++;for(w=y,C=r;C>=1&&le[C]===0;C--);if(w>C&&(w=C),C===0)return h[g++]=20971520,h[g++]=20971520,v.bits=1,0;for(S=1;S<C&&le[S]===0;S++);for(w<S&&(w=S),D=1,b=1;b<=r;b++)if(D<<=1,D-=le[b],D<0)return-1;if(D>0&&(e===o||C!==1))return-1;for(ue[1]=0,b=1;b<r;b++)ue[b+1]=ue[b]+le[b];for(x=0;x<m;x++)t[p+x]!==0&&(_[ue[t[p+x]]++]=x);if(e===o?(oe=de=_,ce=19):e===s?(oe=l,se-=257,de=u,k-=257,ce=256):(oe=d,de=f,ce=-1),te=0,x=0,b=S,ae=g,T=w,E=0,O=-1,ee=1<<w,ie=ee-1,e===s&&ee>i||e===c&&ee>a)return 1;for(;;){fe=b-E,_[x]<ce?(A=0,j=_[x]):_[x]>ce?(A=de[k+_[x]],j=oe[se+_[x]]):(A=96,j=0),ne=1<<b-E,re=1<<T,S=re;do re-=ne,h[ae+(te>>E)+re]=fe<<24|A<<16|j|0;while(re!==0);for(ne=1<<b-1;te≠)ne>>=1;if(ne===0?te=0:(te&=ne-1,te+=ne),x++,--le[b]===0){if(b===C)break;b=t[p+_[x]]}if(b>w&&(te&ie)!==O){for(E===0&&(E=w),ae+=S,T=b-E,D=1<<T;T+E<C&&(D-=le[T+E],!(D<=0));)T++,D<<=1;if(ee+=1<<T,e===s&&ee>i||e===c&&ee>a)return 1;O=te&ie,h[O]=w<<24|T<<16|ae-g|0}}return te!==0&&(h[ae+te]=b-E<<24|4194304),v.bits=w,0}})),qS=n((e=>{var t=IS(),n=RS(),r=zS(),i=GS(),a=KS(),o=0,s=1,c=2,l=4,u=5,d=6,f=0,p=1,m=2,h=-2,g=-3,_=-4,v=-5,y=8,b=1,x=2,S=3,C=4,w=5,T=6,E=7,D=8,ee=9,te=10,ne=11,re=12,O=13,ie=14,ae=15,oe=16,se=17,ce=18,le=19,ue=20,de=21,k=22,fe=23,A=24,j=25,pe=26,me=27,he=28,ge=29,_e=30,ve=31,ye=32,be=852,M=592,N=15;function xe(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Se(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function P(e){var n;return!e||!e.state?h:(n=e.state,e.total_in=e.total_out=n.total=0,e.msg=``,n.wrap&&(e.adler=n.wrap&1),n.mode=b,n.last=0,n.havedict=0,n.dmax=32768,n.head=null,n.hold=0,n.bits=0,n.lencode=n.lendyn=new t.Buf32(be),n.distcode=n.distdyn=new t.Buf32(M),n.sane=1,n.back=-1,f)}function Ce(e){var t;return!e||!e.state?h:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,P(e))}function F(e,t){var n,r;return!e||!e.state||(r=e.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?h:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Ce(e))}function we(e,t){var n,r;return e?(r=new Se,e.state=r,r.window=null,n=F(e,t),n!==f&&(e.state=null),n):h}function I(e){return we(e,N)}var L=!0,Te,Ee;function De(e){if(L){var n;for(Te=new t.Buf32(512),Ee=new t.Buf32(32),n=0;n<144;)e.lens[n++]=8;for(;n<256;)e.lens[n++]=9;for(;n<280;)e.lens[n++]=7;for(;n<288;)e.lens[n++]=8;for(a(s,e.lens,0,288,Te,0,e.work,{bits:9}),n=0;n<32;)e.lens[n++]=5;a(c,e.lens,0,32,Ee,0,e.work,{bits:5}),L=!1}e.lencode=Te,e.lenbits=9,e.distcode=Ee,e.distbits=5}function Oe(e,n,r,i){var a,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new t.Buf8(o.wsize)),i>=o.wsize?(t.arraySet(o.window,n,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(a=o.wsize-o.wnext,a>i&&(a=i),t.arraySet(o.window,n,r-i,a,o.wnext),i-=a,i?(t.arraySet(o.window,n,r-i,i,0),o.wnext=i,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=a))),0}function R(e,be){var M,N,Se,P,Ce,F,we,I,L,Te,Ee,R,ke,Ae,je=0,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be=new t.Buf8(4),Ve,He,Ue=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return h;M=e.state,M.mode===re&&(M.mode=O),Ce=e.next_out,Se=e.output,we=e.avail_out,P=e.next_in,N=e.input,F=e.avail_in,I=M.hold,L=M.bits,Te=F,Ee=we,ze=f;inf_leave:for(;;)switch(M.mode){case b:if(M.wrap===0){M.mode=O;break}for(;L<16;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(M.wrap&2&&I===35615){M.check=0,Be[0]=I&255,Be[1]=I>>>8&255,M.check=r(M.check,Be,2,0),I=0,L=0,M.mode=x;break}if(M.flags=0,M.head&&(M.head.done=!1),!(M.wrap&1)||(((I&255)<<8)+(I>>8))%31){e.msg=`incorrect header check`,M.mode=_e;break}if((I&15)!==y){e.msg=`unknown compression method`,M.mode=_e;break}if(I>>>=4,L-=4,Re=(I&15)+8,M.wbits===0)M.wbits=Re;else if(Re>M.wbits){e.msg=`invalid window size`,M.mode=_e;break}M.dmax=1<<Re,e.adler=M.check=1,M.mode=I&512?te:re,I=0,L=0;break;case x:for(;L<16;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(M.flags=I,(M.flags&255)!==y){e.msg=`unknown compression method`,M.mode=_e;break}if(M.flags&57344){e.msg=`unknown header flags set`,M.mode=_e;break}M.head&&(M.head.text=I>>8&1),M.flags&512&&(Be[0]=I&255,Be[1]=I>>>8&255,M.check=r(M.check,Be,2,0)),I=0,L=0,M.mode=S;case S:for(;L<32;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.head&&(M.head.time=I),M.flags&512&&(Be[0]=I&255,Be[1]=I>>>8&255,Be[2]=I>>>16&255,Be[3]=I>>>24&255,M.check=r(M.check,Be,4,0)),I=0,L=0,M.mode=C;case C:for(;L<16;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.head&&(M.head.xflags=I&255,M.head.os=I>>8),M.flags&512&&(Be[0]=I&255,Be[1]=I>>>8&255,M.check=r(M.check,Be,2,0)),I=0,L=0,M.mode=w;case w:if(M.flags&1024){for(;L<16;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.length=I,M.head&&(M.head.extra_len=I),M.flags&512&&(Be[0]=I&255,Be[1]=I>>>8&255,M.check=r(M.check,Be,2,0)),I=0,L=0}else M.head&&(M.head.extra=null);M.mode=T;case T:if(M.flags&1024&&(R=M.length,R>F&&(R=F),R&&(M.head&&(Re=M.head.extra_len-M.length,M.head.extra||(M.head.extra=Array(M.head.extra_len)),t.arraySet(M.head.extra,N,P,R,Re)),M.flags&512&&(M.check=r(M.check,N,R,P)),F-=R,P+=R,M.length-=R),M.length))break inf_leave;M.length=0,M.mode=E;case E:if(M.flags&2048){if(F===0)break inf_leave;R=0;do Re=N[P+R++],M.head&&Re&&M.length<65536&&(M.head.name+=String.fromCharCode(Re));while(Re&&R<F);if(M.flags&512&&(M.check=r(M.check,N,R,P)),F-=R,P+=R,Re)break inf_leave}else M.head&&(M.head.name=null);M.length=0,M.mode=D;case D:if(M.flags&4096){if(F===0)break inf_leave;R=0;do Re=N[P+R++],M.head&&Re&&M.length<65536&&(M.head.comment+=String.fromCharCode(Re));while(Re&&R<F);if(M.flags&512&&(M.check=r(M.check,N,R,P)),F-=R,P+=R,Re)break inf_leave}else M.head&&(M.head.comment=null);M.mode=ee;case ee:if(M.flags&512){for(;L<16;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(I!==(M.check&65535)){e.msg=`header crc mismatch`,M.mode=_e;break}I=0,L=0}M.head&&(M.head.hcrc=M.flags>>9&1,M.head.done=!0),e.adler=M.check=0,M.mode=re;break;case te:for(;L<32;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}e.adler=M.check=xe(I),I=0,L=0,M.mode=ne;case ne:if(M.havedict===0)return e.next_out=Ce,e.avail_out=we,e.next_in=P,e.avail_in=F,M.hold=I,M.bits=L,m;e.adler=M.check=1,M.mode=re;case re:if(be===u||be===d)break inf_leave;case O:if(M.last){I>>>=L&7,L-=L&7,M.mode=me;break}for(;L<3;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}switch(M.last=I&1,I>>>=1,--L,I&3){case 0:M.mode=ie;break;case 1:if(De(M),M.mode=ue,be===d){I>>>=2,L-=2;break inf_leave}break;case 2:M.mode=se;break;case 3:e.msg=`invalid block type`,M.mode=_e}I>>>=2,L-=2;break;case ie:for(I>>>=L&7,L-=L&7;L<32;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if((I&65535)!=(I>>>16^65535)){e.msg=`invalid stored block lengths`,M.mode=_e;break}if(M.length=I&65535,I=0,L=0,M.mode=ae,be===d)break inf_leave;case ae:M.mode=oe;case oe:if(R=M.length,R){if(R>F&&(R=F),R>we&&(R=we),R===0)break inf_leave;t.arraySet(Se,N,P,R,Ce),F-=R,P+=R,we-=R,Ce+=R,M.length-=R;break}M.mode=re;break;case se:for(;L<14;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(M.nlen=(I&31)+257,I>>>=5,L-=5,M.ndist=(I&31)+1,I>>>=5,L-=5,M.ncode=(I&15)+4,I>>>=4,L-=4,M.nlen>286||M.ndist>30){e.msg=`too many length or distance symbols`,M.mode=_e;break}M.have=0,M.mode=ce;case ce:for(;M.have<M.ncode;){for(;L<3;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.lens[Ue[M.have++]]=I&7,I>>>=3,L-=3}for(;M.have<19;)M.lens[Ue[M.have++]]=0;if(M.lencode=M.lendyn,M.lenbits=7,Ve={bits:M.lenbits},ze=a(o,M.lens,0,19,M.lencode,0,M.work,Ve),M.lenbits=Ve.bits,ze){e.msg=`invalid code lengths set`,M.mode=_e;break}M.have=0,M.mode=le;case le:for(;M.have<M.nlen+M.ndist;){for(;je=M.lencode[I&(1<<M.lenbits)-1],Me=je>>>24,Ne=je>>>16&255,Pe=je&65535,!(Me<=L);){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(Pe<16)I>>>=Me,L-=Me,M.lens[M.have++]=Pe;else{if(Pe===16){for(He=Me+2;L<He;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(I>>>=Me,L-=Me,M.have===0){e.msg=`invalid bit length repeat`,M.mode=_e;break}Re=M.lens[M.have-1],R=3+(I&3),I>>>=2,L-=2}else if(Pe===17){for(He=Me+3;L<He;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}I>>>=Me,L-=Me,Re=0,R=3+(I&7),I>>>=3,L-=3}else{for(He=Me+7;L<He;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}I>>>=Me,L-=Me,Re=0,R=11+(I&127),I>>>=7,L-=7}if(M.have+R>M.nlen+M.ndist){e.msg=`invalid bit length repeat`,M.mode=_e;break}for(;R--;)M.lens[M.have++]=Re}}if(M.mode===_e)break;if(M.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,M.mode=_e;break}if(M.lenbits=9,Ve={bits:M.lenbits},ze=a(s,M.lens,0,M.nlen,M.lencode,0,M.work,Ve),M.lenbits=Ve.bits,ze){e.msg=`invalid literal/lengths set`,M.mode=_e;break}if(M.distbits=6,M.distcode=M.distdyn,Ve={bits:M.distbits},ze=a(c,M.lens,M.nlen,M.ndist,M.distcode,0,M.work,Ve),M.distbits=Ve.bits,ze){e.msg=`invalid distances set`,M.mode=_e;break}if(M.mode=ue,be===d)break inf_leave;case ue:M.mode=de;case de:if(F>=6&&we>=258){e.next_out=Ce,e.avail_out=we,e.next_in=P,e.avail_in=F,M.hold=I,M.bits=L,i(e,Ee),Ce=e.next_out,Se=e.output,we=e.avail_out,P=e.next_in,N=e.input,F=e.avail_in,I=M.hold,L=M.bits,M.mode===re&&(M.back=-1);break}for(M.back=0;je=M.lencode[I&(1<<M.lenbits)-1],Me=je>>>24,Ne=je>>>16&255,Pe=je&65535,!(Me<=L);){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(Ne&&!(Ne&240)){for(Fe=Me,Ie=Ne,Le=Pe;je=M.lencode[Le+((I&(1<<Fe+Ie)-1)>>Fe)],Me=je>>>24,Ne=je>>>16&255,Pe=je&65535,!(Fe+Me<=L);){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}I>>>=Fe,L-=Fe,M.back+=Fe}if(I>>>=Me,L-=Me,M.back+=Me,M.length=Pe,Ne===0){M.mode=pe;break}if(Ne&32){M.back=-1,M.mode=re;break}if(Ne&64){e.msg=`invalid literal/length code`,M.mode=_e;break}M.extra=Ne&15,M.mode=k;case k:if(M.extra){for(He=M.extra;L<He;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.length+=I&(1<<M.extra)-1,I>>>=M.extra,L-=M.extra,M.back+=M.extra}M.was=M.length,M.mode=fe;case fe:for(;je=M.distcode[I&(1<<M.distbits)-1],Me=je>>>24,Ne=je>>>16&255,Pe=je&65535,!(Me<=L);){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(!(Ne&240)){for(Fe=Me,Ie=Ne,Le=Pe;je=M.distcode[Le+((I&(1<<Fe+Ie)-1)>>Fe)],Me=je>>>24,Ne=je>>>16&255,Pe=je&65535,!(Fe+Me<=L);){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}I>>>=Fe,L-=Fe,M.back+=Fe}if(I>>>=Me,L-=Me,M.back+=Me,Ne&64){e.msg=`invalid distance code`,M.mode=_e;break}M.offset=Pe,M.extra=Ne&15,M.mode=A;case A:if(M.extra){for(He=M.extra;L<He;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}M.offset+=I&(1<<M.extra)-1,I>>>=M.extra,L-=M.extra,M.back+=M.extra}if(M.offset>M.dmax){e.msg=`invalid distance too far back`,M.mode=_e;break}M.mode=j;case j:if(we===0)break inf_leave;if(R=Ee-we,M.offset>R){if(R=M.offset-R,R>M.whave&&M.sane){e.msg=`invalid distance too far back`,M.mode=_e;break}R>M.wnext?(R-=M.wnext,ke=M.wsize-R):ke=M.wnext-R,R>M.length&&(R=M.length),Ae=M.window}else Ae=Se,ke=Ce-M.offset,R=M.length;R>we&&(R=we),we-=R,M.length-=R;do Se[Ce++]=Ae[ke++];while(--R);M.length===0&&(M.mode=de);break;case pe:if(we===0)break inf_leave;Se[Ce++]=M.length,we--,M.mode=de;break;case me:if(M.wrap){for(;L<32;){if(F===0)break inf_leave;F--,I|=N[P++]<<L,L+=8}if(Ee-=we,e.total_out+=Ee,M.total+=Ee,Ee&&(e.adler=M.check=M.flags?r(M.check,Se,Ee,Ce-Ee):n(M.check,Se,Ee,Ce-Ee)),Ee=we,(M.flags?I:xe(I))!==M.check){e.msg=`incorrect data check`,M.mode=_e;break}I=0,L=0}M.mode=he;case he:if(M.wrap&&M.flags){for(;L<32;){if(F===0)break inf_leave;F--,I+=N[P++]<<L,L+=8}if(I!==(M.total&4294967295)){e.msg=`incorrect length check`,M.mode=_e;break}I=0,L=0}M.mode=ge;case ge:ze=p;break inf_leave;case _e:ze=g;break inf_leave;case ve:return _;case ye:default:return h}return e.next_out=Ce,e.avail_out=we,e.next_in=P,e.avail_in=F,M.hold=I,M.bits=L,(M.wsize||Ee!==e.avail_out&&M.mode<_e&&(M.mode<me||be!==l))&&Oe(e,e.output,e.next_out,Ee-e.avail_out)?(M.mode=ve,_):(Te-=e.avail_in,Ee-=e.avail_out,e.total_in+=Te,e.total_out+=Ee,M.total+=Ee,M.wrap&&Ee&&(e.adler=M.check=M.flags?r(M.check,Se,Ee,e.next_out-Ee):n(M.check,Se,Ee,e.next_out-Ee)),e.data_type=M.bits+(M.last?64:0)+(M.mode===re?128:0)+(M.mode===ue||M.mode===ae?256:0),(Te===0&&Ee===0||be===l)&&ze===f&&(ze=v),ze)}function ke(e){if(!e||!e.state)return h;var t=e.state;return t.window&&=null,e.state=null,f}function Ae(e,t){var n;return!e||!e.state||(n=e.state,!(n.wrap&2))?h:(n.head=t,t.done=!1,f)}function je(e,t){var r=t.length,i,a,o;return!e||!e.state||(i=e.state,i.wrap!==0&&i.mode!==ne)?h:i.mode===ne&&(a=1,a=n(a,t,r,0),a!==i.check)?g:(o=Oe(e,t,r,r),o?(i.mode=ve,_):(i.havedict=1,f))}e.inflateReset=Ce,e.inflateReset2=F,e.inflateResetKeep=P,e.inflateInit=I,e.inflateInit2=we,e.inflate=R,e.inflateEnd=ke,e.inflateGetHeader=Ae,e.inflateSetDictionary=je,e.inflateInfo=`pako inflate (from Nodeca project)`})),JS=n(((e,t)=>{t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}})),YS=n(((e,t)=>{function n(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=``,this.comment=``,this.hcrc=0,this.done=!1}t.exports=n})),XS=n((e=>{var t=qS(),n=IS(),r=HS(),i=JS(),a=BS(),o=US(),s=YS(),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=n.assign({chunkSize:16384,windowBits:0,to:``},e||{});var u=this.options;u.raw&&u.windowBits>=0&&u.windowBits<16&&(u.windowBits=-u.windowBits,u.windowBits===0&&(u.windowBits=-15)),u.windowBits>=0&&u.windowBits<16&&!(e&&e.windowBits)&&(u.windowBits+=32),u.windowBits>15&&u.windowBits<48&&(u.windowBits&15||(u.windowBits|=15)),this.err=0,this.msg=``,this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var d=t.inflateInit2(this.strm,u.windowBits);if(d!==i.Z_OK||(this.header=new s,t.inflateGetHeader(this.strm,this.header),u.dictionary&&(typeof u.dictionary==`string`?u.dictionary=r.string2buf(u.dictionary):c.call(u.dictionary)===`[object ArrayBuffer]`&&(u.dictionary=new Uint8Array(u.dictionary)),u.raw&&(d=t.inflateSetDictionary(this.strm,u.dictionary),d!==i.Z_OK))))throw Error(a[d])}l.prototype.push=function(e,a){var o=this.strm,s=this.options.chunkSize,l=this.options.dictionary,u,d,f,p,m,h=!1;if(this.ended)return!1;d=a===~~a?a:a===!0?i.Z_FINISH:i.Z_NO_FLUSH,o.input=typeof e==`string`?r.binstring2buf(e):c.call(e)===`[object ArrayBuffer]`?new Uint8Array(e):e,o.next_in=0,o.avail_in=o.input.length;do{if(o.avail_out===0&&(o.output=new n.Buf8(s),o.next_out=0,o.avail_out=s),u=t.inflate(o,i.Z_NO_FLUSH),u===i.Z_NEED_DICT&&l&&(u=t.inflateSetDictionary(this.strm,l)),u===i.Z_BUF_ERROR&&h===!0&&(u=i.Z_OK,h=!1),u!==i.Z_STREAM_END&&u!==i.Z_OK)return this.onEnd(u),this.ended=!0,!1;o.next_out&&(o.avail_out===0||u===i.Z_STREAM_END||o.avail_in===0&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&(this.options.to===`string`?(f=r.utf8border(o.output,o.next_out),p=o.next_out-f,m=r.buf2string(o.output,f),o.next_out=p,o.avail_out=s-p,p&&n.arraySet(o.output,o.output,f,p,0),this.onData(m)):this.onData(n.shrinkBuf(o.output,o.next_out))),o.avail_in===0&&o.avail_out===0&&(h=!0)}while((o.avail_in>0||o.avail_out===0)&&u!==i.Z_STREAM_END);return u===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(u=t.inflateEnd(this.strm),this.onEnd(u),this.ended=!0,u===i.Z_OK):d!==i.Z_SYNC_FLUSH||(this.onEnd(i.Z_OK),o.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){e===i.Z_OK&&(this.result=this.options.to===`string`?this.chunks.join(``):n.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function u(e,t){var n=new l(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}function d(e,t){return t||={},t.raw=!0,u(e,t)}e.Inflate=l,e.inflate=u,e.inflateRaw=d,e.ungzip=u})),ZS=n(((e,t)=>{var n=IS().assign,r=WS(),i=XS(),a=JS(),o={};n(o,r,i,a),t.exports=o})),QS=n(((e,t)=>{let n=(e,t)=>function(...n){let r=t.promiseModule;return new r((r,i)=>{t.multiArgs?n.push((...e)=>{t.errorFirst?e[0]?i(e):(e.shift(),r(e)):r(e)}):t.errorFirst?n.push((e,t)=>{e?i(e):r(t)}):n.push(r),e.apply(this,n)})};t.exports=(e,t)=>{t=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},t);let r=typeof e;if(e===null||r!==`object`&&r!==`function`)throw TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${e===null?`null`:r}\``);let i=e=>{let n=t=>typeof t==`string`?e===t:t.test(e);return t.include?t.include.some(n):!t.exclude.some(n)},a;a=r===`function`?function(...r){return t.excludeMain?e(...r):n(e,t).apply(this,r)}:Object.create(Object.getPrototypeOf(e));for(let r in e){let o=e[r];a[r]=typeof o==`function`&&i(r)?n(o,t):o}return a}})),$S=n(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.*\/|^\.+$/,l=`node-ignore`;typeof Symbol<`u`&&(l=Symbol.for(`node-ignore`));let u=l,d=(e,t,n)=>Object.defineProperty(e,t,{value:n}),f=/([0-z])-([0-z])/g,p=()=>!1,m=e=>e.replace(f,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),h=e=>{let{length:t}=e;return e.slice(0,t-t%2)},g=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${h(r)}${i}`:i===`]`&&r.length%2==0?`[${m(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(e,t)=>`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`]],_=Object.create(null),v=(e,t)=>{let n=_[e];return n||(n=g.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),_[e]=n),t?new RegExp(n,`i`):new RegExp(n)},y=e=>typeof e==`string`,b=e=>e&&y(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,x=e=>e.split(s);var S=class{constructor(e,t,n,r){this.origin=e,this.pattern=t,this.negative=n,this.regex=r}};let C=(e,t)=>{let n=e,r=!1;e.indexOf(`!`)===0&&(r=!0,e=e.substr(1)),e=e.replace(a,`!`).replace(o,`#`);let i=v(e,t);return new S(n,e,r,i)},w=(e,t)=>{throw new t(e)},T=(e,t,n)=>y(e)?e?!T.isNotRelative(e)||n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),E=e=>c.test(e);T.isNotRelative=E,T.convert=e=>e;var D=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){d(this,u,!0),this._rules=[],this._ignoreCase=t,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[u]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(b(e)){let t=C(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(y(e)?x(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,t){let n=!1,r=!1;return this._rules.forEach(i=>{let{negative:a}=i;r===a&&n!==r||a&&!n&&!r&&!t||i.regex.test(e)&&(n=!a,r=a)}),{ignored:n,unignored:r}}_test(e,t,n,r){let i=e&&T.convert(e);return T(i,e,this._allowRelativePaths?p:w),this._t(i,t,n,r)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`),r.pop(),!r.length)return t[e]=this._testOne(e,n);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let ee=e=>new D(e);if(ee.isPathValid=e=>T(e&&T.convert(e),e,p),ee.default=ee,t.exports=ee,typeof process<`u`&&({}.IGNORE_TEST_WIN32||process.platform===`win32`)){T.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;T.isNotRelative=t=>e.test(t)||E(t)}})),eC=n(((e,t)=>{function n(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function r(e,t,r){return t=t instanceof RegExp?t:new RegExp(n(t),`g`),e.replace(t,r)}t.exports={clean:function(e){if(typeof e!=`string`)throw Error(`Expected a string, received: `+e);return e=r(e,`./`,`/`),e=r(e,`..`,`.`),e=r(e,` `,`-`),e=r(e,/^[~^:?*\\\-]/g,``),e=r(e,/[~^:?*\\]/g,`-`),e=r(e,/[~^:?*\\\-]$/g,``),e=r(e,`@{`,`-`),e=r(e,/\.$/g,``),e=r(e,/\/$/g,``),e=r(e,/\.lock$/g,``),e}}})),tC=n(((e,t)=>{t.exports=function(e,t){var n=e,r=t,i=n.length,a=r.length,o=!1,s=null,c=i+1,l=[],u=[],d=[],f=``,p=-1,m=0,h=1,g,_,v=function(){i>=a&&(g=n,_=i,n=r,r=g,i=a,a=_,o=!0,c=i+1)},y=function(e,t,n){return{x:e,y:t,k:n}},b=function(e,t){return{elem:e,t}},x=function(e,t,o){var s=t>o?l[e-1+c]:l[e+1+c],d,f=Math.max(t,o);for(d=f-e;d<i&&f<a&&n[d]===r[f];)++d,++f;return l[e+c]=u.length,u[u.length]=new y(d,f,s),f},S=function(e){var t=i=1,i,a=s=0,s,c;for(c=e.length-1;c>=0;--c)for(;a<e[c].x||s<e[c].y;)e[c].y-e[c].x>s-a?(o?d[d.length]=new b(r[s],p):d[d.length]=new b(r[s],h),++i,++s):e[c].y-e[c].x<s-a?(o?d[d.length]=new b(n[a],h):d[d.length]=new b(n[a],p),++t,++a):(d[d.length]=new b(n[a],m),f+=n[a],++t,++i,++a,++s)};return v(),{SES_DELETE:-1,SES_COMMON:0,SES_ADD:1,editdistance:function(){return s},getlcs:function(){return f},getses:function(){return d},compose:function(){var e=a-i,t=i+a+3,n={},r,o,d,f,p;for(f=0;f<t;++f)n[f]=-1,l[f]=-1;r=-1;do{for(++r,p=-r;p<=e-1;++p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);for(p=e+r;p>=e+1;--p)n[p+c]=x(p,n[p-1+c]+1,n[p+1+c]);n[e+c]=x(e,n[e-1+c]+1,n[e+1+c])}while(n[e+c]!==a);for(s=e+2*r,o=l[e+c],d=[];o!==-1;)d[d.length]=new y(u[o].x,u[o].y,null),o=u[o].k;S(d)}}}})),nC=n(((e,t)=>{var n=tC();function r(e,t){var r=new n(e,t);r.compose();for(var i=r.getses(),a,o,s=e.length-1,c=t.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(o?(o.chain={file1index:s,file2index:c,chain:null},o=o.chain):(a={file1index:s,file2index:c,chain:null},o=a),s--,c--):i[l].t===r.SES_DELETE?s--:i[l].t===r.SES_ADD&&c--;var u={file1index:-1,file2index:-1,chain:null};return o?(o.chain=u,a):u}function i(e,t){for(var n=[],i=e.length,a=t.length,o=r(e,t);o!==null;o=o.chain){var s=i-o.file1index-1,c=a-o.file2index-1;i=o.file1index,a=o.file2index,(s||c)&&n.push({file1:[i+1,s],file2:[a+1,c]})}return n.reverse(),n}function a(e,t,n){var r,a=i(t,e),o=i(t,n),s=[];function c(e,t){s.push([e.file1[0],t,e.file1[1],e.file2[0],e.file2[1]])}for(r=0;r<a.length;r++)c(a[r],0);for(r=0;r<o.length;r++)c(o[r],2);s.sort(function(e,t){return e[0]-t[0]});var l=[],u=0;function d(e){e>u&&(l.push([1,u,e-u]),u=e)}for(var f=0;f<s.length;f++){for(var p=f,m=s[f],h=m[0],g=h+m[2];f<s.length-1;){var _=s[f+1],v=_[0];if(v>g)break;g=Math.max(g,v+_[2]),f++}if(d(h),p==f)m[4]>0&&l.push([m[1],m[3],m[4]]);else{var y={0:[e.length,-1,t.length,-1],2:[n.length,-1,t.length,-1]};for(r=p;r<=f;r++){m=s[r];var b=y[m[1]],x=m[0],S=x+m[2],C=m[3],w=C+m[4];b[0]=Math.min(C,b[0]),b[1]=Math.max(w,b[1]),b[2]=Math.min(x,b[2]),b[3]=Math.max(S,b[3])}var T=y[0][0]+(h-y[0][2]),E=y[0][1]+(g-y[0][3]),D=y[2][0]+(h-y[2][2]),ee=y[2][1]+(g-y[2][3]);l.push([-1,T,E-T,h,g-h,D,ee-D])}u=g}return d(t.length),l}function o(e,t,n){var r=[],i=[e,t,n],o=a(e,t,n),s=[];function c(){s.length&&r.push({ok:s}),s=[]}function l(e){for(var t=0;t<e.length;t++)s.push(e[t])}function u(t){if(t[2]!=t[6])return!0;for(var r=t[1],i=t[5],a=0;a<t[2];a++)if(e[a+r]!=n[a+i])return!0;return!1}for(var d=0;d<o.length;d++){var f=o[d],p=f[0];p==-1?u(f)?(c(),r.push({conflict:{a:e.slice(f[1],f[1]+f[2]),aIndex:f[1],o:t.slice(f[3],f[3]+f[4]),oIndex:f[3],b:n.slice(f[5],f[5]+f[6]),bIndex:f[5]}})):l(i[0].slice(f[1],f[1]+f[2])):l(i[p].slice(f[1],f[1]+f[2]))}return c(),r}t.exports=o})),rC=e(MS(),1),iC=e(PS(),1),aC=e(FS(),1),oC=e(ZS(),1),sC=e(QS(),1),cC=e($S(),1),lC=e(eC(),1),uC=e(nC(),1),dC=class e extends Error{constructor(e){super(e),this.caller=``}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(t){let n=new e(t.message);return n.code=t.code,n.data=t.data,n.caller=t.caller,n.stack=t.stack,n}get isIsomorphicGitError(){return!0}},fC=class e extends dC{constructor(t){super(`Modifying the index is not possible because you have unmerged files: ${t.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=e.code,this.data={filepaths:t}}};fC.code=`UnmergedPathsError`;var K=class e extends dC{constructor(t){super(`An internal error caused this command to fail.\n\nIf you're using an application that depends on isomorphic-git, please report this error to that application's developers.\n\nIf you're a developer and you believe this is a bug in isomorphic-git, please file an issue at https://github.com/isomorphic-git/isomorphic-git/issues with a minimal reproduction, version and environment details, and this error message: ${t}`),this.code=this.name=e.code,this.data={message:t}}};K.code=`InternalError`;var pC=class e extends dC{constructor(t){super(`The filepath "${t}" contains unsafe character sequences`),this.code=this.name=e.code,this.data={filepath:t}}};pC.code=`UnsafeFilepathError`;var mC=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let t=this.buffer.slice(this._start,this._start+e);return this._start+=e,t}toString(e,t){let n=this.buffer.toString(e,this._start,this._start+t);return this._start+=t,n}write(e,t,n){let r=this.buffer.write(e,this._start,t,n);return this._start+=t,r}copy(e,t,n){let r=e.copy(this.buffer,this._start,t,n);return this._start+=r,r}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let t=this.buffer.writeUInt8(e,this._start);return this._start+=1,t}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let t=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,t}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let t=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,t}};function hC(e,t){return-(e<t)||+(e>t)}function gC(e,t){return hC(e.path,t.path)}function _C(e){let t=e>0?e>>12:0;t!==4&&t!==8&&t!==10&&t!==14&&(t=8);let n=e&511;return n=n&73?493:420,t!==8&&(n=0),(t<<12)+n}const vC=2**32;function yC(e,t,n,r){if(e!==void 0&&t!==void 0)return[e,t];n===void 0&&(n=r.valueOf());let i=Math.floor(n/1e3);return[i,(n-i*1e3)*1e6]}function bC(e){let[t,n]=yC(e.ctimeSeconds,e.ctimeNanoseconds,e.ctimeMs,e.ctime),[r,i]=yC(e.mtimeSeconds,e.mtimeNanoseconds,e.mtimeMs,e.mtime);return{ctimeSeconds:t%vC,ctimeNanoseconds:n%vC,mtimeSeconds:r%vC,mtimeNanoseconds:i%vC,dev:e.dev%vC,ino:e.ino%vC,mode:_C(e.mode%vC),uid:e.uid%vC,gid:e.gid%vC,size:e.size>-1?e.size%vC:0}}function xC(e){let t=``;for(let n of new Uint8Array(e))n<16&&(t+=`0`),t+=n.toString(16);return t}let SC=null;async function CC(e){return SC===null&&(SC=await EC()),SC?TC(e):wC(e)}function wC(e){return new rC.default().update(e).digest(`hex`)}async function TC(e){return xC(await crypto.subtle.digest(`SHA-1`,e))}async function EC(){try{return await TC(new Uint8Array([]))===`da39a3ee5e6b4b0d3255bfef95601890afd80709`}catch{}return!1}function DC(e){return{assumeValid:!!(e&32768),extended:!!(e&16384),stage:(e&12288)>>12,nameLength:e&4095}}function OC(e){let t=e.flags;return t.extended=!1,t.nameLength=Math.min(Buffer.from(e.path).length,4095),(t.assumeValid?32768:0)+(t.extended?16384:0)+((t.stage&3)<<12)+(t.nameLength&4095)}var kC=class e{constructor(e,t){this._dirty=!1,this._unmergedPaths=t||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let t=this._entries.get(e.path);t||=(this._entries.set(e.path,e),e),t.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(t){if(Buffer.isBuffer(t))return e.fromBuffer(t);if(t===null)return new e(null);throw new K(`invalid type passed to GitIndex.from`)}static async fromBuffer(t){if(t.length===0)throw new K(`Index file is empty (.git/index)`);let n=new e,r=new mC(t),i=r.toString(`utf8`,4);if(i!==`DIRC`)throw new K(`Invalid dircache magic file number: ${i}`);let a=await CC(t.slice(0,-20)),o=t.slice(-20).toString(`hex`);if(o!==a)throw new K(`Invalid checksum in GitIndex buffer: expected ${o} but saw ${a}`);let s=r.readUInt32BE();if(s!==2)throw new K(`Unsupported dircache version: ${s}`);let c=r.readUInt32BE(),l=0;for(;!r.eof()&&l<c;){let e={};e.ctimeSeconds=r.readUInt32BE(),e.ctimeNanoseconds=r.readUInt32BE(),e.mtimeSeconds=r.readUInt32BE(),e.mtimeNanoseconds=r.readUInt32BE(),e.dev=r.readUInt32BE(),e.ino=r.readUInt32BE(),e.mode=r.readUInt32BE(),e.uid=r.readUInt32BE(),e.gid=r.readUInt32BE(),e.size=r.readUInt32BE(),e.oid=r.slice(20).toString(`hex`),e.flags=DC(r.readUInt16BE());let i=t.indexOf(0,r.tell()+1)-r.tell();if(i<1)throw new K(`Got a path length of: ${i}`);if(e.path=r.toString(`utf8`,i),e.path.includes(`..\\`)||e.path.includes(`../`))throw new pC(e.path);let a=8-(r.tell()-12)%8;for(a===0&&(a=8);a--;){let t=r.readUInt8();if(t!==0)throw new K(`Expected 1-8 null characters but got '${t}' after ${e.path}`);if(r.eof())throw new K(`Unexpected end of file`)}e.stages=[],n._addEntry(e),l++}return n}get unmergedPaths(){return[...this._unmergedPaths]}get entries(){return[...this._entries.values()].sort(gC)}get entriesMap(){return this._entries}get entriesFlat(){return[...this.entries].flatMap(e=>e.stages.length>1?e.stages.filter(e=>e):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:t,oid:n,stage:r=0}){t||={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0},t=bC(t);let i=Buffer.from(e),a={ctimeSeconds:t.ctimeSeconds,ctimeNanoseconds:t.ctimeNanoseconds,mtimeSeconds:t.mtimeSeconds,mtimeNanoseconds:t.mtimeNanoseconds,dev:t.dev,ino:t.ino,mode:t.mode||33188,uid:t.uid,gid:t.gid,size:t.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:r,nameLength:i.length<4095?i.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let t of this._entries.keys())t.startsWith(e+`/`)&&this._entries.delete(t);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(`
|
|
1153
1153
|
`)}static async _entryToBuffer(e){let t=Buffer.from(e.path),n=Math.ceil((62+t.length+1)/8)*8,r=Buffer.alloc(n),i=new mC(r),a=bC(e);return i.writeUInt32BE(a.ctimeSeconds),i.writeUInt32BE(a.ctimeNanoseconds),i.writeUInt32BE(a.mtimeSeconds),i.writeUInt32BE(a.mtimeNanoseconds),i.writeUInt32BE(a.dev),i.writeUInt32BE(a.ino),i.writeUInt32BE(a.mode),i.writeUInt32BE(a.uid),i.writeUInt32BE(a.gid),i.writeUInt32BE(a.size),i.write(e.oid,20,`hex`),i.writeUInt16BE(OC(e)),i.write(e.path,t.length,`utf8`),r}async toObject(){let t=Buffer.alloc(12),n=new mC(t);n.write(`DIRC`,4,`utf8`),n.writeUInt32BE(2),n.writeUInt32BE(this.entriesFlat.length);let r=[];for(let t of this.entries)if(r.push(e._entryToBuffer(t)),t.stages.length>1)for(let n of t.stages)n&&n!==t&&r.push(e._entryToBuffer(n));r=await Promise.all(r);let i=Buffer.concat(r),a=Buffer.concat([t,i]),o=await CC(a);return Buffer.concat([a,Buffer.from(o,`hex`)])}};function AC(e,t,n=!0,r=!0){let i=bC(e),a=bC(t);return n&&i.mode!==a.mode||i.mtimeSeconds!==a.mtimeSeconds||i.ctimeSeconds!==a.ctimeSeconds||i.uid!==a.uid||i.gid!==a.gid||r&&i.ino!==a.ino||i.size!==a.size}let jC;function MC(){return jC===void 0&&(jC=new iC.default({maxPending:1/0})),jC}function NC(e,t){return MC().acquire(e,t)}const PC=Symbol(`IndexCache`);function FC(){return{map:new Map,stats:new Map}}async function IC(e,t,n){let[r,i]=await Promise.all([e.lstat(t),e.read(t)]),a=await kC.from(i);n.map.set(t,a),n.stats.set(t,r)}async function LC(e,t,n){let r=n.stats.get(t);if(r===void 0)return!0;if(r===null)return!1;let i=await e.lstat(t);return i!==null&&AC(r,i)}var RC=class{static async acquire({fs:e,gitdir:t,cache:n,allowUnmerged:r=!0},i){n[PC]||(n[PC]=FC());let a=`${t}/index`,o,s=[];return await NC(a,async()=>{let t=n[PC];await LC(e,a,t)&&await IC(e,a,t);let c=t.map.get(a);if(s=c.unmergedPaths,s.length&&!r)throw new fC(s);if(o=await i(c),c._dirty){let n=await c.toObject();await e.write(a,n),t.stats.set(a,await e.lstat(a)),c._dirty=!1}}),o}};function zC(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t>-1&&(e=e.slice(t+1)),e}function BC(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return t===-1?`.`:t===0?`/`:e.slice(0,t)}function VC(e){let t=new Map,n=function(e){if(!t.has(e)){let r={type:`tree`,fullpath:e,basename:zC(e),metadata:{},children:[]};t.set(e,r),r.parent=n(BC(e)),r.parent&&r.parent!==r&&r.parent.children.push(r)}return t.get(e)},r=function(e,r){if(!t.has(e)){let i={type:`blob`,fullpath:e,basename:zC(e),metadata:r,parent:n(BC(e)),children:[]};i.parent&&i.parent.children.push(i),t.set(e,i)}return t.get(e)};n(`.`);for(let t of e)r(t.path,t);return t}function HC(e){switch(e){case 16384:return`tree`;case 33188:return`blob`;case 33261:return`blob`;case 40960:return`blob`;case 57344:return`commit`}throw new K(`Unexpected GitTree entry mode: ${e.toString(8)}`)}var UC=class{constructor({fs:e,gitdir:t,cache:n}){this.treePromise=RC.acquire({fs:e,gitdir:t,cache:n},async function(e){return VC(e.entries)});let r=this;this.ConstructEntry=class{constructor(e){this._fullpath=e,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return r.type(this)}async mode(){return r.mode(this)}async stat(){return r.stat(this)}async content(){return r.content(this)}async oid(){return r.oid(this)}}}async readdir(e){let t=e._fullpath,n=(await this.treePromise).get(t);if(!n||n.type===`blob`)return null;if(n.type!==`tree`)throw Error(`ENOTDIR: not a directory, scandir '${t}'`);let r=n.children.map(e=>e.fullpath);return r.sort(hC),r}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let t=(await this.treePromise).get(e._fullpath);if(!t)throw Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let n=t.type===`tree`?{}:bC(t.metadata);e._type=t.type===`tree`?`tree`:HC(n.mode),e._mode=n.mode,e._stat=t.type===`tree`?void 0:n}return e._stat}async content(e){}async oid(e){return e._oid===!1&&(e._oid=(await this.treePromise).get(e._fullpath).metadata.oid),e._oid}};const WC=Symbol(`GitWalkSymbol`);function GC(){let e=Object.create(null);return Object.defineProperty(e,WC,{value:function({fs:e,gitdir:t,cache:n}){return new UC({fs:e,gitdir:t,cache:n})}}),Object.freeze(e),e}var KC=class e extends dC{constructor(t){super(`Could not find ${t}.`),this.code=this.name=e.code,this.data={what:t}}};KC.code=`NotFoundError`;var qC=class e extends dC{constructor(t,n,r,i){super(`Object ${t} ${i?`at ${i}`:``}was anticipated to be a ${r} but it is a ${n}.`),this.code=this.name=e.code,this.data={oid:t,actual:n,expected:r,filepath:i}}};qC.code=`ObjectTypeError`;var JC=class e extends dC{constructor(t){super(`Expected a 40-char hex object id but saw "${t}".`),this.code=this.name=e.code,this.data={value:t}}};JC.code=`InvalidOidError`;var YC=class e extends dC{constructor(t,n){super(`"${t}" would be an invalid git reference. (Hint: a valid alternative would be "${n}".)`),this.code=this.name=e.code,this.data={ref:t,suggestion:n}}};YC.code=`InvalidRefNameError`;var XC=class e extends dC{constructor(t){super(`Could not find a fetch refspec for remote "${t}". Make sure the config file has an entry like the following:
|
|
@@ -1255,7 +1255,7 @@ gpgsig`+DT(o)+`
|
|
|
1255
1255
|
`,stderr:``,exitCode:0}}function tk(e,t){if(e.startsWith(`file://`))try{return Pt(decodeURIComponent(new URL(e).pathname))}catch{return null}return e.startsWith(`/`)?Pt(e):e.startsWith(`./`)||e.startsWith(`../`)?Pt(Ft(t,e)):null}async function nk(e,t,n,r,i,a,o){if(n===t||n.startsWith(`${t}/`))return ik(Error(`destination is inside the source repository`),n);try{await e.lfs.stat(`${t}/.git`);try{if((await e.lfs.readdir(n)).length>0)return ik(Error(`destination path '${i}' already exists and is not an empty directory.`),n)}catch{await e.lfs.mkdir(n,{recursive:!0})}let s=o??await qE({fs:e.lfs,dir:t});await rk(e,`${t}/.git`,`${n}/.git`),s&&await fE({fs:e.lfs,dir:n,ref:s,force:!0}),await oE({fs:e.lfs,dir:n,remote:`origin`,url:r,force:!0}),await e.fs.flush();let c=await bD({fs:e.lfs,dir:n});return c.length>0&&(a+=`Checked out ${c.length} files.\n`),{stdout:`${a}done.\n`,stderr:``,exitCode:0}}catch(e){return ik(e,n)}}async function rk(e,t,n){let r=await e.lfs.lstat(t);if(r.isDirectory()){await e.lfs.mkdir(n,{recursive:!0});for(let r of await e.lfs.readdir(t))await rk(e,`${t}/${r}`,`${n}/${r}`)}else r.isSymbolicLink()?await e.lfs.symlink(await e.lfs.readlink(t),n):await e.lfs.writeFile(n,await e.lfs.readFile(t))}function ik(e,t){return{stdout:``,stderr:`fatal: ${EO(e).replace(/'\/__opfs__\/[^']*<path>'/g,`'${t}'`).replace(/\/__opfs__\/[^\s'"<]*<path>/g,t).replace(/<path>/g,t)}\n`,exitCode:128}}async function ak(e,t,n){let{flags:r}=_O(sk(n),wO.commit),i=TO(r,`message`);if(!i)return{stdout:``,stderr:"error: switch `m` requires a value\n",exitCode:1};let a=r.amend===!0,o=r.all===!0,s=r[`allow-empty`]===!0;if(o&&await ok(e,t),!s&&!a&&!(await eO({fs:e.lfs,dir:t})).some(([,e,,t])=>t!==e))return{stdout:``,stderr:`nothing to commit, working tree clean
|
|
1256
1256
|
`,exitCode:1};let c=(await KE({fs:e.lfs,dir:t,message:i,author:await e.resolveAuthor(t),amend:a,noUpdateBranch:void 0})).slice(0,7);return{stdout:`[${await qE({fs:e.lfs,dir:t})??`HEAD`} ${c}] ${i}\n`,stderr:``,exitCode:0}}async function ok(e,t){let n=await eO({fs:e.lfs,dir:t});for(let[r,i,a,o]of n)i!==0&&a!==o&&(a===0?await JD({fs:e.lfs,dir:t,filepath:r}):await GT({fs:e.lfs,dir:t,filepath:r}))}function sk(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(r.startsWith(`-`)&&!r.startsWith(`--`)&&r.length>2&&!r.includes(`=`)){let e=r.slice(1);for(let n of e)t.push(`-${n}`)}else t.push(r)}return t}async function ck(e,t,n){let r=n.includes(`--list`)||n.includes(`-l`),i=n.includes(`--unset`),a=n.includes(`--global`),o=n.find(e=>!e.startsWith(`-`)&&e.includes(`.`));if(r)return fk(e,t,a);if(i)return lk(e,t,o,a);if(!o)return{stdout:``,stderr:`usage: git config [--global] [--list] [--unset] <key> [<value>]
|
|
1257
1257
|
`,exitCode:1};let s=n.indexOf(o),c;for(let e=s+1;e<n.length;e++)if(!n[e].startsWith(`-`)){c=n[e];break}return c===void 0?dk(e,t,o,a):uk(e,t,o,c,a)}async function lk(e,t,n,r){if(!n)return{stdout:``,stderr:`error: key required for --unset
|
|
1258
|
-
`,exitCode:1};if(n===`credential.token`||n===`github.token`)return await e.setGithubToken(``),{stdout:``,stderr:``,exitCode:0};if(r){let t=await e.getGlobalFs();try{let e=await t.readTextFile(ur),r=cr(e,n);await t.writeFile(ur,r)}catch{}}else try{let r=`${t}/.git/config`,i=await e.fs.readTextFile(r),a=cr(i,n);await e.fs.writeFile(r,a)}catch{}return{stdout:``,stderr:``,exitCode:0}}async function uk(e,t,n,r,i){return n===`credential.token`||n===`github.token`?(await e.setGithubToken(r),{stdout:``,stderr:``,exitCode:0}):(i?await
|
|
1258
|
+
`,exitCode:1};if(n===`credential.token`||n===`github.token`)return await e.setGithubToken(``),{stdout:``,stderr:``,exitCode:0};if(r){let t=await e.getGlobalFs();try{let e=await t.readTextFile(ur),r=cr(e,n);await t.writeFile(ur,r)}catch{}}else try{let r=`${t}/.git/config`,i=await e.fs.readTextFile(r),a=cr(i,n);await e.fs.writeFile(r,a)}catch{}return{stdout:``,stderr:``,exitCode:0}}async function uk(e,t,n,r,i){return n===`credential.token`||n===`github.token`?(await e.setGithubToken(r),{stdout:``,stderr:``,exitCode:0}):(i?await Yee(await e.getGlobalFs(),n,r):await QD({fs:e.lfs,dir:t,path:n,value:r}),n===`user.name`&&e.setDefaultAuthorName(r),n===`user.email`&&e.setDefaultAuthorEmail(r),{stdout:``,stderr:``,exitCode:0})}async function dk(e,t,n,r){if(n===`credential.token`||n===`github.token`){let t=e.getGithubToken();return{stdout:t?`${t}\n`:``,stderr:``,exitCode:+!t}}let i;return r?i=await lr(await e.getGlobalFs(),n):(i=await fD({fs:e.lfs,dir:t,path:n}),i||=await lr(await e.getGlobalFs(),n)),{stdout:i?`${i}\n`:``,stderr:``,exitCode:+!i}}async function fk(e,t,n){let r=``;if(!n)try{let n=`${t}/.git/config`,i=await e.fs.readTextFile(n);r+=pk(i)}catch{}try{let t=await(await e.getGlobalFs()).readTextFile(ur);r+=pk(t)}catch{}return{stdout:r,stderr:``,exitCode:0}}function pk(e){let t=``,n=``,r=``;for(let i of e.split(`
|
|
1259
1259
|
`)){let e=i.trim();if(!e||e.startsWith(`#`)||e.startsWith(`;`))continue;let a=e.match(/^\[(\w+)(?:\s+"([^"]*)")?\]$/);if(a){n=a[1].toLowerCase(),r=a[2]??``;continue}let o=e.match(/^(\w+)\s*=\s*(.*)$/);if(o&&n){let e=o[1],i=o[2].trim(),a=r?`${n}.${r}.${e}`:`${n}.${e}`;t+=`${a}=${i}\n`}}return t}async function mk(e,t,n){let r=hk(n),i=await gk(e,t,r.base);for(let n of r.steps)if(n.kind===`first-parent`)for(let r=0;r<n.count;r++)i=await _k(e,t,i,1);else i=await _k(e,t,i,n.count);return i}function hk(e){if(e.includes(`@{`))throw Error(`reflog selectors are unsupported`);let t=/^(.+?)(?:(~[0-9]*|\^[0-9]*))*$/.exec(e);if(!t)throw Error(`invalid revision`);let n=t[1],r=e.slice(n.length),i=r.match(/~[0-9]*|\^[0-9]*/g)??[];if(i.join(``)!==r)throw Error(`invalid revision`);return{base:n,steps:i.map(e=>{let t=e.length===1?1:Number(e.slice(1));return{kind:e[0]===`~`?`first-parent`:`parent`,count:t}})}}async function gk(e,t,n){try{return await iD({fs:e.lfs,dir:t,oid:n})}catch{return await ZD({fs:e.lfs,dir:t,ref:n})}}async function _k(e,t,n,r){if(r<1)return n;let{commit:i}=await KD({fs:e.lfs,dir:t,oid:n}),a=i.parent[r-1];if(!a)throw Error(`missing parent`);return a}function vk(e,t){return t.length===0||t.some(t=>{let n=t.replace(/^\.\//,``).replace(/\/+$/,``);return n===``||e===n||e.startsWith(`${n}/`)})}async function yk(e,t,n){let{flags:r,positionals:i,doubleDashRest:a}=_O(n,wO.diff),o=r.staged===!0||r.cached===!0,s={nameOnly:r[`name-only`]===!0,stat:r.stat===!0,pathspecs:a};if(i.length>=2)return wk(e,t,i[0],i[1],s);if(i.length===1){let n=kk(i[0]);return n?wk(e,t,n[0],n[1],s):o?xk(e,t,i[0],s):Ek(e,t,i[0],s)}let c=o?await bk(e,t,s.pathspecs):await Sk(e,t,s.pathspecs);if(c.length===0)return{stdout:``,stderr:``,exitCode:0};if(s.nameOnly)return{stdout:c.map(e=>e.filepath).join(`
|
|
1260
1260
|
`)+`
|
|
1261
1261
|
`,stderr:``,exitCode:0};if(s.stat)return Mk(c);let l=``;for(let e of c)l+=FO({oldContent:e.oldContent,newContent:e.newContent,oldName:e.filepath,newName:e.filepath});return{stdout:l,stderr:``,exitCode:0}}async function bk(e,t,n=[],r=`HEAD`){let i=[];return await rO({fs:e.lfs,dir:t,trees:[AT({ref:r}),GC()],map:async(r,[a,o])=>{if(r===`.`||r.startsWith(`.git`)||!vk(r,n))return;let s=a?await a.type():void 0,c=o?await o.type():void 0;if(s===`tree`||c===`tree`)return;let l=a?await a.oid():void 0,u=o?await o.oid():void 0;if(l===u)return;let d=await Ck(e,t,l),f=await Ck(e,t,u);i.push({filepath:r,oldContent:d,newContent:f})}}),i}async function xk(e,t,n,r){let i;try{i=await mk(e,t,n)}catch{return jk(n)}return Ok(await bk(e,t,r.pathspecs,i),r)}async function Sk(e,t,n=[]){let r=[],i=new Map;await rO({fs:e.lfs,dir:t,trees:[GC()],map:async(e,[t])=>{if(e===`.`||e.startsWith(`.git`)||!t||await t.type()!==`blob`)return;let n=await t.oid();n&&i.set(e,n)}});for(let[a,o]of i){if(!vk(a,n))continue;let i=await Ck(e,t,o),s=``;try{s=await e.fs.readTextFile(`${t}/${a}`)}catch{}i!==s&&r.push({filepath:a,oldContent:i,newContent:s})}return r}async function Ck(e,t,n){if(!n)return``;try{let{blob:r}=await GD({fs:e.lfs,dir:t,oid:n});return new TextDecoder().decode(r)}catch{return``}}async function wk(e,t,n,r,i){try{return await Tk(e,t,await mk(e,t,n),await mk(e,t,r),i)}catch{return jk(await Ak(e,t,[n,r])??n)}}async function Tk(e,t,n,r,i){let a=[];return await rO({fs:e.lfs,dir:t,trees:[AT({ref:n}),AT({ref:r})],map:async(e,[t,n])=>{let r=await Dk(e,t,n,i.pathspecs??[]);r&&a.push(r)}}),Ok(a,i)}async function Ek(e,t,n,r){let i;try{i=await mk(e,t,n)}catch{return jk(n)}let a=new Set(await bD({fs:e.lfs,dir:t})),o=[];return await rO({fs:e.lfs,dir:t,trees:[AT({ref:i}),jT()],map:async(e,[t,n])=>{if(!t&&!a.has(e))return;let i=await Dk(e,t,n,r.pathspecs??[]);i&&o.push(i)}}),Ok(o,r)}async function Dk(e,t,n,r){if(e===`.`||!vk(e,r))return null;let i=t?await t.type():void 0,a=n?await n.type():void 0;if(i===`tree`||a===`tree`||(t?await t.oid():void 0)===(n?await n.oid():void 0))return null;let o=t?await t.content():void 0,s=n?await n.content():void 0;return{filepath:e,oldContent:o?new TextDecoder().decode(o):``,newContent:s?new TextDecoder().decode(s):``}}function Ok(e,t){return e.length===0?{stdout:``,stderr:``,exitCode:0}:t.nameOnly?{stdout:`${e.map(e=>e.filepath).join(`
|
|
@@ -1334,7 +1334,7 @@ error: Please commit or stash them.
|
|
|
1334
1334
|
or: git symbolic-ref (-d | --delete) <name>`;function pj(){return{stdout:``,stderr:`${fj}\n`,exitCode:129}}function mj(e){return!e.startsWith(`refs/`)||e.length===5||e.includes(`..`)||e.includes(`@{`)||e.split(`/`).some(e=>!e||e.startsWith(`.`)||e.endsWith(`.`)||e.endsWith(`.lock`))?!1:![...e].some(e=>{let t=e.charCodeAt(0);return t<=32||t===127||`~^:?*[\\`.includes(e)})}async function hj(e,t,n){try{let r=await ZD({fs:e.lfs,dir:t,ref:n,depth:2});return r.startsWith(`refs/`)?{kind:`symbolic`,target:r}:{kind:`direct`}}catch{return{kind:`missing`}}}async function gj(e,t,n,r){let i=await hj(e,t,n);if(i.kind!==`symbolic`)return{stdout:``,stderr:`fatal: ref ${n} is not a symbolic ref\n`,exitCode:i.kind===`direct`?1:128};if(!r)return i.target;let a=new Set([n]),o=i.target;for(;;){if(a.has(o))return{stdout:``,stderr:`fatal: ref ${n} has a circular symbolic target\n`,exitCode:128};a.add(o);let r=await hj(e,t,o);if(r.kind!==`symbolic`)return o;o=r.target}}function _j(e){for(let t of[`refs/heads/`,`refs/tags/`,`refs/remotes/`])if(e.startsWith(t))return e.slice(t.length);return e.startsWith(`refs/`)?e.slice(5):e}function vj(e,t){let n=new Set([`m`,`delete`,`d`,`quiet`,`q`,`short`,`recurse`]),r=Object.keys(e).find(e=>!n.has(e));if(r)return{stdout:``,stderr:`error: unknown option '${r}'\n${fj}\n`,exitCode:129};if(e.m!==void 0)return{stdout:``,stderr:`fatal: option '-m' is not supported because reflogs are not persisted
|
|
1335
1335
|
`,exitCode:128};if(e.delete===!1||t&&(e.short!==void 0||e.recurse!==void 0))return pj()}async function yj(e,t,n,r){if(n===`HEAD`)return{stdout:``,stderr:`fatal: deleting 'HEAD' is not allowed
|
|
1336
1336
|
`,exitCode:128};let i=await hj(e,t,n);return i.kind===`symbolic`?(await XE({fs:e.lfs,dir:t,ref:n}),{stdout:``,stderr:``,exitCode:0}):{stdout:``,stderr:r?``:`fatal: Cannot delete ${n}, not a symbolic ref\n`,exitCode:i.kind===`direct`?1:128}}async function bj(e,t,n,r){return mj(r)?(await oO({fs:e.lfs,dir:t,ref:n,value:r,force:!0,symbolic:!0}),{stdout:``,stderr:``,exitCode:0}):{stdout:``,stderr:r.startsWith(`refs/`)?`fatal: Refusing to set '${n}' to invalid ref '${r}'\n`:`fatal: Refusing to point ${n} outside of refs/\n`,exitCode:128}}async function xj(e,t,n,r){let i=await gj(e,t,n,r.recurse!==!1);return typeof i==`string`?{stdout:`${r.short?_j(i):i}\n`,stderr:``,exitCode:0}:r.quiet&&i.exitCode===1?{...i,stderr:``}:i}async function Sj(e,t,n){let{flags:r,positionals:i}=_O(n,wO[`symbolic-ref`]),a=r.delete===!0,o=vj(r,a);if(o)return o;let s=r.quiet!==void 0||r.short!==void 0||r.recurse!==void 0;return a?i.length===1?yj(e,t,i[0],!!r.quiet):pj():i.length===2?s?pj():bj(e,t,i[0],i[1]):i.length===1?xj(e,t,i[0],r):pj()}async function Cj(e,t,n){let{flags:r,positionals:i}=_O(n,wO.tag),a=r.delete===!0,o=TO(r,`list`),s=r.annotate===!0,c=TO(r,`message`),l=r.force===!0;if(a){let n=i[0];return n?(await eD({fs:e.lfs,dir:t,ref:n}),{stdout:`Deleted tag '${n}'\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fatal: tag name required
|
|
1337
|
-
`,exitCode:128}}if(o!==void 0||i.length===0){let n=await ED({fs:e.lfs,dir:t}),r=n,i=o||void 0;if(i){let e=RegExp(`^`+i.replace(/\*/g,`.*`)+`$`);r=n.filter(t=>e.test(t))}return{stdout:r.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}let u=i[0],d=i[1];if(s||c){let n=await e.resolveAuthor(t);await Pie({fs:e.lfs,dir:t,ref:u,message:c??u,object:d,tagger:{...n,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},force:l})}else await tO({fs:e.lfs,dir:t,ref:u,object:d,force:l});return{stdout:``,stderr:``,exitCode:0}}function wj(e,t){let n=t.mtimeMs??0;return{type:e,mode:t.mode??(e===`dir`?16877:e===`symlink`?40960:33188),size:t.size??0,ino:t.ino??0,mtimeMs:n,ctimeMs:t.ctimeMs??n,uid:1,gid:1,dev:1,isFile:()=>e===`file`,isDirectory:()=>e===`dir`,isSymbolicLink:()=>e===`symlink`}}function Tj(e){if(typeof e==`string`)return/^utf-?8$/i.test(e);if(e&&typeof e==`object`){let t=e.encoding;if(typeof t==`string`)return/^utf-?8$/i.test(t)}return!1}function Ej(e){return{promises:{async readFile(t,n){return await e.readFile(t,Tj(n)?{encoding:`utf-8`}:{encoding:`binary`})},async writeFile(t,n,r){await e.writeFile(t,n)},async unlink(t){await e.rm(t)},async readdir(t){return(await e.readDir(t)).map(e=>e.name)},async mkdir(t,n){let r=n??void 0;await e.mkdir(t,r?.recursive===void 0?void 0:{recursive:r.recursive})},async rmdir(t){await e.rm(t)},async stat(t){let n=await e.stat(t);return wj(n.type===`directory`?`dir`:`file`,{size:n.size,mtimeMs:n.mtime,ctimeMs:n.ctime})},async lstat(t){let n=await e.lstat(t);return wj(n.type===`directory`?`dir`:n.type===`symlink`?`symlink`:`file`,{size:n.size,mtimeMs:n.mtime,ctimeMs:n.ctime})},async readlink(t){if(e.isPathUnderMount(t))throw new $t(`EINVAL`,`symlinks not supported on mounted filesystems`,t);return e.readlink(t)},async symlink(t,n){if(e.isPathUnderMount(n))throw new $t(`EINVAL`,`symlinks not supported on mounted filesystems`,n);await e.symlink(t,n)}}}}const Dj=r(`git-commands`),Oj=new Set([`clone`,`fetch`,`pull`,`push`,`ls-remote`]),kj={string:[`c`,`C`,`git-dir`,`work-tree`],boolean:[`help`,`version`,`no-pager`,`paginate`,`no-replace-objects`],alias:{h:`help`},stopEarly:!0};function Aj(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).map(e=>String(e))}function jj(e,t){if(e instanceof Map){let n=e.get(t);return n&&n.length>0?n:void 0}let n=e[t];return n&&n.length>0?n:void 0}var Mj=class e{options;static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;currentEnv;currentConfigOverrides;ctx;constructor(e){this.options=e,this.lfs=Ej(e.fs).promises,this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`,this.ctx={lfs:this.lfs,fs:this.options.fs,corsProxy:this.corsProxy,getOnAuth:()=>this.getOnAuth(),resolveAuthor:e=>this.resolveAuthor(e),getGlobalFs:()=>this.getGlobalFs(),setGithubToken:e=>this.setGithubToken(e),getGithubToken:()=>this.githubToken,setDefaultAuthorName:e=>{this.authorName=e},setDefaultAuthorEmail:e=>{this.authorEmail=e},getConfigOverrides:()=>this.currentConfigOverrides}}getOnAuth(){let e=this.resolveAuthToken();if(e)return()=>({username:`x-access-token`,password:e})}resolveAuthToken(){if(this.githubToken)return this.githubToken;let e=this.currentEnv;if(!e)return;let t=jj(e,`GH_TOKEN`);if(t)return t;let n=jj(e,`GITHUB_TOKEN`);if(n)return n}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=
|
|
1337
|
+
`,exitCode:128}}if(o!==void 0||i.length===0){let n=await ED({fs:e.lfs,dir:t}),r=n,i=o||void 0;if(i){let e=RegExp(`^`+i.replace(/\*/g,`.*`)+`$`);r=n.filter(t=>e.test(t))}return{stdout:r.map(e=>`${e}\n`).join(``),stderr:``,exitCode:0}}let u=i[0],d=i[1];if(s||c){let n=await e.resolveAuthor(t);await Pie({fs:e.lfs,dir:t,ref:u,message:c??u,object:d,tagger:{...n,timestamp:Math.floor(Date.now()/1e3),timezoneOffset:0},force:l})}else await tO({fs:e.lfs,dir:t,ref:u,object:d,force:l});return{stdout:``,stderr:``,exitCode:0}}function wj(e,t){let n=t.mtimeMs??0;return{type:e,mode:t.mode??(e===`dir`?16877:e===`symlink`?40960:33188),size:t.size??0,ino:t.ino??0,mtimeMs:n,ctimeMs:t.ctimeMs??n,uid:1,gid:1,dev:1,isFile:()=>e===`file`,isDirectory:()=>e===`dir`,isSymbolicLink:()=>e===`symlink`}}function Tj(e){if(typeof e==`string`)return/^utf-?8$/i.test(e);if(e&&typeof e==`object`){let t=e.encoding;if(typeof t==`string`)return/^utf-?8$/i.test(t)}return!1}function Ej(e){return{promises:{async readFile(t,n){return await e.readFile(t,Tj(n)?{encoding:`utf-8`}:{encoding:`binary`})},async writeFile(t,n,r){await e.writeFile(t,n)},async unlink(t){await e.rm(t)},async readdir(t){return(await e.readDir(t)).map(e=>e.name)},async mkdir(t,n){let r=n??void 0;await e.mkdir(t,r?.recursive===void 0?void 0:{recursive:r.recursive})},async rmdir(t){await e.rm(t)},async stat(t){let n=await e.stat(t);return wj(n.type===`directory`?`dir`:`file`,{size:n.size,mtimeMs:n.mtime,ctimeMs:n.ctime})},async lstat(t){let n=await e.lstat(t);return wj(n.type===`directory`?`dir`:n.type===`symlink`?`symlink`:`file`,{size:n.size,mtimeMs:n.mtime,ctimeMs:n.ctime})},async readlink(t){if(e.isPathUnderMount(t))throw new $t(`EINVAL`,`symlinks not supported on mounted filesystems`,t);return e.readlink(t)},async symlink(t,n){if(e.isPathUnderMount(n))throw new $t(`EINVAL`,`symlinks not supported on mounted filesystems`,n);await e.symlink(t,n)}}}}const Dj=r(`git-commands`),Oj=new Set([`clone`,`fetch`,`pull`,`push`,`ls-remote`]),kj={string:[`c`,`C`,`git-dir`,`work-tree`],boolean:[`help`,`version`,`no-pager`,`paginate`,`no-replace-objects`],alias:{h:`help`},stopEarly:!0};function Aj(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).map(e=>String(e))}function jj(e,t){if(e instanceof Map){let n=e.get(t);return n&&n.length>0?n:void 0}let n=e[t];return n&&n.length>0?n:void 0}var Mj=class e{options;static globalFsByDbName=new Map;lfs;corsProxy;authorName;authorEmail;globalDbName;githubToken;currentEnv;currentConfigOverrides;ctx;constructor(e){this.options=e,this.lfs=Ej(e.fs).promises,this.corsProxy=e.corsProxy,this.authorName=e.authorName??`User`,this.authorEmail=e.authorEmail??`user@example.com`,this.globalDbName=e.globalDbName??`slicc-fs-global`,this.ctx={lfs:this.lfs,fs:this.options.fs,corsProxy:this.corsProxy,getOnAuth:()=>this.getOnAuth(),resolveAuthor:e=>this.resolveAuthor(e),getGlobalFs:()=>this.getGlobalFs(),setGithubToken:e=>this.setGithubToken(e),getGithubToken:()=>this.githubToken,setDefaultAuthorName:e=>{this.authorName=e},setDefaultAuthorEmail:e=>{this.authorEmail=e},getConfigOverrides:()=>this.currentConfigOverrides}}getOnAuth(){let e=this.resolveAuthToken();if(e)return()=>({username:`x-access-token`,password:e})}resolveAuthToken(){if(this.githubToken)return this.githubToken;let e=this.currentEnv;if(!e)return;let t=jj(e,`GH_TOKEN`);if(t)return t;let n=jj(e,`GITHUB_TOKEN`);if(n)return n}getGlobalFs(){let t=e.globalFsByDbName.get(this.globalDbName);if(t)return t;let n=Kn.create({dbName:this.globalDbName});return e.globalFsByDbName.set(this.globalDbName,n),n}async loadGithubToken(){try{let e=(await(await this.getGlobalFs()).readTextFile(`/workspace/.git/github-token`)).trim();this.githubToken=e||void 0}catch{this.githubToken=void 0}}async ensureFreshGithubToken(){try{await this.options.ensureFreshGithubToken?.()}catch(e){Dj.warn(`GitHub token freshness check failed; continuing with existing auth`,{error:e instanceof Error?e.message:String(e)})}}async setGithubToken(e){let t=e.trim(),n=await this.getGlobalFs();if(!t){try{await n.rm(`/workspace/.git/github-token`)}catch{}this.githubToken=void 0;return}await n.writeFile(`/workspace/.git/github-token`,t),this.githubToken=t}async resolveAuthor(e){let t=async t=>{try{return await fD({fs:this.lfs,dir:e,path:t})}catch{return}},n=this.currentConfigOverrides,r=await this.getGlobalFs();return{name:n?.get(`user.name`)??await t(`user.name`)??await lr(r,`user.name`)??this.authorName,email:n?.get(`user.email`)??await t(`user.email`)??await lr(r,`user.email`)??this.authorEmail}}async execute(e,t,n){if(e.length===0)return this.help();let r=this.stripGlobalFlags(e,t);if(r.versionRequested&&r.remainingArgs.length===0)return this.version();if(r.helpRequested||r.remainingArgs.length===0)return this.help();let i=r.effectiveCwd,[a,...o]=r.remainingArgs,s=wO[a]??{},c=_O(o,s),l=Object.hasOwn(s.alias??{},`h`);if(c.flags.help||c.flags.h&&!l)return this.help();this.currentEnv=n,this.currentConfigOverrides=r.configOverrides;try{switch(Oj.has(a)&&await this.ensureFreshGithubToken(),await this.loadGithubToken(),a){case`init`:return await Fk(this.ctx,i,o);case`clone`:return await ek(this.ctx,i,o);case`add`:return await vO(this.ctx,i,o);case`status`:return await sj(this.ctx,i,o);case`commit`:return await ak(this.ctx,i,o);case`log`:return await Ik(this.ctx,i,o);case`ls-remote`:return await Jk(this.ctx,i,o);case`branch`:return await SO(this.ctx,i,o);case`checkout`:return await DO(this.ctx,i,o);case`clean`:return await GO(this.ctx,i,o);case`diff`:return await yk(this.ctx,i,o);case`show`:return await UA(this.ctx,i,o);case`remote`:return await AA(this.ctx,i,o);case`fetch`:return await Pk(this.ctx,i,o);case`pull`:return await cA(this.ctx,i,o);case`push`:return await lA(this.ctx,i,o);case`merge`:return await nA(this.ctx,i,o);case`merge-base`:return await iA(this.ctx,i,o);case`cherry-pick`:return await UO(this.ctx,i,o);case`rebase`:return await fA(this.ctx,i,o);case`revert`:return await LA(this.ctx,i,o);case`merge-file`:return await oA(this.ctx,i,o);case`reset`:return await jA(this.ctx,i,o);case`config`:return await ck(this.ctx,i,o);case`tag`:return await Cj(this.ctx,i,o);case`ls-files`:return await Gk(this.ctx,i,o);case`ls-tree`:return await Xk(this.ctx,i,o);case`show-ref`:return await KA(this.ctx,i,o);case`symbolic-ref`:return await Sj(this.ctx,i,o);case`stash`:return await qA(this.ctx,i,o);case`rm`:return await VA(this.ctx,i,o);case`mv`:return await sA(this.ctx,i,o);case`rev-parse`:return await IA(this.ctx,i,o);case`help`:return this.help();case`version`:return this.version();default:return{stdout:``,stderr:`git: '${a}' is not a git command. See 'git help'.\n`,exitCode:127}}}catch(e){return{stdout:``,stderr:`fatal: ${EO(e)}\n`,exitCode:128}}finally{this.currentEnv=void 0,this.currentConfigOverrides=void 0}}stripGlobalFlags(e,t){let n=_O(e,kj),r=t;for(let e of Aj(n.flags.C))e!==``&&(r=e.startsWith(`/`)?e:`${r}/${e}`);let i=new Map;for(let e of Aj(n.flags.c)){if(e===``)continue;let t=e.indexOf(`=`);if(t<0){i.set(e.toLowerCase(),``);continue}i.set(e.slice(0,t).toLowerCase(),e.slice(t+1))}return{effectiveCwd:r,remainingArgs:n.positionals,helpRequested:!!(n.flags.help||n.flags.h),versionRequested:!!n.flags.version,configOverrides:i}}version(){return{stdout:`git version 2.43.0 (isomorphic-git ${nO()})\n`,stderr:``,exitCode:0}}help(){return{stdout:`usage: git <command> [<args>]
|
|
1338
1338
|
|
|
1339
1339
|
Available commands:
|
|
1340
1340
|
init Initialize a new repository
|
|
@@ -1642,7 +1642,7 @@ except BaseException:
|
|
|
1642
1642
|
* @copyright Chen, Yi-Cyuan 2014-2024
|
|
1643
1643
|
* @license MIT
|
|
1644
1644
|
*/
|
|
1645
|
-
(function(){var e=`input is invalid type`,n=typeof window==`object`,r=n?window:{};r.JS_SHA1_NO_WINDOW&&(n=!1);var i=!n&&typeof self==`object`,a=!r.JS_SHA1_NO_NODE_JS&&typeof process==`object`&&process.versions&&process.versions.node;a?r=globalThis:i&&(r=self);var o=!r.JS_SHA1_NO_COMMON_JS&&typeof t==`object`&&t.exports,s=typeof define==`function`&&define.amd,c=!r.JS_SHA1_NO_ARRAY_BUFFER&&typeof ArrayBuffer<`u`,l=`0123456789abcdef`.split(``),u=[-2147483648,8388608,32768,128],d=[24,16,8,0],f=[`hex`,`array`,`digest`,`arrayBuffer`],p=[],m=Array.isArray;(r.JS_SHA1_NO_NODE_JS||!m)&&(m=function(e){return Object.prototype.toString.call(e)===`[object Array]`});var h=ArrayBuffer.isView;c&&(r.JS_SHA1_NO_ARRAY_BUFFER_IS_VIEW||!h)&&(h=function(e){return typeof e==`object`&&e.buffer&&e.buffer.constructor===ArrayBuffer});var g=function(t){var n=typeof t;if(n===`string`)return[t,!0];if(n!==`object`||t===null)throw Error(e);if(c&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!m(t)&&!h(t))throw Error(e);return[t,!1]},_=function(e){return function(t){return new S(!0).update(t)[e]()}},v=function(){var e=_(`hex`);a&&(e=y(e)),e.create=function(){return new S},e.update=function(t){return e.create().update(t)};for(var t=0;t<f.length;++t){var n=f[t];e[n]=_(n)}return e},y=function(t){var n=Rt(),i=
|
|
1645
|
+
(function(){var e=`input is invalid type`,n=typeof window==`object`,r=n?window:{};r.JS_SHA1_NO_WINDOW&&(n=!1);var i=!n&&typeof self==`object`,a=!r.JS_SHA1_NO_NODE_JS&&typeof process==`object`&&process.versions&&process.versions.node;a?r=globalThis:i&&(r=self);var o=!r.JS_SHA1_NO_COMMON_JS&&typeof t==`object`&&t.exports,s=typeof define==`function`&&define.amd,c=!r.JS_SHA1_NO_ARRAY_BUFFER&&typeof ArrayBuffer<`u`,l=`0123456789abcdef`.split(``),u=[-2147483648,8388608,32768,128],d=[24,16,8,0],f=[`hex`,`array`,`digest`,`arrayBuffer`],p=[],m=Array.isArray;(r.JS_SHA1_NO_NODE_JS||!m)&&(m=function(e){return Object.prototype.toString.call(e)===`[object Array]`});var h=ArrayBuffer.isView;c&&(r.JS_SHA1_NO_ARRAY_BUFFER_IS_VIEW||!h)&&(h=function(e){return typeof e==`object`&&e.buffer&&e.buffer.constructor===ArrayBuffer});var g=function(t){var n=typeof t;if(n===`string`)return[t,!0];if(n!==`object`||t===null)throw Error(e);if(c&&t.constructor===ArrayBuffer)return[new Uint8Array(t),!1];if(!m(t)&&!h(t))throw Error(e);return[t,!1]},_=function(e){return function(t){return new S(!0).update(t)[e]()}},v=function(){var e=_(`hex`);a&&(e=y(e)),e.create=function(){return new S},e.update=function(t){return e.create().update(t)};for(var t=0;t<f.length;++t){var n=f[t];e[n]=_(n)}return e},y=function(t){var n=Rt(),i=or().Buffer,a=i.from&&!r.JS_SHA1_NO_BUFFER_FROM?i.from:function(e){return new i(e)};return function(r){if(typeof r==`string`)return n.createHash(`sha1`).update(r,`utf8`).digest(`hex`);if(r==null)throw Error(e);return r.constructor===ArrayBuffer&&(r=new Uint8Array(r)),m(r)||h(r)||r.constructor===i?n.createHash(`sha1`).update(a(r)).digest(`hex`):t(r)}},b=function(e){return function(t,n){return new C(t,!0).update(n)[e]()}},x=function(){var e=b(`hex`);e.create=function(e){return new C(e)},e.update=function(t,n){return e.create(t).update(n)};for(var t=0;t<f.length;++t){var n=f[t];e[n]=b(n)}return e};function S(e){e?(p[0]=p[16]=p[1]=p[2]=p[3]=p[4]=p[5]=p[6]=p[7]=p[8]=p[9]=p[10]=p[11]=p[12]=p[13]=p[14]=p[15]=0,this.blocks=p):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}S.prototype.update=function(e){if(this.finalized)throw Error(`finalize already called`);var t=g(e);e=t[0];for(var n=t[1],r,i=0,a,o=e.length||0,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),n)for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<d[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<d[a++&3],s[a>>>2]|=(128|r&63)<<d[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<d[a++&3],s[a>>>2]|=(128|r>>>6&63)<<d[a++&3],s[a>>>2]|=(128|r&63)<<d[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<d[a++&3],s[a>>>2]|=(128|r>>>12&63)<<d[a++&3],s[a>>>2]|=(128|r>>>6&63)<<d[a++&3],s[a>>>2]|=(128|r&63)<<d[a++&3]);else for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<d[a++&3];this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this},S.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=u[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}},S.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a,o,s,c=this.blocks;for(o=16;o<80;++o)s=c[o-3]^c[o-8]^c[o-14]^c[o-16],c[o]=s<<1|s>>>31;for(o=0;o<20;o+=5)a=t&n|~t&r,s=e<<5|e>>>27,i=s+a+i+1518500249+c[o]<<0,t=t<<30|t>>>2,a=e&t|~e&n,s=i<<5|i>>>27,r=s+a+r+1518500249+c[o+1]<<0,e=e<<30|e>>>2,a=i&e|~i&t,s=r<<5|r>>>27,n=s+a+n+1518500249+c[o+2]<<0,i=i<<30|i>>>2,a=r&i|~r&e,s=n<<5|n>>>27,t=s+a+t+1518500249+c[o+3]<<0,r=r<<30|r>>>2,a=n&r|~n&i,s=t<<5|t>>>27,e=s+a+e+1518500249+c[o+4]<<0,n=n<<30|n>>>2;for(;o<40;o+=5)a=t^n^r,s=e<<5|e>>>27,i=s+a+i+1859775393+c[o]<<0,t=t<<30|t>>>2,a=e^t^n,s=i<<5|i>>>27,r=s+a+r+1859775393+c[o+1]<<0,e=e<<30|e>>>2,a=i^e^t,s=r<<5|r>>>27,n=s+a+n+1859775393+c[o+2]<<0,i=i<<30|i>>>2,a=r^i^e,s=n<<5|n>>>27,t=s+a+t+1859775393+c[o+3]<<0,r=r<<30|r>>>2,a=n^r^i,s=t<<5|t>>>27,e=s+a+e+1859775393+c[o+4]<<0,n=n<<30|n>>>2;for(;o<60;o+=5)a=t&n|t&r|n&r,s=e<<5|e>>>27,i=s+a+i-1894007588+c[o]<<0,t=t<<30|t>>>2,a=e&t|e&n|t&n,s=i<<5|i>>>27,r=s+a+r-1894007588+c[o+1]<<0,e=e<<30|e>>>2,a=i&e|i&t|e&t,s=r<<5|r>>>27,n=s+a+n-1894007588+c[o+2]<<0,i=i<<30|i>>>2,a=r&i|r&e|i&e,s=n<<5|n>>>27,t=s+a+t-1894007588+c[o+3]<<0,r=r<<30|r>>>2,a=n&r|n&i|r&i,s=t<<5|t>>>27,e=s+a+e-1894007588+c[o+4]<<0,n=n<<30|n>>>2;for(;o<80;o+=5)a=t^n^r,s=e<<5|e>>>27,i=s+a+i-899497514+c[o]<<0,t=t<<30|t>>>2,a=e^t^n,s=i<<5|i>>>27,r=s+a+r-899497514+c[o+1]<<0,e=e<<30|e>>>2,a=i^e^t,s=r<<5|r>>>27,n=s+a+n-899497514+c[o+2]<<0,i=i<<30|i>>>2,a=r^i^e,s=n<<5|n>>>27,t=s+a+t-899497514+c[o+3]<<0,r=r<<30|r>>>2,a=n^r^i,s=t<<5|t>>>27,e=s+a+e-899497514+c[o+4]<<0,n=n<<30|n>>>2;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0},S.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4;return l[e>>>28&15]+l[e>>>24&15]+l[e>>>20&15]+l[e>>>16&15]+l[e>>>12&15]+l[e>>>8&15]+l[e>>>4&15]+l[e&15]+l[t>>>28&15]+l[t>>>24&15]+l[t>>>20&15]+l[t>>>16&15]+l[t>>>12&15]+l[t>>>8&15]+l[t>>>4&15]+l[t&15]+l[n>>>28&15]+l[n>>>24&15]+l[n>>>20&15]+l[n>>>16&15]+l[n>>>12&15]+l[n>>>8&15]+l[n>>>4&15]+l[n&15]+l[r>>>28&15]+l[r>>>24&15]+l[r>>>20&15]+l[r>>>16&15]+l[r>>>12&15]+l[r>>>8&15]+l[r>>>4&15]+l[r&15]+l[i>>>28&15]+l[i>>>24&15]+l[i>>>20&15]+l[i>>>16&15]+l[i>>>12&15]+l[i>>>8&15]+l[i>>>4&15]+l[i&15]},S.prototype.toString=S.prototype.hex,S.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4;return[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255]},S.prototype.array=S.prototype.digest,S.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(20),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),e};function C(e,t){var n,r=g(e);if(e=r[0],r[1]){var i=[],a=e.length,o=0,s;for(n=0;n<a;++n)s=e.charCodeAt(n),s<128?i[o++]=s:s<2048?(i[o++]=192|s>>>6,i[o++]=128|s&63):s<55296||s>=57344?(i[o++]=224|s>>>12,i[o++]=128|s>>>6&63,i[o++]=128|s&63):(s=65536+((s&1023)<<10|e.charCodeAt(++n)&1023),i[o++]=240|s>>>18,i[o++]=128|s>>>12&63,i[o++]=128|s>>>6&63,i[o++]=128|s&63);e=i}e.length>64&&(e=new S(!0).update(e).array());var c=[],l=[];for(n=0;n<64;++n){var u=e[n]||0;c[n]=92^u,l[n]=54^u}S.call(this,t),this.update(l),this.oKeyPad=c,this.inner=!0,this.sharedMemory=t}C.prototype=new S,C.prototype.finalize=function(){if(S.prototype.finalize.call(this),this.inner){this.inner=!1;var e=this.array();S.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(e),S.prototype.finalize.call(this)}};var w=v();w.sha1=w,w.sha1.hmac=x(),o?t.exports=w:(r.sha1=w,s&&define(function(){return w}))})()}))();const cF=65536,lF={md5:oF,sha1:sF.sha1,sha256:Jv};function uF(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(wP(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function dF(e){let t=String(e).toLowerCase().replace(`-`,``),n=lF[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(uF(e,t)),a},digest(e){i=!0;let t=wP(r.array());return e?t.toString(e):t}};return a}function fF(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function pF(e){return fF().getRandomValues(e)}function mF(e){for(let t=0;t<e.length;t+=cF){let n=Math.min(t+cF,e.length);pF(e.subarray(t,n))}}function hF(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const gF=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function _F(){let e=fF();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=pF(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${gF[t[0]]}${gF[t[1]]}${gF[t[2]]}${gF[t[3]]}-${gF[t[4]]}${gF[t[5]]}-${gF[t[6]]}${gF[t[7]]}-${gF[t[8]]}${gF[t[9]]}-${gF[t[10]]}${gF[t[11]]}${gF[t[12]]}${gF[t[13]]}${gF[t[14]]}${gF[t[15]]}`}const vF={randomFillSync(e,t=0,n){let r=hF(e),i=t,a=n===void 0?r.length:i+n;return mF(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return mF(hF(n)),n},randomUUID:_F,getRandomValues(e){return pF(e)},createHash:dF,get webcrypto(){return fF()},get subtle(){return fF().subtle}},yF={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
|
|
1646
1646
|
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function bF(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 xF(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=bF(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function SF(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:xF(t)}function CF(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 wF(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 TF(e){let t=wF(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function EF(...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=bF(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function DF(e,t){let n=EF(e),r=EF(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 OF(e){let t=e.charCodeAt(0)===47?`/`:``,n=wF(e),r=TF(e),i=r?n.slice(0,n.length-r.length):n,a=CF(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function kF(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 AF={sep:`/`,delimiter:`:`,basename:wF,dirname:CF,extname:TF,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:SF,normalize:xF,resolve:EF,relative:DF,parse:OF,format:kF},jF={isatty:e=>!1,ReadStream:class{},WriteStream:class{}};function MF(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 NF(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const PF={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:MF,pathToFileURL:NF};var FF=4,IF=0,LF=1,RF=2;function zF(e){let t=e.length;for(;--t>=0;)e[t]=0}var BF=29,VF=256,HF=286,UF=30,WF=19,GF=573,KF=15,qF=16,JF=7,YF=256,XF=16,ZF=17,QF=18,$F=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),eI=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),tI=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),nI=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),rI=512,iI=Array(576);zF(iI);var aI=Array(UF*2);zF(aI);var oI=Array(rI);zF(oI);var sI=Array(256);zF(sI);var cI=Array(BF);zF(cI);var lI=Array(UF);zF(lI);var uI=class{constructor(e,t,n,r,i){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=i,this.has_stree=e&&e.length}},dI,fI,pI,mI=class{constructor(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}},hI=e=>e<256?oI[e]:oI[256+(e>>>7)],gI=(e,t)=>{e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255},_I=(e,t,n)=>{e.bi_valid>qF-n?(e.bi_buf|=t<<e.bi_valid&65535,gI(e,e.bi_buf),e.bi_buf=t>>qF-e.bi_valid,e.bi_valid+=n-qF):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},vI=(e,t,n)=>{_I(e,n[t*2],n[t*2+1])},yI=(e,t)=>{let n=0;do n|=e&1,e>>>=1,n<<=1;while(--t>0);return n>>>1},bI=e=>{e.bi_valid===16?(gI(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)},xI=(e,t)=>{let n=t.dyn_tree,r=t.max_code,i=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,c=t.stat_desc.max_length,l,u,d,f,p,m,h=0;for(f=0;f<=KF;f++)e.bl_count[f]=0;for(n[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<GF;l++)u=e.heap[l],f=n[n[u*2+1]*2+1]+1,f>c&&(f=c,h++),n[u*2+1]=f,!(u>r)&&(e.bl_count[f]++,p=0,u>=s&&(p=o[u-s]),m=n[u*2],e.opt_len+=m*(f+p),a&&(e.static_len+=m*(i[u*2+1]+p)));if(h!==0){do{for(f=c-1;e.bl_count[f]===0;)f--;e.bl_count[f]--,e.bl_count[f+1]+=2,e.bl_count[c]--,h-=2}while(h>0);for(f=c;f!==0;f--)for(u=e.bl_count[f];u!==0;)d=e.heap[--l],!(d>r)&&(n[d*2+1]!==f&&(e.opt_len+=(f-n[d*2+1])*n[d*2],n[d*2+1]=f),u--)}},SI=(e,t,n)=>{let r=Array(16),i=0,a,o;for(a=1;a<=KF;a++)i=i+n[a-1]<<1,r[a]=i;for(o=0;o<=t;o++){let t=e[o*2+1];t!==0&&(e[o*2]=yI(r[t]++,t))}},CI=()=>{let e,t,n,r,i,a=Array(16);for(n=0,r=0;r<BF-1;r++)for(cI[r]=n,e=0;e<1<<$F[r];e++)sI[n++]=r;for(sI[n-1]=r,i=0,r=0;r<16;r++)for(lI[r]=i,e=0;e<1<<eI[r];e++)oI[i++]=r;for(i>>=7;r<UF;r++)for(lI[r]=i<<7,e=0;e<1<<eI[r]-7;e++)oI[256+i++]=r;for(t=0;t<=KF;t++)a[t]=0;for(e=0;e<=143;)iI[e*2+1]=8,e++,a[8]++;for(;e<=255;)iI[e*2+1]=9,e++,a[9]++;for(;e<=279;)iI[e*2+1]=7,e++,a[7]++;for(;e<=287;)iI[e*2+1]=8,e++,a[8]++;for(SI(iI,287,a),e=0;e<UF;e++)aI[e*2+1]=5,aI[e*2]=yI(e,5);dI=new uI(iI,$F,257,HF,KF),fI=new uI(aI,eI,0,UF,KF),pI=new uI([],tI,0,WF,JF)},wI=e=>{let t;for(t=0;t<HF;t++)e.dyn_ltree[t*2]=0;for(t=0;t<UF;t++)e.dyn_dtree[t*2]=0;for(t=0;t<WF;t++)e.bl_tree[t*2]=0;e.dyn_ltree[YF*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},TI=e=>{e.bi_valid>8?gI(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},EI=(e,t,n,r)=>{let i=t*2,a=n*2;return e[i]<e[a]||e[i]===e[a]&&r[t]<=r[n]},DI=(e,t,n)=>{let r=e.heap[n],i=n<<1;for(;i<=e.heap_len&&(i<e.heap_len&&EI(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!EI(t,r,e.heap[i],e.depth));)e.heap[n]=e.heap[i],n=i,i<<=1;e.heap[n]=r},OI=(e,t,n)=>{let r,i,a=0,o,s;if(e.sym_next!==0)do r=e.pending_buf[e.sym_buf+a++]&255,r+=(e.pending_buf[e.sym_buf+a++]&255)<<8,i=e.pending_buf[e.sym_buf+a++],r===0?vI(e,i,t):(o=sI[i],vI(e,o+VF+1,t),s=$F[o],s!==0&&(i-=cI[o],_I(e,i,s)),r--,o=hI(r),vI(e,o,n),s=eI[o],s!==0&&(r-=lI[o],_I(e,r,s)));while(a<e.sym_next);vI(e,YF,t)},kI=(e,t)=>{let n=t.dyn_tree,r=t.stat_desc.static_tree,i=t.stat_desc.has_stree,a=t.stat_desc.elems,o,s,c=-1,l;for(e.heap_len=0,e.heap_max=GF,o=0;o<a;o++)n[o*2]===0?n[o*2+1]=0:(e.heap[++e.heap_len]=c=o,e.depth[o]=0);for(;e.heap_len<2;)l=e.heap[++e.heap_len]=c<2?++c:0,n[l*2]=1,e.depth[l]=0,e.opt_len--,i&&(e.static_len-=r[l*2+1]);for(t.max_code=c,o=e.heap_len>>1;o>=1;o--)DI(e,n,o);l=a;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],DI(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=s,n[l*2]=n[o*2]+n[s*2],e.depth[l]=(e.depth[o]>=e.depth[s]?e.depth[o]:e.depth[s])+1,n[o*2+1]=n[s*2+1]=l,e.heap[1]=l++,DI(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],xI(e,t),SI(n,c,e.bl_count)},AI=(e,t,n)=>{let r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)&&(s<l?e.bl_tree[a*2]+=s:a===0?s<=10?e.bl_tree[34]++:e.bl_tree[36]++:(a!==i&&e.bl_tree[a*2]++,e.bl_tree[32]++),s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4))},jI=(e,t,n)=>{let r,i=-1,a,o=t[1],s=0,c=7,l=4;for(o===0&&(c=138,l=3),r=0;r<=n;r++)if(a=o,o=t[(r+1)*2+1],!(++s<c&&a===o)){if(s<l)do vI(e,a,e.bl_tree);while(--s!==0);else a===0?s<=10?(vI(e,ZF,e.bl_tree),_I(e,s-3,3)):(vI(e,QF,e.bl_tree),_I(e,s-11,7)):(a!==i&&(vI(e,a,e.bl_tree),s--),vI(e,XF,e.bl_tree),_I(e,s-3,2));s=0,i=a,o===0?(c=138,l=3):a===o?(c=6,l=3):(c=7,l=4)}},MI=e=>{let t;for(AI(e,e.dyn_ltree,e.l_desc.max_code),AI(e,e.dyn_dtree,e.d_desc.max_code),kI(e,e.bl_desc),t=18;t>=3&&e.bl_tree[nI[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t},NI=(e,t,n,r)=>{let i;for(_I(e,t-257,5),_I(e,n-1,5),_I(e,r-4,4),i=0;i<r;i++)_I(e,e.bl_tree[nI[i]*2+1],3);jI(e,e.dyn_ltree,t-1),jI(e,e.dyn_dtree,n-1)},PI=e=>{let t=4093624447,n;for(n=0;n<=31;n++,t>>>=1)if(t&1&&e.dyn_ltree[n*2]!==0)return IF;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return LF;for(n=32;n<VF;n++)if(e.dyn_ltree[n*2]!==0)return LF;return IF},FI=!1,II=e=>{FI||=(CI(),!0),e.l_desc=new mI(e.dyn_ltree,dI),e.d_desc=new mI(e.dyn_dtree,fI),e.bl_desc=new mI(e.bl_tree,pI),e.bi_buf=0,e.bi_valid=0,wI(e)},LI=(e,t,n,r)=>{_I(e,0+ +!!r,3),TI(e),gI(e,n),gI(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n},RI=e=>{_I(e,2,3),vI(e,YF,iI),bI(e)},zI=(e,t,n,r)=>{let i,a,o=0;e.level>0?(e.strm.data_type===RF&&(e.strm.data_type=PI(e)),kI(e,e.l_desc),kI(e,e.d_desc),o=MI(e),i=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=i&&(i=a)):i=a=n+5,n+4<=i&&t!==-1?LI(e,t,n,r):e.strategy===FF||a===i?(_I(e,2+ +!!r,3),OI(e,iI,aI)):(_I(e,4+ +!!r,3),NI(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),OI(e,e.dyn_ltree,e.dyn_dtree)),wI(e),r&&TI(e)},BI=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,t===0?e.dyn_ltree[n*2]++:(e.matches++,t--,e.dyn_ltree[(sI[n]+VF+1)*2]++,e.dyn_dtree[hI(t)*2]++),e.sym_next===e.sym_end),VI=(e,t,n,r)=>{let i=e&65535|0,a=e>>>16&65535|0,o=0;for(;n!==0;){o=n>2e3?2e3:n,n-=o;do i=i+t[r++]|0,a=a+i|0;while(--o);i%=65521,a%=65521}return i|a<<16|0},HI=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var r=0;r<8;r++)e=e&1?3988292384^e>>>1:e>>>1;t[n]=e}return t})()),UI=(e,t,n,r)=>{let i=HI,a=r+n;e^=-1;for(let n=r;n<a;n++)e=e>>>8^i[(e^t[n])&255];return e^-1},WI={2:`need dictionary`,1:`stream end`,0:``,"-1":`file error`,"-2":`stream error`,"-3":`data error`,"-4":`insufficient memory`,"-5":`buffer error`,"-6":`incompatible version`},GI=9,KI=573,qI=3,JI=258,YI=262,XI=32,ZI=42,QI=57,$I=69,eL=73,tL=91,nL=103,rL=113,iL=666,aL=1,oL=2,sL=3,cL=4,lL=3,uL=(e,t)=>(e.msg=WI[t],t),dL=e=>e*2-(e>4?9:0),fL=e=>{let t=e.length;for(;--t>=0;)e[t]=0},pL=e=>{let t,n,r,i=e.w_size;t=e.hash_size,r=t;do n=e.head[--r],e.head[r]=n>=i?n-i:0;while(--t);t=i,r=t;do n=e.prev[--r],e.prev[r]=n>=i?n-i:0;while(--t)},mL=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask,hL=(e,t)=>{let n;if(e.legacy_hash)n=e.ins_h=mL(e,e.ins_h,e.window[t+qI-1]);else{let r=e.window,i=r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24;n=e.ins_h=Math.imul(i,66521)+66521>>>16&e.hash_mask}let r=e.prev[t&e.w_mask]=e.head[n];return e.head[n]=t,r},gL=e=>{let t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))},_L=(e,t)=>{zI(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,gL(e.strm)},vL=(e,t)=>{e.pending_buf[e.pending++]=t},yL=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255},bL=(e,t,n,r)=>{let i=e.avail_in;return i>r&&(i=r),i===0?0:(e.avail_in-=i,t.set(e.input.subarray(e.next_in,e.next_in+i),n),e.state.wrap===1?e.adler=VI(e.adler,t,i,n):e.state.wrap===2&&(e.adler=UI(e.adler,t,i,n)),e.next_in+=i,e.total_in+=i,i)},xL=(e,t)=>{let n=e.max_chain_length,r=e.strstart,i,a,o=e.prev_length,s=e.nice_match,c=e.strstart>e.w_size-YI?e.strstart-(e.w_size-YI):0,l=e.window,u=e.w_mask,d=e.prev,f=e.strstart+JI,p=l[r+o-1],m=l[r+o];e.prev_length>=e.good_match&&(n>>=2),s>e.lookahead&&(s=e.lookahead);do{if(i=t,l[i+o]!==m||l[i+o-1]!==p||l[i]!==l[r]||l[++i]!==l[r+1])continue;r+=2,i++;do;while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<f);if(a=JI-(f-r),r=f-JI,a>o){if(e.match_start=t,o=a,a>=s)break;p=l[r+o-1],m=l[r+o]}}while((t=d[t&u])>c&&--n!==0);return o<=e.lookahead?o:e.lookahead},SL=e=>{let t=e.w_size,n,r,i;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-YI)&&(e.window.set(e.window.subarray(t,t+t-r),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),pL(e),r+=t),e.strm.avail_in===0)break;if(n=bL(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=n,!e.legacy_hash){if(e.lookahead+e.insert>qI)for(i=e.strstart-e.insert;e.insert&&(hL(e,i),i++,e.insert--,!(e.lookahead+e.insert<=qI)););}else if(e.lookahead+e.insert>=qI)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=mL(e,e.ins_h,e.window[i+1]);e.insert&&(hL(e,i),i++,e.insert--,!(e.lookahead+e.insert<qI)););}while(e.lookahead<YI&&e.strm.avail_in!==0)},CL=(e,t)=>{let n=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,r,i,a,o=0,s=e.strm.avail_in;do{if(r=65535,a=e.bi_valid+42>>3,e.strm.avail_out<a||(a=e.strm.avail_out-a,i=e.strstart-e.block_start,r>i+e.strm.avail_in&&(r=i+e.strm.avail_in),r>a&&(r=a),r<n&&(r===0&&t!==4||t===0||r!==i+e.strm.avail_in)))break;o=+(t===4&&r===i+e.strm.avail_in),LI(e,0,0,o),e.pending_buf[e.pending-4]=r,e.pending_buf[e.pending-3]=r>>8,e.pending_buf[e.pending-2]=~r,e.pending_buf[e.pending-1]=~r>>8,gL(e.strm),i&&(i>r&&(i=r),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,r-=i),r&&(bL(e.strm,e.strm.output,e.strm.next_out,r),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r)}while(o===0);return s-=e.strm.avail_in,s&&(s>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=s&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-s,e.strm.next_in),e.strstart),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),o?cL:t!==0&&t!==4&&e.strm.avail_in===0&&e.strstart===e.block_start?oL:(a=e.window_size-e.strstart,e.strm.avail_in>a&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,a+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),a>e.strm.avail_in&&(a=e.strm.avail_in),a&&(bL(e.strm,e.window,e.strstart,a),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.high_water<e.strstart&&(e.high_water=e.strstart),a=e.bi_valid+42>>3,a=e.pending_buf_size-a>65535?65535:e.pending_buf_size-a,n=a>e.w_size?e.w_size:a,i=e.strstart-e.block_start,(i>=n||(i||t===4)&&t!==0&&e.strm.avail_in===0&&i<=a)&&(r=i>a?a:i,o=+(t===4&&e.strm.avail_in===0&&r===i),LI(e,e.block_start,r,o),e.block_start+=r,gL(e.strm)),o?sL:aL)},wL=(e,t)=>{let n,r;for(;;){if(e.lookahead<YI){if(SL(e),e.lookahead<YI&&t===0)return aL;if(e.lookahead===0)break}if(n=0,e.lookahead>=qI&&(n=hL(e,e.strstart)),n!==0&&e.strstart-n<=e.w_size-YI&&(e.match_length=xL(e,n)),e.match_length>=qI)if(r=BI(e,e.strstart-e.match_start,e.match_length-qI),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=qI){e.match_length--;do e.strstart++,n=hL(e,e.strstart);while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.legacy_hash&&(e.ins_h=e.window[e.strstart],e.ins_h=mL(e,e.ins_h,e.window[e.strstart+1]));else r=BI(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(_L(e,!1),e.strm.avail_out===0))return aL}return e.insert=e.strstart<qI-1?e.strstart:qI-1,t===4?(_L(e,!0),e.strm.avail_out===0?sL:cL):e.sym_next&&(_L(e,!1),e.strm.avail_out===0)?aL:oL},TL=(e,t)=>{let n,r,i;for(;;){if(e.lookahead<YI){if(SL(e),e.lookahead<YI&&t===0)return aL;if(e.lookahead===0)break}if(n=0,e.lookahead>=qI&&(n=hL(e,e.strstart)),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=qI-1,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-YI&&(e.match_length=xL(e,n),e.match_length<=5&&(e.strategy===1||e.match_length===qI&&e.strstart-e.match_start>4096)&&(e.match_length=qI-1)),e.prev_length>=qI&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-qI,r=BI(e,e.strstart-1-e.prev_match,e.prev_length-qI),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=i&&(n=hL(e,e.strstart));while(--e.prev_length!==0);if(e.match_available=0,e.match_length=qI-1,e.strstart++,r&&(_L(e,!1),e.strm.avail_out===0))return aL}else if(e.match_available){if(r=BI(e,0,e.window[e.strstart-1]),r&&_L(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return aL}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&=(r=BI(e,0,e.window[e.strstart-1]),0),e.insert=e.strstart<qI-1?e.strstart:qI-1,t===4?(_L(e,!0),e.strm.avail_out===0?sL:cL):e.sym_next&&(_L(e,!1),e.strm.avail_out===0)?aL:oL},EL=(e,t)=>{let n,r,i,a,o=e.window;for(;;){if(e.lookahead<=JI){if(SL(e),e.lookahead<=JI&&t===0)return aL;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=qI&&e.strstart>0&&(i=e.strstart-1,r=o[i],r===o[++i]&&r===o[++i]&&r===o[++i])){a=e.strstart+JI;do;while(r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&r===o[++i]&&i<a);e.match_length=JI-(a-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=qI?(n=BI(e,1,e.match_length-qI),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=BI(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(_L(e,!1),e.strm.avail_out===0))return aL}return e.insert=0,t===4?(_L(e,!0),e.strm.avail_out===0?sL:cL):e.sym_next&&(_L(e,!1),e.strm.avail_out===0)?aL:oL},DL=(e,t)=>{let n;for(;;){if(e.lookahead===0&&(SL(e),e.lookahead===0)){if(t===0)return aL;break}if(e.match_length=0,n=BI(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(_L(e,!1),e.strm.avail_out===0))return aL}return e.insert=0,t===4?(_L(e,!0),e.strm.avail_out===0?sL:cL):e.sym_next&&(_L(e,!1),e.strm.avail_out===0)?aL:oL},OL=class{constructor(e,t,n,r,i){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=i}},kL=[new OL(0,0,0,0,CL),new OL(4,4,8,4,wL),new OL(4,5,16,8,wL),new OL(4,6,32,32,wL),new OL(4,4,16,16,TL),new OL(8,16,32,32,TL),new OL(8,16,128,128,TL),new OL(8,32,128,256,TL),new OL(32,128,258,1024,TL),new OL(32,258,258,4096,TL)],AL=e=>{e.window_size=2*e.w_size,fL(e.head),e.max_lazy_match=kL[e.level].max_lazy,e.good_match=kL[e.level].good_length,e.nice_match=kL[e.level].nice_length,e.max_chain_length=kL[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=qI-1,e.match_available=0,e.ins_h=0},jL=class{constructor(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.legacy_hash=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(KI*2),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),fL(this.dyn_ltree),fL(this.dyn_dtree),fL(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),fL(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),fL(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}},ML=e=>{if(!e)return 1;let t=e.state;return+(!t||t.strm!==e||t.status!==ZI&&t.status!==QI&&t.status!==$I&&t.status!==eL&&t.status!==tL&&t.status!==nL&&t.status!==rL&&t.status!==iL)},NL=e=>{if(ML(e))return uL(e,-2);e.total_in=e.total_out=0,e.data_type=2;let t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?QI:t.wrap?ZI:rL,e.adler=t.wrap===2?0:1,t.last_flush=-2,II(t),0},PL=e=>{let t=NL(e);return t===0&&AL(e.state),t},FL=(e,t,n,r,i,a,o)=>{if(!e)return-2;let s=1;if(t===-1&&(t=6),r<0?(s=0,r=-r):r>15&&(s=2,r-=16),i<1||i>GI||n!==8||r<8||r>15||t<0||t>9||a<0||a>4||r===8&&s!==1)return uL(e,-2);r===8&&(r=9);let c=new jL;return e.state=c,c.strm=e,c.status=ZI,c.wrap=s,c.gzhead=null,c.w_bits=r,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.legacy_hash=+!!o,c.hash_bits=i+7,!c.legacy_hash&&c.hash_bits<15&&(c.hash_bits=15),c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+qI-1)/qI),c.window=new Uint8Array(c.w_size*2),c.head=new Uint16Array(c.hash_size),c.prev=new Uint16Array(c.w_size),c.lit_bufsize=1<<i+6,c.pending_buf_size=c.lit_bufsize*4,c.pending_buf=new Uint8Array(c.pending_buf_size),c.sym_buf=c.lit_bufsize,c.sym_end=(c.lit_bufsize-1)*3,c.level=t,c.strategy=a,c.method=n,PL(e)},IL=(e,t)=>{if(ML(e)||t>5||t<0)return e?uL(e,-2):-2;let n=e.state;if(!e.output||e.avail_in!==0&&!e.input||n.status===iL&&t!==4)return uL(e,e.avail_out===0?-5:-2);let r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(gL(e),e.avail_out===0)return n.last_flush=-1,0}else if(e.avail_in===0&&dL(t)<=dL(r)&&t!==4)return uL(e,-5);if(n.status===iL&&e.avail_in!==0)return uL(e,-5);if(n.status===ZI&&n.wrap===0&&(n.status=rL),n.status===ZI){let t=8+(n.w_bits-8<<4)<<8,r=-1;if(r=n.strategy>=2||n.level<2?0:n.level<6?1:n.level===6?2:3,t|=r<<6,n.strstart!==0&&(t|=XI),t+=31-t%31,yL(n,t),n.strstart!==0&&(yL(n,e.adler>>>16),yL(n,e.adler&65535)),e.adler=1,n.status=rL,gL(e),n.pending!==0)return n.last_flush=-1,0}if(n.status===QI){if(e.adler=0,vL(n,31),vL(n,139),vL(n,8),n.gzhead)vL(n,+!!n.gzhead.text+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),vL(n,n.gzhead.time&255),vL(n,n.gzhead.time>>8&255),vL(n,n.gzhead.time>>16&255),vL(n,n.gzhead.time>>24&255),vL(n,n.level===9?2:n.strategy>=2||n.level<2?4:0),vL(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(vL(n,n.gzhead.extra.length&255),vL(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=UI(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=$I;else if(vL(n,0),vL(n,0),vL(n,0),vL(n,0),vL(n,0),vL(n,n.level===9?2:n.strategy>=2||n.level<2?4:0),vL(n,lL),n.status=rL,gL(e),n.pending!==0)return n.last_flush=-1,0}if(n.status===$I){if(n.gzhead.extra){let t=n.pending,r=(n.gzhead.extra.length&65535)-n.gzindex;for(;n.pending+r>n.pending_buf_size;){let i=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex+=i,gL(e),n.pending!==0)return n.last_flush=-1,0;t=0,r-=i}let i=new Uint8Array(n.gzhead.extra);n.pending_buf.set(i.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending+=r,n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=eL}if(n.status===eL){if(n.gzhead.name){let t=n.pending,r;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t)),gL(e),n.pending!==0)return n.last_flush=-1,0;t=0}r=n.gzindex<n.gzhead.name.length?n.gzhead.name.charCodeAt(n.gzindex++)&255:0,vL(n,r)}while(r!==0);n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=tL}if(n.status===tL){if(n.gzhead.comment){let t=n.pending,r;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t)),gL(e),n.pending!==0)return n.last_flush=-1,0;t=0}r=n.gzindex<n.gzhead.comment.length?n.gzhead.comment.charCodeAt(n.gzindex++)&255:0,vL(n,r)}while(r!==0);n.gzhead.hcrc&&n.pending>t&&(e.adler=UI(e.adler,n.pending_buf,n.pending-t,t))}n.status=nL}if(n.status===nL){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(gL(e),n.pending!==0))return n.last_flush=-1,0;vL(n,e.adler&255),vL(n,e.adler>>8&255),e.adler=0}if(n.status=rL,gL(e),n.pending!==0)return n.last_flush=-1,0}if(e.avail_in!==0||n.lookahead!==0||t!==0&&n.status!==iL){let r=n.level===0?CL(n,t):n.strategy===2?DL(n,t):n.strategy===3?EL(n,t):kL[n.level].func(n,t);if((r===sL||r===cL)&&(n.status=iL),r===aL||r===sL)return e.avail_out===0&&(n.last_flush=-1),0;if(r===oL&&(t===1?RI(n):t!==5&&(LI(n,0,0,!1),t===3&&(fL(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),gL(e),e.avail_out===0))return n.last_flush=-1,0}return t===4?n.wrap<=0?1:(n.wrap===2?(vL(n,e.adler&255),vL(n,e.adler>>8&255),vL(n,e.adler>>16&255),vL(n,e.adler>>24&255),vL(n,e.total_in&255),vL(n,e.total_in>>8&255),vL(n,e.total_in>>16&255),vL(n,e.total_in>>24&255)):(yL(n,e.adler>>>16),yL(n,e.adler&65535)),gL(e),n.wrap>0&&(n.wrap=-n.wrap),+(n.pending===0)):0},LL=e=>{if(ML(e))return-2;let t=e.state.status;return e.state=null,t===rL?uL(e,-3):0},RL=(e,t)=>{let n=t.length;if(ML(e))return-2;let r=e.state,i=r.wrap;if(i===2||i===1&&r.status!==ZI||r.lookahead)return-2;if(i===1&&(e.adler=VI(e.adler,t,n,0)),r.wrap=0,n>=r.w_size){i===0&&(fL(r.head),r.strstart=0,r.block_start=0,r.insert=0);let e=new Uint8Array(r.w_size);e.set(t.subarray(n-r.w_size,n),0),t=e,n=r.w_size}let a=e.avail_in,o=e.next_in,s=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,SL(r);r.lookahead>=qI;){let e=r.strstart,t=r.lookahead-(qI-1);do hL(r,e),e++;while(--t);r.strstart=e,r.lookahead=qI-1,SL(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=qI-1,r.match_available=0,e.next_in=o,e.input=s,e.avail_in=a,r.wrap=i,0},zL=16209,BL=16191;function VL(e,t){let n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E=e.state;n=e.next_in,w=e.input,r=n+(e.avail_in-5),i=e.next_out,T=e.output,a=i-(t-e.avail_out),o=i+(e.avail_out-257),s=E.dmax,c=E.wsize,l=E.whave,u=E.wnext,d=E.window,f=E.hold,p=E.bits,m=E.lencode,h=E.distcode,g=(1<<E.lenbits)-1,_=(1<<E.distbits)-1;top:do{p<15&&(f+=w[n++]<<p,p+=8,f+=w[n++]<<p,p+=8),v=m[f&g];dolen:for(;;){if(y=v>>>24,f>>>=y,p-=y,y=v>>>16&255,y===0)T[i++]=v&65535;else if(y&16){b=v&65535,y&=15,y&&(p<y&&(f+=w[n++]<<p,p+=8),b+=f&(1<<y)-1,f>>>=y,p-=y),p<15&&(f+=w[n++]<<p,p+=8,f+=w[n++]<<p,p+=8),v=h[f&_];dodist:for(;;){if(y=v>>>24,f>>>=y,p-=y,y=v>>>16&255,y&16){if(x=v&65535,y&=15,p<y&&(f+=w[n++]<<p,p+=8,p<y&&(f+=w[n++]<<p,p+=8)),x+=f&(1<<y)-1,x>s){e.msg=`invalid distance too far back`,E.mode=zL;break top}if(f>>>=y,p-=y,y=i-a,x>y){if(y=x-y,y>l&&E.sane){e.msg=`invalid distance too far back`,E.mode=zL;break top}if(S=0,C=d,u===0){if(S+=c-y,y<b){b-=y;do T[i++]=d[S++];while(--y);S=i-x,C=T}}else if(u<y){if(S+=c+u-y,y-=u,y<b){b-=y;do T[i++]=d[S++];while(--y);if(S=0,u<b){y=u,b-=y;do T[i++]=d[S++];while(--y);S=i-x,C=T}}}else if(S+=u-y,y<b){b-=y;do T[i++]=d[S++];while(--y);S=i-x,C=T}for(;b>2;)T[i++]=C[S++],T[i++]=C[S++],T[i++]=C[S++],b-=3;b&&(T[i++]=C[S++],b>1&&(T[i++]=C[S++]))}else{S=i-x;do T[i++]=T[S++],T[i++]=T[S++],T[i++]=T[S++],b-=3;while(b>2);b&&(T[i++]=T[S++],b>1&&(T[i++]=T[S++]))}}else if(y&64){e.msg=`invalid distance code`,E.mode=zL;break top}else{v=h[(v&65535)+(f&(1<<y)-1)];continue dodist}break}}else if(!(y&64)){v=m[(v&65535)+(f&(1<<y)-1)];continue dolen}else if(y&32){E.mode=BL;break top}else{e.msg=`invalid literal/length code`,E.mode=zL;break top}break}}while(n<r&&i<o);b=p>>3,n-=b,p-=b<<3,f&=(1<<p)-1,e.next_in=n,e.next_out=i,e.avail_in=n<r?5+(r-n):5-(n-r),e.avail_out=i<o?257+(o-i):257-(i-o),E.hold=f,E.bits=p}var HL=15,UL=852,WL=592,GL=0,KL=1,qL=2,JL=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),YL=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,199,75]),XL=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ZL=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),QL=(e,t,n,r,i,a,o,s)=>{let c=s.bits,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0,y,b,x,S,C,w=null,T,E=new Uint16Array(16),D=new Uint16Array(16),ee=null,te,ne,re;for(l=0;l<=HL;l++)E[l]=0;for(u=0;u<r;u++)E[t[n+u]]++;for(p=c,f=HL;f>=1&&E[f]===0;f--);if(p>f&&(p=f),f===0)return i[a++]=20971520,i[a++]=20971520,s.bits=1,0;for(d=1;d<f&&E[d]===0;d++);for(p<d&&(p=d),g=1,l=1;l<=HL;l++)if(g<<=1,g-=E[l],g<0)return-1;if(g>0&&(e===GL||f!==1))return-1;for(D[1]=0,l=1;l<HL;l++)D[l+1]=D[l]+E[l];for(u=0;u<r;u++)t[n+u]!==0&&(o[D[t[n+u]]++]=u);if(e===GL?(w=ee=o,T=20):e===KL?(w=JL,ee=YL,T=257):(w=XL,ee=ZL,T=0),v=0,u=0,l=d,C=a,m=p,h=0,x=-1,_=1<<p,S=_-1,e===KL&&_>UL||e===qL&&_>WL)return 1;for(;;){te=l-h,o[u]+1<T?(ne=0,re=o[u]):o[u]>=T?(ne=ee[o[u]-T],re=w[o[u]-T]):(ne=96,re=0),y=1<<l-h,b=1<<m,d=b;do b-=y,i[C+(v>>h)+b]=te<<24|ne<<16|re|0;while(b!==0);for(y=1<<l-1;v&y;)y>>=1;if(y===0?v=0:(v&=y-1,v+=y),u++,--E[l]===0){if(l===f)break;l=t[n+o[u]]}if(l>p&&(v&S)!==x){for(h===0&&(h=p),C+=d,m=l-h,g=1<<m;m+h<f&&(g-=E[m+h],!(g<=0));)m++,g<<=1;if(_+=1<<m,e===KL&&_>UL||e===qL&&_>WL)return 1;x=v&S,i[x]=p<<24|m<<16|C-a|0}}return v!==0&&(i[C+v]=l-h<<24|4194304),s.bits=p,0},$L=0,eR=1,tR=2,nR=16180,rR=16181,iR=16182,aR=16183,oR=16184,sR=16185,cR=16186,lR=16187,uR=16188,dR=16189,fR=16190,pR=16191,mR=16192,hR=16193,gR=16194,_R=16195,vR=16196,yR=16197,bR=16198,xR=16199,SR=16200,CR=16201,wR=16202,TR=16203,ER=16204,DR=16205,OR=16206,kR=16207,AR=16208,jR=16209,MR=16210,NR=16211,PR=852,FR=592,IR=e=>(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24),LR=class{constructor(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}},RR=e=>{if(!e)return 1;let t=e.state;return+(!t||t.strm!==e||t.mode<nR||t.mode>NR)},zR=e=>{if(RR(e))return-2;let t=e.state;return e.total_in=e.total_out=t.total=0,e.msg=``,t.wrap&&(e.adler=t.wrap&1),t.mode=nR,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(PR),t.distcode=t.distdyn=new Int32Array(FR),t.sane=1,t.back=-1,0},BR=e=>{if(RR(e))return-2;let t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,zR(e)},VR=(e,t)=>{let n;if(RR(e))return-2;let r=e.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?-2:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,BR(e))},HR=(e,t)=>{if(!e)return-2;let n=new LR;e.state=n,n.strm=e,n.window=null,n.mode=nR;let r=VR(e,t);return r!==0&&(e.state=null),r},UR=!0,WR,GR,KR=e=>{if(UR){WR=new Int32Array(512),GR=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(QL(eR,e.lens,0,288,WR,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;QL(tR,e.lens,0,32,GR,0,e.work,{bits:5}),UR=!1}e.lencode=WR,e.lenbits=9,e.distcode=GR,e.distbits=5},qR=(e,t,n,r)=>{let i,a=e.state;return a.window===null&&(a.window=new Uint8Array(1<<a.wbits)),a.wsize===0&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0),r>=a.wsize?(a.window.set(t.subarray(n-a.wsize,n),0),a.wnext=0,a.whave=a.wsize):(i=a.wsize-a.wnext,i>r&&(i=r),a.window.set(t.subarray(n-r,n-r+i),a.wnext),r-=i,r?(a.window.set(t.subarray(n-r,n),0),a.wnext=r,a.whave=a.wsize):(a.wnext+=i,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=i))),0},JR=(e,t)=>{let n,r,i,a,o,s,c,l,u,d,f,p,m,h,g=0,_,v,y,b,x,S,C,w,T=new Uint8Array(4),E,D,ee=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(RR(e)||!e.output||!e.input&&e.avail_in!==0)return-2;n=e.state,n.mode===pR&&(n.mode=mR),o=e.next_out,i=e.output,c=e.avail_out,a=e.next_in,r=e.input,s=e.avail_in,l=n.hold,u=n.bits,d=s,f=c,w=0;inf_leave:for(;;)switch(n.mode){case nR:if(n.wrap===0){n.mode=mR;break}for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.wrap&2&&l===35615){n.wbits===0&&(n.wbits=15),n.check=0,T[0]=l&255,T[1]=l>>>8&255,n.check=UI(n.check,T,2,0),l=0,u=0,n.mode=rR;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg=`incorrect header check`,n.mode=jR;break}if((l&15)!=8){e.msg=`unknown compression method`,n.mode=jR;break}if(l>>>=4,u-=4,C=(l&15)+8,n.wbits===0&&(n.wbits=C),C>15||C>n.wbits){e.msg=`invalid window size`,n.mode=jR;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=l&512?dR:pR,l=0,u=0;break;case rR:for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.flags=l,(n.flags&255)!=8){e.msg=`unknown compression method`,n.mode=jR;break}if(n.flags&57344){e.msg=`unknown header flags set`,n.mode=jR;break}n.head&&(n.head.text=l>>8&1),n.flags&512&&n.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,n.check=UI(n.check,T,2,0)),l=0,u=0,n.mode=iR;case iR:for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.head&&(n.head.time=l),n.flags&512&&n.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,T[2]=l>>>16&255,T[3]=l>>>24&255,n.check=UI(n.check,T,4,0)),l=0,u=0,n.mode=aR;case aR:for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.head&&(n.head.xflags=l&255,n.head.os=l>>8),n.flags&512&&n.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,n.check=UI(n.check,T,2,0)),l=0,u=0,n.mode=oR;case oR:if(n.flags&1024){for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.length=l,n.head&&(n.head.extra_len=l),n.flags&512&&n.wrap&4&&(T[0]=l&255,T[1]=l>>>8&255,n.check=UI(n.check,T,2,0)),l=0,u=0}else n.head&&(n.head.extra=null);n.mode=sR;case sR:if(n.flags&1024&&(p=n.length,p>s&&(p=s),p&&(n.head&&(C=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(a,a+p),C)),n.flags&512&&n.wrap&4&&(n.check=UI(n.check,r,p,a)),s-=p,a+=p,n.length-=p),n.length))break inf_leave;n.length=0,n.mode=cR;case cR:if(n.flags&2048){if(s===0)break inf_leave;p=0;do C=r[a+p++],n.head&&C&&n.length<65536&&(n.head.name+=String.fromCharCode(C));while(C&&p<s);if(n.flags&512&&n.wrap&4&&(n.check=UI(n.check,r,p,a)),s-=p,a+=p,C)break inf_leave}else n.head&&(n.head.name=null);n.length=0,n.mode=lR;case lR:if(n.flags&4096){if(s===0)break inf_leave;p=0;do C=r[a+p++],n.head&&C&&n.length<65536&&(n.head.comment+=String.fromCharCode(C));while(C&&p<s);if(n.flags&512&&n.wrap&4&&(n.check=UI(n.check,r,p,a)),s-=p,a+=p,C)break inf_leave}else n.head&&(n.head.comment=null);n.mode=uR;case uR:if(n.flags&512){for(;u<16;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.wrap&4&&l!==(n.check&65535)){e.msg=`header crc mismatch`,n.mode=jR;break}l=0,u=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=pR;break;case dR:for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}e.adler=n.check=IR(l),l=0,u=0,n.mode=fR;case fR:if(n.havedict===0)return e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,2;e.adler=n.check=1,n.mode=pR;case pR:if(t===5||t===6)break inf_leave;case mR:if(n.last){l>>>=u&7,u-=u&7,n.mode=OR;break}for(;u<3;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}switch(n.last=l&1,l>>>=1,--u,l&3){case 0:n.mode=hR;break;case 1:if(KR(n),n.mode=xR,t===6){l>>>=2,u-=2;break inf_leave}break;case 2:n.mode=vR;break;case 3:e.msg=`invalid block type`,n.mode=jR}l>>>=2,u-=2;break;case hR:for(l>>>=u&7,u-=u&7;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if((l&65535)!=(l>>>16^65535)){e.msg=`invalid stored block lengths`,n.mode=jR;break}if(n.length=l&65535,l=0,u=0,n.mode=gR,t===6)break inf_leave;case gR:n.mode=_R;case _R:if(p=n.length,p){if(p>s&&(p=s),p>c&&(p=c),p===0)break inf_leave;i.set(r.subarray(a,a+p),o),s-=p,a+=p,c-=p,o+=p,n.length-=p;break}n.mode=pR;break;case vR:for(;u<14;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.nlen=(l&31)+257,l>>>=5,u-=5,n.ndist=(l&31)+1,l>>>=5,u-=5,n.ncode=(l&15)+4,l>>>=4,u-=4,n.nlen>286||n.ndist>30){e.msg=`too many length or distance symbols`,n.mode=jR;break}n.have=0,n.mode=yR;case yR:for(;n.have<n.ncode;){for(;u<3;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.lens[ee[n.have++]]=l&7,l>>>=3,u-=3}for(;n.have<19;)n.lens[ee[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,E={bits:n.lenbits},w=QL($L,n.lens,0,19,n.lencode,0,n.work,E),n.lenbits=E.bits,w){e.msg=`invalid code lengths set`,n.mode=jR;break}n.have=0,n.mode=bR;case bR:for(;n.have<n.nlen+n.ndist;){for(;g=n.lencode[l&(1<<n.lenbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(y<16)l>>>=_,u-=_,n.lens[n.have++]=y;else{if(y===16){for(D=_+2;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(l>>>=_,u-=_,n.have===0){e.msg=`invalid bit length repeat`,n.mode=jR;break}C=n.lens[n.have-1],p=3+(l&3),l>>>=2,u-=2}else if(y===17){for(D=_+3;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=_,u-=_,C=0,p=3+(l&7),l>>>=3,u-=3}else{for(D=_+7;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=_,u-=_,C=0,p=11+(l&127),l>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){e.msg=`invalid bit length repeat`,n.mode=jR;break}for(;p--;)n.lens[n.have++]=C}}if(n.mode===jR)break;if(n.lens[256]===0){e.msg=`invalid code -- missing end-of-block`,n.mode=jR;break}if(n.lenbits=9,E={bits:n.lenbits},w=QL(eR,n.lens,0,n.nlen,n.lencode,0,n.work,E),n.lenbits=E.bits,w){e.msg=`invalid literal/lengths set`,n.mode=jR;break}if(n.distbits=6,n.distcode=n.distdyn,E={bits:n.distbits},w=QL(tR,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,E),n.distbits=E.bits,w){e.msg=`invalid distances set`,n.mode=jR;break}if(n.mode=xR,t===6)break inf_leave;case xR:n.mode=SR;case SR:if(s>=6&&c>=258){e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,VL(e,f),o=e.next_out,i=e.output,c=e.avail_out,a=e.next_in,r=e.input,s=e.avail_in,l=n.hold,u=n.bits,n.mode===pR&&(n.back=-1);break}for(n.back=0;g=n.lencode[l&(1<<n.lenbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(v&&!(v&240)){for(b=_,x=v,S=y;g=n.lencode[S+((l&(1<<b+x)-1)>>b)],_=g>>>24,v=g>>>16&255,y=g&65535,!(b+_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=b,u-=b,n.back+=b}if(l>>>=_,u-=_,n.back+=_,n.length=y,v===0){n.mode=DR;break}if(v&32){n.back=-1,n.mode=pR;break}if(v&64){e.msg=`invalid literal/length code`,n.mode=jR;break}n.extra=v&15,n.mode=CR;case CR:if(n.extra){for(D=n.extra;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.length+=l&(1<<n.extra)-1,l>>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=wR;case wR:for(;g=n.distcode[l&(1<<n.distbits)-1],_=g>>>24,v=g>>>16&255,y=g&65535,!(_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(!(v&240)){for(b=_,x=v,S=y;g=n.distcode[S+((l&(1<<b+x)-1)>>b)],_=g>>>24,v=g>>>16&255,y=g&65535,!(b+_<=u);){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}l>>>=b,u-=b,n.back+=b}if(l>>>=_,u-=_,n.back+=_,v&64){e.msg=`invalid distance code`,n.mode=jR;break}n.offset=y,n.extra=v&15,n.mode=TR;case TR:if(n.extra){for(D=n.extra;u<D;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}n.offset+=l&(1<<n.extra)-1,l>>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg=`invalid distance too far back`,n.mode=jR;break}n.mode=ER;case ER:if(c===0)break inf_leave;if(p=f-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg=`invalid distance too far back`,n.mode=jR;break}p>n.wnext?(p-=n.wnext,m=n.wsize-p):m=n.wnext-p,p>n.length&&(p=n.length),h=n.window}else h=i,m=o-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do i[o++]=h[m++];while(--p);n.length===0&&(n.mode=SR);break;case DR:if(c===0)break inf_leave;i[o++]=n.length,c--,n.mode=SR;break;case OR:if(n.wrap){for(;u<32;){if(s===0)break inf_leave;s--,l|=r[a++]<<u,u+=8}if(f-=c,e.total_out+=f,n.total+=f,n.wrap&4&&f&&(e.adler=n.check=n.flags?UI(n.check,i,f,o-f):VI(n.check,i,f,o-f)),f=c,n.wrap&4&&(n.flags?l:IR(l))!==n.check){e.msg=`incorrect data check`,n.mode=jR;break}l=0,u=0}n.mode=kR;case kR:if(n.wrap&&n.flags){for(;u<32;){if(s===0)break inf_leave;s--,l+=r[a++]<<u,u+=8}if(n.wrap&4&&l!==(n.total&4294967295)){e.msg=`incorrect length check`,n.mode=jR;break}l=0,u=0}n.mode=AR;case AR:w=1;break inf_leave;case jR:w=-3;break inf_leave;case MR:return-4;case NR:default:return-2}return e.next_out=o,e.avail_out=c,e.next_in=a,e.avail_in=s,n.hold=l,n.bits=u,(n.wsize||f!==e.avail_out&&n.mode<jR&&(n.mode<OR||t!==4))&&qR(e,e.output,e.next_out,f-e.avail_out)?(n.mode=MR,-4):(d-=e.avail_in,f-=e.avail_out,e.total_in+=d,e.total_out+=f,n.total+=f,n.wrap&4&&f&&(e.adler=n.check=n.flags?UI(n.check,i,f,e.next_out-f):VI(n.check,i,f,e.next_out-f)),e.data_type=n.bits+(n.last?64:0)+(n.mode===pR?128:0)+(n.mode===xR||n.mode===gR?256:0),(d===0&&f===0||t===4)&&w===0&&(w=-5),w)},YR=e=>{if(RR(e))return-2;let t=e.state;return t.window&&=null,e.state=null,0},XR=(e,t)=>{let n=t.length,r,i,a;return RR(e)||(r=e.state,r.wrap!==0&&r.mode!==fR)?-2:r.mode===fR&&(i=1,i=VI(i,t,n,0),i!==r.check)?-3:(a=qR(e,t,n,n),a?(r.mode=MR,-4):(r.havedict=1,0))},ZR=class{constructor(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=``,this.state=null,this.data_type=2,this.adler=0}},QR=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},$R=Object.prototype.toString,ez={level:-1,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,raw:!1,gzip:!1,legacyHash:!1,dictionary:new Uint8Array},tz=class{options;err;msg;ended;started;chunks;strm;result;constructor(e={}){this.options=Object.assign({},ez,e);let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg=``,this.ended=!1,this.started=!1,this.chunks=[],this.result=new Uint8Array,this.strm=new ZR,this.strm.avail_out=0;let n=FL(this.strm,t.level,8,t.windowBits,t.memLevel,t.strategy,t.legacyHash);if(n!==0)throw Error(WI[n]);$R.call(t.dictionary)===`[object ArrayBuffer]`&&(t.dictionary=new Uint8Array(t.dictionary));let r=t.dictionary;if(r.length){if(t.gzip)throw Error(`dictionary is not supported with gzip`);if(n=RL(this.strm,r),n!==0)throw Error(WI[n])}}push(e,t=!1){let n=this.strm,r=this.options.chunkSize,i,a;if(this.ended)return!1;for(a=typeof t==`number`?t:t===!0?4:0,n.input=typeof e==`string`?new TextEncoder().encode(e):$R.call(e)===`[object ArrayBuffer]`?new Uint8Array(e):e,n.next_in=0,n.avail_in=n.input.length,this.started||(this.started=!0,this.onStart(n));;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),(a===2||a===3)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(i=IL(n,a),i===-2)break;if(i===1){n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),i=LL(this.strm);break}if(n.avail_out===0){this.onData(n.output);continue}if(a>0&&n.next_out>0){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(n.avail_in===0)return!0}return this.err=i,this.msg=n.msg||WI[i],this.ended=!0,this.onEnd(i),i===0}onStart(e){}onData(e){this.chunks.push(e)}onEnd(e){e===0&&(this.result=QR(this.chunks)),this.chunks=[]}};function nz(e,t={}){let n=new tz(t);if(n.push(e,!0),n.err)throw Error(n.msg);return n.result}function rz(e,t={}){return nz(e,Object.assign({},t,{raw:!0}))}function iz(e,t={}){return nz(e,Object.assign({},t,{gzip:!0}))}var az=Object.prototype.toString,oz={chunkSize:65536,windowBits:15,raw:!1,dictionary:new Uint8Array},sz=class{options;err;msg;ended;started;chunks;strm;result;constructor(e={}){this.options=Object.assign({},oz,e);let t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!e.windowBits&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg=``,this.ended=!1,this.started=!1,this.chunks=[],this.result=new Uint8Array,this.strm=new ZR,this.strm.avail_out=0;let n=HR(this.strm,t.windowBits);if(n!==0)throw Error(WI[n]);az.call(t.dictionary)===`[object ArrayBuffer]`&&(t.dictionary=new Uint8Array(t.dictionary));let r=t.dictionary;if(t.raw&&r.length&&(n=XR(this.strm,r),n!==0))throw Error(WI[n])}push(e,t=!1){let n=this.strm,r=this.options.chunkSize,i,a,o;if(this.ended)return this.err===0;for(a=typeof t==`number`?t:t===!0?4:0,n.input=az.call(e)===`[object ArrayBuffer]`?new Uint8Array(e):e,n.next_in=0,n.avail_in=n.input.length,this.started||(this.started=!0,this.onStart(n));;){if(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),i=JR(n,a),i===2){let e=this.options.dictionary;e.length&&(i=XR(n,e),i===0?i=JR(n,a):i===-3&&(i=2))}for(;n.avail_in>0&&i===1&&n.state.wrap&2&&n.state.flags!==0&&n.input[n.next_in]!==0;)BR(n),i=JR(n,a);if(i===-2||i===-3||i===2||i===-4)break;if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===1||a>0)&&(this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out)),n.avail_out=0,n.next_out=0),i!==0&&i!==-5||o!==0){if(i===1){i=YR(this.strm);break}if(n.avail_in===0){if(a===4){i=YR(this.strm),i===0&&(i=-5);break}return!0}}}return this.err=i,this.msg=n.msg||WI[i],this.ended=!0,this.onEnd(i),i===0}onStart(e){}onData(e){this.chunks.push(e)}onEnd(e){e===0&&(this.result=QR(this.chunks)),this.chunks=[]}};function cz(e,t={}){let n=new sz(t);if(n.push(e,!0),n.err)throw Error(n.msg);let r=n.result;return t.toText?new TextDecoder().decode(r):r}function lz(e,t={}){return cz(e,{...t,raw:!0})}function uz(e){return typeof e==`string`?new Uint8Array(wP(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function dz(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 fz(e,t,n){return wP(e(uz(t),dz(n)))}function pz(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=fz(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const mz={gzipSync:(e,t)=>fz(iz,e,t),gunzipSync:(e,t)=>fz(cz,e,t),deflateSync:(e,t)=>fz(nz,e,t),inflateSync:(e,t)=>fz(cz,e,t),deflateRawSync:(e,t)=>fz(rz,e,t),inflateRawSync:(e,t)=>fz(lz,e,t),gzip:(e,t,n)=>pz(iz,e,t,n),gunzip:(e,t,n)=>pz(cz,e,t,n),deflate:(e,t,n)=>pz(nz,e,t,n),inflate:(e,t,n)=>pz(cz,e,t,n),deflateRaw:(e,t,n)=>pz(rz,e,t,n),inflateRaw:(e,t,n)=>pz(lz,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}};function hz(e){let t=[],n={},r=[],i=(e,t)=>{if(e in n){let r=n[e];Array.isArray(r)?r.push(String(t)):n[e]=[String(r),String(t)]}else n[e]=t},a=2;for(;a<e.length;){let n=e[a];if(n===`--`){r.push(...e.slice(a+1));break}if(n.startsWith(`--`)){let t=n.slice(2),r=t.indexOf(`=`);if(r!==-1){i(t.slice(0,r),t.slice(r+1)),a++;continue}let o=e[a+1];if(o!==void 0&&!o.startsWith(`-`)){i(t,o),a+=2;continue}i(t,!0),a++;continue}if(n.startsWith(`-`)&&n.length>1){for(let e of n.slice(1))i(e,!0);a++;continue}t.push(n),a++}return{positional:t,flags:n,subcommand:t.length>0&&/^[a-z][\w-]*$/i.test(t[0])?t[0]:null,passthrough:r}}function gz(e){let t=[...e];return Object.defineProperty(t,"parseFlags",{value:()=>hz(t),enumerable:!1,writable:!1,configurable:!1}),t}const _z=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},vz={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function yz(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*vz[i])}function bz(e){return e<10?`0${e}`:String(e)}const xz={parseDuration:yz,ago(e,t=new Date){return new Date(t.getTime()-yz(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-yz(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+yz(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-yz(e));return`${n.getFullYear()}/${bz(n.getMonth()+1)}/${bz(n.getDate())}`}};function Sz(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var Cz=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function wz(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Tz(e,t){return{log:(...t)=>e(`${t.map(wz).join(` `)}
|
|
1647
1647
|
`),info:(...t)=>e(`${t.map(wz).join(` `)}
|
|
1648
1648
|
`),warn:(...e)=>t(`${e.map(wz).join(` `)}
|
|
@@ -1650,7 +1650,7 @@ except BaseException:
|
|
|
1650
1650
|
`)}}function Ez(e,t,n){let r=!!e.env?.NO_COLOR,i=!1,a=0,o=e=>{i=!0,a=e},s=Oz(e.stdin??``,o),c=gz(e.argv),l={write:t,end:()=>void 0,isTTY:!r},u={write:n,end:()=>void 0,isTTY:!r};return{processShim:{argv:c,env:e.env,versions:{node:yr},version:`v${yr}`,platform:`linux`,arch:`x64`,cwd:()=>e.cwd,exit:e=>{let t=Number.isFinite(e)?Number(e):0;throw o(t),new Cz(t)},stdin:s,stdout:l,stderr:u},getDidCallProcessExit:()=>i,getExitCode:()=>a,recordExit:o}}var Dz=class extends jP.Stream{isTTY=!1;consumed=!1;flowScheduled=!1;paused=!1;buffer;onExit;constructor(e,t){super(),this.buffer=e,this.onExit=t}read(){return this.consumed?null:(this.consumed=!0,this.buffer.length>0?this.buffer:null)}toString(){return this.buffer}setEncoding(e){return this}pause(){return this.paused=!0,this}resume(){return this.paused=!1,this.scheduleFlow(),this}on(e,t){return super.on(e,t),e===`data`&&this.scheduleFlow(),this}addListener(e,t){return this.on(e,t)}once(e,t){return super.once(e,t),e===`data`&&this.scheduleFlow(),this}scheduleFlow(){this.flowScheduled||(this.flowScheduled=!0,queueMicrotask(()=>this.flush()))}flush(){if(this.paused){this.flowScheduled=!1;return}try{this.consumed||(this.consumed=!0,this.buffer.length>0&&this.emit(`data`,this.buffer)),this.readable=!1,this.emit(`end`),this.emit(`close`)}catch(e){if(e instanceof Cz){this.onExit(e.code);return}throw e}}[Symbol.asyncIterator](){return{next:async()=>this.consumed?{value:void 0,done:!0}:(this.consumed=!0,{value:this.buffer,done:!1})}}};function Oz(e,t){return new Dz(e,t)}function kz(e){if(e===``)return[];let t=e.split(`
|
|
1651
1651
|
`);return t[t.length-1]===``&&t.pop(),t.map(e=>e.endsWith(`\r`)?e.slice(0,-1):e)}function Az(e){if(typeof e==`string`)return e;if(e&&typeof e.read==`function`){let t=e.read();return typeof t==`string`?t:``}return``}function jz(e){return new TextDecoder(`utf-8`).decode(PN(e))}function Mz(e){if(e&&typeof e.write==`function`)return e}var Nz=class extends TP{terminal=!1;lines;cursor=0;closed=!1;flushScheduled=!1;output;onExit;constructor(e,t,n){super(),this.lines=kz(jz(Az(e))),this.output=t??n.output,this.onExit=n.onExit}on(e,t){return super.on(e,t),e===`line`&&this.scheduleFlush(),this}once(e,t){return super.once(e,t),e===`line`&&this.scheduleFlush(),this}pause(){return this}resume(){return this}close(){this.closed||(this.closed=!0,this.emit(`close`))}question(e,t,n){let r=typeof t==`function`?t:typeof n==`function`?n:void 0;this.output?.write(String(e));let i=this.cursor<this.lines.length?this.lines[this.cursor++]:``;if(r){queueMicrotask(()=>this.runHandler(()=>r(i)));return}return Promise.resolve(i)}[Symbol.asyncIterator](){return{next:async()=>!this.closed&&this.cursor<this.lines.length?{value:this.lines[this.cursor++],done:!1}:(this.close(),{value:void 0,done:!0})}}scheduleFlush(){this.flushScheduled||this.closed||(this.flushScheduled=!0,queueMicrotask(()=>this.flush()))}flush(){this.flushScheduled=!1,this.runHandler(()=>{for(;!this.closed&&this.cursor<this.lines.length;)this.emit(`line`,this.lines[this.cursor++]);this.close()})}runHandler(e){try{e()}catch(e){if(e instanceof Cz&&this.onExit){this.closed=!0,this.onExit(e.code);return}throw e}}};function Pz(e){let t=(t,n)=>{let r,i;if(t&&typeof t==`object`&&`input`in t){let e=t;r=e.input,i=Mz(e.output)}else r=t,i=Mz(n);if(r==null)throw TypeError(`readline.createInterface: an 'input' stream is required`);return new Nz(r,i,e)},n=(...e)=>{let t=e[e.length-1];return typeof t==`function`&&queueMicrotask(()=>t()),!0},r={createInterface:t,Interface:Nz,emitKeypressEvents:()=>void 0,cursorTo:n,moveCursor:n,clearLine:n,clearScreenDown:n};return{...r,promises:r}}var Fz=class extends Error{status;statusText;url;body;constructor(e,t,n,r){let i=typeof r==`string`&&r?`: ${r.slice(0,200)}`:r&&typeof r==`object`?`: ${Iz(r).slice(0,200)}`:``;super(`HTTP ${e} ${t} ${n}${i}`),this.status=e,this.statusText=t,this.url=n,this.body=r,this.name=`HttpError`}};function Iz(e){try{return JSON.stringify(e)}catch{return String(e)}}function Lz(e){return new Promise(t=>setTimeout(t,e))}function Rz(e,t,n){let r;if(r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:e?`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`:t,!n)return r;let i=[];for(let[e,t]of Object.entries(n))if(t!=null)if(Array.isArray(t))for(let n of t)n!=null&&i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);else i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`);return i.length===0?r:r+(r.includes(`?`)?`&`:`?`)+i.join(`&`)}function zz(e,t){let n={};if(e)for(let[t,r]of Object.entries(e))n[t]=r;if(t)for(let[e,r]of Object.entries(t))n[e]=r;return n}function Bz(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function Vz(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3)}let n=Date.parse(t);if(Number.isFinite(n)){let e=n-Date.now();return e>0?e:0}return null}async function Hz(e){if(Bz(e.headers.get(`content-type`))){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}return e.text()}function Uz(e,t){if(e!=null)return typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob||typeof FormData<`u`&&e instanceof FormData||typeof URLSearchParams<`u`&&e instanceof URLSearchParams||typeof ReadableStream<`u`&&e instanceof ReadableStream?e:typeof e==`object`?(Object.keys(t).some(e=>e.toLowerCase()===`content-type`)||(t[`Content-Type`]=`application/json`),JSON.stringify(e)):String(e)}function Wz(e){let t=e.sleep??Lz;function n(n){let r=new Set(n.retry?.on??[]),i=Math.max(1,Math.trunc(n.retry?.maxAttempts??1));async function a(a,o,s={}){let c=Rz(n.baseUrl,o,s.params),l=zz(n.headers,s.headers);if(n.token){let e=await n.token({method:a,path:o,url:c});e&&(Object.keys(l).some(e=>e.toLowerCase()===`authorization`)||(l.Authorization=`Bearer ${e}`))}let u=Uz(s.body,l),d={method:a,headers:l};u!==void 0&&(d.body=u);let f=null;for(let a=0;a<i;a++){let o=n.timeoutMs?new AbortController:null,l=o?setTimeout(()=>o.abort(Error(`timeout`)),n.timeoutMs):null,u=s.signal&&o?.signal?AbortSignal.any([s.signal,o.signal]):s.signal??o?.signal,p=u?{...d,signal:u}:d,m;try{m=await e.fetch(c,p)}finally{l!==null&&clearTimeout(l)}if(f=m,m.ok){let e=await Hz(m);return s.raw?{body:e,headers:Object.fromEntries(m.headers.entries()),status:m.status}:e}if(!(a+1<i&&r.has(m.status))){let e=await Hz(m).catch(()=>null);throw new Fz(m.status,m.statusText,c,e)}let h=Vz(m.headers.get(`retry-after`)),g=500*2**a;await t(h===null?g:h)}if(f){let e=await Hz(f).catch(()=>null);throw new Fz(f.status,f.statusText,c,e)}throw Error(`http: no attempts made for ${a} ${c}`)}return Object.freeze({get:((e,t)=>a(`GET`,e,t)),post:((e,t)=>a(`POST`,e,t)),put:((e,t)=>a(`PUT`,e,t)),patch:((e,t)=>a(`PATCH`,e,t)),delete:((e,t)=>a(`DELETE`,e,t))})}return Object.freeze({client:n})}function Gz(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 Kz(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`,Gz(JSON.stringify(t.schema))),t.readOnly!==void 0&&r.push(`--read-only`,Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly));let i=t.cwd===void 0?n||`.`:String(t.cwd),a=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,i,a,String(e)]}function qz(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(Kz(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 Jz(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 Yz(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:Jz(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Xz(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:Jz(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Jz(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Jz(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Yz(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Zz(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 Qz(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 $z(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 Xz(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=Zz(c),d=Qz(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function eB(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 tB(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=eB(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 nB(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 rB(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 rB(e){if(typeof e==`string`||e instanceof URLSearchParams)return{body:e.toString()};if(e instanceof Blob)return{body:iB(new Uint8Array(await e.arrayBuffer())),defaultContentType:e.type||`application/octet-stream`};if(e instanceof ArrayBuffer)return{body:iB(new Uint8Array(e)),defaultContentType:`application/octet-stream`};if(ArrayBuffer.isView(e))return{body:iB(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 iB(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 aB(e){return{findTab:t=>e.call(`browser`,`findTab`,[sB(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,cB(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[eB(t),oB(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[eB(t),oB(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[eB(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[eB(t),n]),fetch:(t,n,r={})=>$z(n,r).then(n=>e.call(`browser`,`evalAsync`,[eB(t),n])),websocket:tB(e)}}function oB(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 sB(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 cB(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function lB(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function uB(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();if(n.created.length||n.modified.length||n.deleted.length)try{await e.call(`vfs`,`flushWrites`,[n])}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`[realm-exec] pre-exec sync-fs flush failed (will retry at exit): ${t}`);return}t.resetBaseline()},a=async(i=!1)=>{if(t?.wasUsed())try{let r=await e.call(`vfs`,`snapshot`,[n]);i?t.applySnapshotPreservingMutations(r):t.applySnapshot(r)}catch(e){let t=e instanceof Error?e.message:String(e);r?.(`[sync-fs] re-snapshot after exec failed: ${t}\n`)}},o=async t=>{await i();try{return await e.call(`exec`,`run`,[t])}finally{await a()}},s=async t=>{await i();try{return await e.call(`exec`,`spawn`,[t])}finally{await a()}},c=1,l=Object.assign(o,{spawn:s,start:(t,n)=>{let r=c++,o=[],s=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(s||u||l)return;l=!0;let c=o.length>0?o.join(``):n?.stdin,p={};c!==void 0&&(p.stdin=c),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await i(),u){await a(!0);return}s=!0;let n=await e.call(`exec`,`start`,[r,t,p]);await a(!0),d(n)}catch(e){await a(!0),f(e)}})()};return{kill:t=>s?e.call(`exec`,`kill`,[r,t]):(u=!0,d({stdout:``,stderr:``,exitCode:lB(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function dB(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 fB(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pB(e){return e==null?[]:Array.isArray(e)?e:[e]}function mB(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:fB(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,dB(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,dB(r)]),receiveFeatureReport:async t=>fB((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 hB(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>mB(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[pB(t)]))[0];if(!n)throw Error(`No device selected.`);return mB(e,n)}}}function gB(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 _B=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 };`)}},vB=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=gB(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 _B(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 _B(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?.())}},yB=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 vB(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()}},bB=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 vB(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 yB(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 xB(e){let t=async t=>new bB(e),n=async(t,n)=>new bB(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const SB=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`]),CB={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 wB(e,t){let n=CB[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function TB(e){return{...e,time:xz,fmt:dP,pool:_z}}function EB(e,t){return e?.startsWith(`/`)?Sz(e):t}function DB(e){return e.includes(`require`)||e.includes(`import`)}async function OB(e,t,n,r){return DB(t)?e.call(`module`,`buildGraph`,[t,EB(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function kB(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 AB(e){return{playwright:xB(e)}}function jB(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={},nodeReadline:c}=e,l=new Map(t.files.map(e=>[e.path,e.cjsSource])),u=new Map(t.files.map(e=>[e.path,e.kind])),d=new Map,f=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:PB(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=MB(t,n,r,i,c);if(a.hit)return a;if(SB.has(t))throw wB(e,t);if(jr.has(t))throw IB(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},p=(e,n)=>{let r=f(n);if(r.hit)return r.value;let i=e?.[n];if(i)return m(i);throw n in t.errors?Error(t.errors[n]):NB(n)};function m(e){let n=d.get(e);if(n)return n.exports;let i=l.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};d.set(e,o);let s=n=>p(t.edges[e],n),c=Sz(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,c,e,r,a,globalThis.Buffer,globalThis),u.get(e)===`cjs`&&kB(o.exports),o.exports}return{require:e=>p(t.entryMap,e)}}function MB(e,t,n,r,i){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:AF}:e===`crypto`?{hit:!0,value:vF}: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:CP}:e===`assert/strict`?{hit:!0,value:SP}:e===`util`?{hit:!0,value:qP}:e===`events`?{hit:!0,value:EP}:e===`os`?{hit:!0,value:yF}:e===`tty`?{hit:!0,value:jF}:e===`stream`?{hit:!0,value:jP}:e===`url`?{hit:!0,value:PF}:e===`zlib`?{hit:!0,value:mz}:e===`readline`&&i?{hit:!0,value:i}:e===`readline/promises`&&i?{hit:!0,value:i.promises}:{hit:!1}}function NB(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 PB(e,t){let n=e.slice(7);if(n===``)throw Error(`require('sliccy:'): empty sliccy: module name`);if(!Object.prototype.hasOwnProperty.call(t,n))throw Error(`require('${e}'): unknown sliccy: module '${n}'. Known names: ${Object.keys(t).sort().join(`, `)}`);return t[n]}const FB={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function IB(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${FB[t]||``}`)}async function LB(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";
|
|
1652
1652
|
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof Cz?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function RB(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?dB(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,dB(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function zB(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>RB(e,t)),request:async t=>RB(e,await e.call(`serial`,`request`,[pB(t)]))}}function BB(e,t){let n=t.handle,r=e=>({status:e.status,data:fB(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,dB(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,dB(r)])}}function VB(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>BB(e,t)),request:async t=>BB(e,await e.call(`usb`,`request`,[pB(t)]))}}function HB(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function UB(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function WB(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function GB(e){let t=HB(e.argv[1]??``),n=WB(t,`references`),r=WB(t,`assets`),i=WB(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)+`
|
|
1653
|
-
`),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 ${UB(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}const KB=new Map,qB=new Map;function JB(e){let t=crypto.randomUUID();return KB.set(t,e),t}function YB(e){return KB.get(e)??null}function XB(e,t){if(!KB.has(e))return t.abort(),()=>{};let n=qB.get(e);return n||(n=new Set,qB.set(e,n)),n.add(t),()=>{let n=qB.get(e);n&&(n.delete(t),n.size===0&&qB.delete(e))}}function ZB(e){KB.delete(e);let t=qB.get(e);if(t){qB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function QB(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 $B(e){let t=YB(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return QB(e)}}function eV(e){return`slicc-sync-fs-`+e}const tV=`sync-fs-ack`,nV=`sync-fs-res`,rV=6e5,iV=5e3,aV=`exec`;function oV(e){return e.channel===aV}function sV(e){let{command:t}=e;if(Array.isArray(t)){if(t.length===0||!t.every(e=>typeof e==`string`))return{errno:`EINVAL`,message:`sync-exec: argv must be a non-empty string[]`};let[e,...n]=t;return{cmd:e,args:n}}return typeof t!=`string`||t.length===0?{errno:`EINVAL`,message:`sync-exec: command must be a non-empty string`}:e.args===void 0?{cmd:t}:!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)?{errno:`EINVAL`,message:`sync-exec: args must be a string[]`}:{cmd:t,args:e.args}}function cV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,rV)}async function lV(e){let t=YB(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-exec: unknown or revoked token`};if(!t.exec)return{ok:!1,errno:`ENOSYS`,message:`sync-exec: exec is not available`};let n=sV(e);if(`errno`in n)return{ok:!1,errno:n.errno,message:n.message};let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},cV(e.timeoutMs,rV)),o=XB(e.token,r);try{let i=await t.exec(n.cmd,{cwd:t.cwd,signal:r.signal,...n.args===void 0?{}:{args:n.args},...e.stdin===void 0?{}:{stdin:e.stdin}});return{ok:!0,kind:`json`,json:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}catch(e){return i?{ok:!1,errno:`ETIMEDOUT`,message:`sync-exec: timed out — ${e instanceof Error?e.message:String(e)}`}:r.signal.aborted?{ok:!1,errno:`ECANCELED`,message:`sync-exec: realm disposed`}:QB(e)}finally{clearTimeout(a),o()}}function uV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function dV(e){let t=pV(e);if(mV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw uV(`EIO`,e.label);hV(t,e.label)}function fV(e){let t=dV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw uV(`EIO`,e.label)}}function pV(e){let t=new XMLHttpRequest;try{t.open(e.method,e.url,!1),t.responseType=`arraybuffer`,t.timeout=e.timeoutMs,t.setRequestHeader(`x-slicc-fs-token`,e.token),e.body?t.send(new Uint8Array(e.body)):t.send()}catch{throw uV(`EIO`,e.label)}return t}function mV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function hV(e,t){throw uV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function gV(e){return(t,n,r)=>{let i=fV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:aV})),timeoutMs:n+iV,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw uV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function _V(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function vV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??gV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&_V(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=cV(t.timeout,n),l={command:e,...t.args===void 0?{}:{args:t.args},...t.input===void 0?{}:{stdin:t.input},timeoutMs:c};try{return a(l,c,s)}finally{o&&r.invalidate()}}}}function yV(e,t){return uV(e,`sync-fs bridge, '${t}'`)}function bV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function xV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:bV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return dV(r(`GET`,e))},writeFile(e,t){dV(r(`POST`,e,t))},stat(e){let t=fV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw yV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=fV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw yV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=fV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw yV(`EIO`,e);return t},exists(e){let t=fV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw yV(`EIO`,e);return t},mkdir(e){dV(r(`POST`,e,void 0,`mkdir`))},rm(e){dV(r(`POST`,e,void 0,`rm`))}}}const SV=new TextEncoder,CV=new TextDecoder;function wV(e){if(!e.ok)return{status:4,payload:SV.encode(JSON.stringify({errno:e.errno,message:e.message}))};switch(e.kind){case`bytes`:return{status:1,payload:e.bytes};case`json`:return{status:2,payload:SV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function TV(e,t){switch(e){case 1:return{ok:!0,kind:`bytes`,bytes:t};case 3:return{ok:!0,kind:`void`};case 2:try{return{ok:!0,kind:`json`,json:JSON.parse(CV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(CV.decode(t)),n=typeof e.errno==`string`&&/^E[A-Z]+$/.test(e.errno)?e.errno:`EIO`;return{ok:!1,errno:n,message:String(e.message??n)}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed errno payload`}}default:return{ok:!1,errno:`EIO`,message:`sync-sab: unknown status ${e}`}}}function EV(e){if(e.byteLength<4160)throw Error(`sync-sab: buffer too small (${e.byteLength} < 4160)`);return{header:new Int32Array(e,0,16),window:new Uint8Array(e,64)}}function DV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function OV(e,t,n={}){let{header:r,window:i}=EV(e),a=n.wait??((e,t,n,r)=>Atomics.wait(e,t,n,r)),o=n.now??(()=>performance.now()),s=0;function c(e,t,n){for(;;){let i=t-o();if(i<=0)throw uV(`ETIMEDOUT`,n);if(a(r,0,1,i),Atomics.load(r,0)===2&&Atomics.load(r,1)===e)return;Atomics.load(r,0)===2&&Atomics.store(r,0,1)}}return{call(e,n,a){let l=++s,u=o()+n,d=null,f=0,p=0;try{for(;;){Atomics.store(r,0,1);let n=p===0?{type:`sync-sab-req`,id:l,req:e}:{type:`sync-sab-next`,id:l,offset:p};try{t.postMessage(n)}catch{throw uV(`EIO`,a)}c(l,u,a);let o=Atomics.load(r,3),s=Atomics.load(r,4);if(Atomics.load(r,5)!==p||s<0||o<0||p+s>o)throw uV(`EIO`,a);if(d===null&&(f=Atomics.load(r,2),d=new Uint8Array(o)),d.set(i.subarray(0,s),p),p+=s,p>=o)break;if(s===0)throw uV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return TV(f,d)}}}function kV(e,t){return uV(e,`sync-sab bridge, '${t}'`)}function AV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function jV(e,t={}){let n=t.timeoutMs??25e3;function r(t,r){let i=e.call(t,n,`sync-sab bridge, '${r}'`);if(!i.ok)throw kV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw kV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw kV(`EIO`,t)}return{readFile:e=>i({op:`read`,path:e},e),writeFile:(e,t)=>{r({op:`write`,path:e,body:t},e)},stat:e=>{let t=a({op:`stat`,path:e},e);if(!AV(t))throw kV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!AV(t))throw kV(`EIO`,e);return t},readdir:e=>{let t=a({op:`readdir`,path:e},e);if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw kV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw kV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function MV(e){return(t,n,r)=>{let i=e.call({...t,channel:aV},n+iV,r);if(!i.ok)throw uV(i.errno,r);let a=i.kind===`json`?i.json:null;if(!a||typeof a.stdout!=`string`||typeof a.stderr!=`string`||typeof a.exitCode!=`number`)throw uV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function NV(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new MN(r)}function PV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function FV(e,t){return t?jV(t):e.syncFsToken?xV(e.syncFsToken):void 0}function IV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return OV(e.syncSab,t)}function LV(e,t,n,r,i){let a=IV(e,t),o=FV(e,a);if(Object.assign(r,QN(n,e.cwd,o,i)),e.syncFsToken)return vV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:MV(a)}:{}})}function RV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Ln().version,writable:!1,enumerable:!1,configurable:!1})}function zV(e,t,n){let r=tP({isTTY:!e,noColor:e});return{colorApi:r,cliApi:$N({writeStdout:t,writeStderr:n,exit:e=>{throw new Cz(e)},color:r})}}function BV(e,t,n){return{readStdinBytes:()=>PN(e.stdin??``),writeStdout:t,writeStderr:n}}function VV(e){return{usbBridge:VB(e),serialBridge:zB(e),hidBridge:hB(e)}}async function HV(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=Tz(i,a),s=Ez(e,i,a),{colorApi:c,cliApi:l}=zV(!!e.env?.NO_COLOR,i,a),u=new UM(t),d=BV(e,i,a),f=KN(u,C,d),p=await NV(u,e.cwd,PV(e,a)),m=LV(e,t,p,f,d),h=uB(u,p,e.cwd,a),g=qz(h,{cwd:e.cwd}),_=GB({argv:e.argv,fs:f,exec:h}),v=aB(u),{usbBridge:y,serialBridge:b,hidBridge:x}=VV(u),S=Wz({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await u.call(`fetch`,`request`,[n,await nB(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=TB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=Sz(T),D=await OB(u,e.code,e.cwd,T),ee=jB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:nF(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:AB(u),nodeReadline:Pz({output:{write:i},onExit:s.recordExit})}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0,re=D.entrySource??e.code,O=globalThis;RV(),O.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ie=await LB(re,{process:s.processShim,console:o,require:ee,module:te,exports:te.exports,fetch:C,__dirname:E,__filename:T},a,ne);await UV(u,p,a),s.getDidCallProcessExit()?ie=s.getExitCode():await WV(u),delete O.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ie})}async function UV(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 WV(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 GV(){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 KV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=GV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&HV(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 qV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=GV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&eN(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 JV=KV(),YV=qV();function XV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?QV():YV({kind:e,ctx:t}):typeof Worker<`u`?ZV():JV({kind:e,ctx:t})}function ZV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return $V(new Worker(new URL(`/assets/js-realm-worker-MogyAk2b.js`,``+import.meta.url),{type:`module`}))}function QV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return $V(new Worker(new URL(`/assets/py-realm-worker-B2OTI7Xc.js`,``+import.meta.url),{type:`module`}))}function $V(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,isolatedThread:!0,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function eH(){if(Dr())return decodeURIComponent(kr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function tH(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function nH(e){return e instanceof Error?e.message:String(e)}function rH(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function iH(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:rH(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function aH(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:rH(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const oH=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,sH=/\bimport\s*\.\s*meta\b/g;function cH(e,t){let n=JSON.stringify(t);return e.replace(oH,n).replace(sH,`({ url: ${n} })`)}async function lH(e,t,n,r){let i=await e();return i.transpileModule(cH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function uH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Br(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!wr(e))return e;let a=tH(t),o;try{return await iH(n,e,t,a)}catch(e){o=e}try{return await lH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${nH(o)}; typescript fallback: ${nH(e)}`)}}}function dH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Br(t));return async({source:e,filename:t})=>{if(!wr(e)&&!Ur(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?tH(t):void 0,o=i?t:`[eval].js`,s;try{return await aH(n,e,t,a)}catch(e){s=e}try{return await lH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${nH(s)}; typescript fallback: ${nH(e)}`)}}}function fH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1653
|
+
`),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 ${UB(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}const KB=new Map,qB=new Map;function JB(e){let t=crypto.randomUUID();return KB.set(t,e),t}function YB(e){return KB.get(e)??null}function XB(e,t){if(!KB.has(e))return t.abort(),()=>{};let n=qB.get(e);return n||(n=new Set,qB.set(e,n)),n.add(t),()=>{let n=qB.get(e);n&&(n.delete(t),n.size===0&&qB.delete(e))}}function ZB(e){KB.delete(e);let t=qB.get(e);if(t){qB.delete(e);for(let e of t)e.signal.aborted||e.abort()}}function QB(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 $B(e){let t=YB(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink,size:e.size}}}case`lstat`:{let e=await n.lstat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,isSymbolicLink:e.isSymbolicLink??!1,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return QB(e)}}function eV(e){return`slicc-sync-fs-`+e}const tV=`sync-fs-ack`,nV=`sync-fs-res`,rV=6e5,iV=5e3,aV=`exec`;function oV(e){return e.channel===aV}function sV(e){let{command:t}=e;if(Array.isArray(t)){if(t.length===0||!t.every(e=>typeof e==`string`))return{errno:`EINVAL`,message:`sync-exec: argv must be a non-empty string[]`};let[e,...n]=t;return{cmd:e,args:n}}return typeof t!=`string`||t.length===0?{errno:`EINVAL`,message:`sync-exec: command must be a non-empty string`}:e.args===void 0?{cmd:t}:!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`)?{errno:`EINVAL`,message:`sync-exec: args must be a string[]`}:{cmd:t,args:e.args}}function cV(e,t){return Math.min(typeof e!=`number`||!Number.isFinite(e)||e<=0?t:e,rV)}async function lV(e){let t=YB(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-exec: unknown or revoked token`};if(!t.exec)return{ok:!1,errno:`ENOSYS`,message:`sync-exec: exec is not available`};let n=sV(e);if(`errno`in n)return{ok:!1,errno:n.errno,message:n.message};let r=new AbortController,i=!1,a=setTimeout(()=>{i=!0,r.abort()},cV(e.timeoutMs,rV)),o=XB(e.token,r);try{let i=await t.exec(n.cmd,{cwd:t.cwd,signal:r.signal,...n.args===void 0?{}:{args:n.args},...e.stdin===void 0?{}:{stdin:e.stdin}});return{ok:!0,kind:`json`,json:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}catch(e){return i?{ok:!1,errno:`ETIMEDOUT`,message:`sync-exec: timed out — ${e instanceof Error?e.message:String(e)}`}:r.signal.aborted?{ok:!1,errno:`ECANCELED`,message:`sync-exec: realm disposed`}:QB(e)}finally{clearTimeout(a),o()}}function uV(e,t){return Object.assign(Error(`${e}: ${t}`),{code:e})}function dV(e){let t=pV(e);if(mV(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw uV(`EIO`,e.label);hV(t,e.label)}function fV(e){let t=dV(e);try{return JSON.parse(new TextDecoder().decode(t))}catch{throw uV(`EIO`,e.label)}}function pV(e){let t=new XMLHttpRequest;try{t.open(e.method,e.url,!1),t.responseType=`arraybuffer`,t.timeout=e.timeoutMs,t.setRequestHeader(`x-slicc-fs-token`,e.token),e.body?t.send(new Uint8Array(e.body)):t.send()}catch{throw uV(`EIO`,e.label)}return t}function mV(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}function hV(e,t){throw uV(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function gV(e){return(t,n,r)=>{let i=fV({method:`POST`,url:`/__slicc/exec-sync`,token:e,body:new TextEncoder().encode(JSON.stringify({...t,channel:aV})),timeoutMs:n+iV,label:r});if(!i||typeof i.stdout!=`string`||typeof i.stderr!=`string`||typeof i.exitCode!=`number`)throw uV(`EIO`,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}}function _V(e,t){let n=e.getMutations();for(let e of n.deleted)t.rm(e);for(let e of n.created)e.isDirectory?t.mkdir(e.path):t.writeFile(e.path,e.content);for(let e of n.modified)t.writeFile(e.path,e.content);e.resetBaseline()}function vV(e,t={}){let n=t.timeoutMs??12e4,{syncFs:r,fsBridge:i}=t,a=t.transport??gV(e);return{run(e,t={}){let o=r?.wasUsed()===!0&&i!==void 0;o&&_V(r,i);let s=`sync-exec bridge, '${Array.isArray(e)?e.join(` `):e}'`,c=cV(t.timeout,n),l={command:e,...t.args===void 0?{}:{args:t.args},...t.input===void 0?{}:{stdin:t.input},timeoutMs:c};try{return a(l,c,s)}finally{o&&r.invalidate()}}}}function yV(e,t){return uV(e,`sync-fs bridge, '${t}'`)}function bV(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function xV(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){return{method:t,url:bV(r,a),token:e,...i?{body:i}:{},timeoutMs:n,label:`sync-fs bridge, '${r}'`}}return{readFile(e){return dV(r(`GET`,e))},writeFile(e,t){dV(r(`POST`,e,t))},stat(e){let t=fV(r(`GET`,e,void 0,`stat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw yV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},lstat(e){let t=fV(r(`GET`,e,void 0,`lstat`));if(!t||typeof t.isFile!=`boolean`||typeof t.isDirectory!=`boolean`||typeof t.size!=`number`)throw yV(`EIO`,e);return{isFile:t.isFile,isDirectory:t.isDirectory,isSymbolicLink:t.isSymbolicLink,size:t.size}},readdir(e){let t=fV(r(`GET`,e,void 0,`readdir`));if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw yV(`EIO`,e);return t},exists(e){let t=fV(r(`GET`,e,void 0,`exists`));if(typeof t!=`boolean`)throw yV(`EIO`,e);return t},mkdir(e){dV(r(`POST`,e,void 0,`mkdir`))},rm(e){dV(r(`POST`,e,void 0,`rm`))}}}const SV=new TextEncoder,CV=new TextDecoder;function wV(e){if(!e.ok)return{status:4,payload:SV.encode(JSON.stringify({errno:e.errno,message:e.message}))};switch(e.kind){case`bytes`:return{status:1,payload:e.bytes};case`json`:return{status:2,payload:SV.encode(JSON.stringify(e.json))};default:return{status:3,payload:new Uint8Array}}}function TV(e,t){switch(e){case 1:return{ok:!0,kind:`bytes`,bytes:t};case 3:return{ok:!0,kind:`void`};case 2:try{return{ok:!0,kind:`json`,json:JSON.parse(CV.decode(t))}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed json payload`}}case 4:try{let e=JSON.parse(CV.decode(t)),n=typeof e.errno==`string`&&/^E[A-Z]+$/.test(e.errno)?e.errno:`EIO`;return{ok:!1,errno:n,message:String(e.message??n)}}catch{return{ok:!1,errno:`EIO`,message:`sync-sab: malformed errno payload`}}default:return{ok:!1,errno:`EIO`,message:`sync-sab: unknown status ${e}`}}}function EV(e){if(e.byteLength<4160)throw Error(`sync-sab: buffer too small (${e.byteLength} < 4160)`);return{header:new Int32Array(e,0,16),window:new Uint8Array(e,64)}}function DV(){if(typeof SharedArrayBuffer>`u`||typeof Atomics>`u`)return!1;let e=globalThis.crossOriginIsolated;return e===void 0||e===!0}function OV(e,t,n={}){let{header:r,window:i}=EV(e),a=n.wait??((e,t,n,r)=>Atomics.wait(e,t,n,r)),o=n.now??(()=>performance.now()),s=0;function c(e,t,n){for(;;){let i=t-o();if(i<=0)throw uV(`ETIMEDOUT`,n);if(a(r,0,1,i),Atomics.load(r,0)===2&&Atomics.load(r,1)===e)return;Atomics.load(r,0)===2&&Atomics.store(r,0,1)}}return{call(e,n,a){let l=++s,u=o()+n,d=null,f=0,p=0;try{for(;;){Atomics.store(r,0,1);let n=p===0?{type:`sync-sab-req`,id:l,req:e}:{type:`sync-sab-next`,id:l,offset:p};try{t.postMessage(n)}catch{throw uV(`EIO`,a)}c(l,u,a);let o=Atomics.load(r,3),s=Atomics.load(r,4);if(Atomics.load(r,5)!==p||s<0||o<0||p+s>o)throw uV(`EIO`,a);if(d===null&&(f=Atomics.load(r,2),d=new Uint8Array(o)),d.set(i.subarray(0,s),p),p+=s,p>=o)break;if(s===0)throw uV(`EIO`,a)}}finally{Atomics.store(r,0,0)}return TV(f,d)}}}function kV(e,t){return uV(e,`sync-sab bridge, '${t}'`)}function AV(e){let t=e;return!!t&&typeof t.isFile==`boolean`&&typeof t.isDirectory==`boolean`&&typeof t.size==`number`}function jV(e,t={}){let n=t.timeoutMs??25e3;function r(t,r){let i=e.call(t,n,`sync-sab bridge, '${r}'`);if(!i.ok)throw kV(i.errno,r);return i}function i(e,t){let n=r(e,t);if(n.ok&&n.kind===`bytes`)return n.bytes;throw kV(`EIO`,t)}function a(e,t){let n=r(e,t);if(n.ok&&n.kind===`json`)return n.json;throw kV(`EIO`,t)}return{readFile:e=>i({op:`read`,path:e},e),writeFile:(e,t)=>{r({op:`write`,path:e,body:t},e)},stat:e=>{let t=a({op:`stat`,path:e},e);if(!AV(t))throw kV(`EIO`,e);return t},lstat:e=>{let t=a({op:`lstat`,path:e},e);if(!AV(t))throw kV(`EIO`,e);return t},readdir:e=>{let t=a({op:`readdir`,path:e},e);if(!Array.isArray(t)||!t.every(e=>typeof e==`string`))throw kV(`EIO`,e);return t},exists:e=>{let t=a({op:`exists`,path:e},e);if(typeof t!=`boolean`)throw kV(`EIO`,e);return t},mkdir:e=>{r({op:`mkdir`,path:e},e)},rm:e=>{r({op:`rm`,path:e},e)}}}function MV(e){return(t,n,r)=>{let i=e.call({...t,channel:aV},n+iV,r);if(!i.ok)throw uV(i.errno,r);let a=i.kind===`json`?i.json:null;if(!a||typeof a.stdout!=`string`||typeof a.stderr!=`string`||typeof a.exitCode!=`number`)throw uV(`EIO`,r);return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}}async function NV(e,t,n){let r;try{r=await e.call(`vfs`,`snapshot`,[t])}catch(e){n?.(e instanceof Error?e.message:String(e)),r={entries:[]}}return new MN(r)}function PV(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function FV(e,t){return t?jV(t):e.syncFsToken?xV(e.syncFsToken):void 0}function IV(e,t){if(!(!e.syncSab||typeof Atomics>`u`||typeof Atomics.wait!=`function`))return OV(e.syncSab,t)}function LV(e,t,n,r,i){let a=IV(e,t),o=FV(e,a);if(Object.assign(r,QN(n,e.cwd,o,i)),e.syncFsToken)return vV(e.syncFsToken,{syncFs:n,...o?{fsBridge:o}:{},...a?{transport:MV(a)}:{}})}function RV(e=globalThis){Object.prototype.hasOwnProperty.call(e,`SLICC_VERSION`)||Object.defineProperty(e,"SLICC_VERSION",{value:Rn().version,writable:!1,enumerable:!1,configurable:!1})}function zV(e,t,n){let r=tP({isTTY:!e,noColor:e});return{colorApi:r,cliApi:$N({writeStdout:t,writeStderr:n,exit:e=>{throw new Cz(e)},color:r})}}function BV(e,t,n){return{readStdinBytes:()=>PN(e.stdin??``),writeStdout:t,writeStderr:n}}function VV(e){return{usbBridge:VB(e),serialBridge:zB(e),hidBridge:hB(e)}}async function HV(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=Tz(i,a),s=Ez(e,i,a),{colorApi:c,cliApi:l}=zV(!!e.env?.NO_COLOR,i,a),u=new UM(t),d=BV(e,i,a),f=KN(u,C,d),p=await NV(u,e.cwd,PV(e,a)),m=LV(e,t,p,f,d),h=uB(u,p,e.cwd,a),g=qz(h,{cwd:e.cwd}),_=GB({argv:e.argv,fs:f,exec:h}),v=aB(u),{usbBridge:y,serialBridge:b,hidBridge:x}=VV(u),S=Wz({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await u.call(`fetch`,`request`,[n,await nB(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=TB({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:l,color:c}),T=e.filename,E=Sz(T),D=await OB(u,e.code,e.cwd,T),ee=jB({graph:D,fsBridge:f,processShim:s.processShim,childProcess:nF(h,m),nodeConsole:o,sliccyModules:w,shimmedPackages:AB(u),nodeReadline:Pz({output:{write:i},onExit:s.recordExit})}).require,te={exports:{},filename:e.filename},ne=D.entrySource!==void 0,re=D.entrySource??e.code,O=globalThis;RV(),O.__slicc_compileWasm=e=>u.call(`wasm`,`compile`,[e]);let ie=await LB(re,{process:s.processShim,console:o,require:ee,module:te,exports:te.exports,fetch:C,__dirname:E,__filename:T},a,ne);await UV(u,p,a),s.getDidCallProcessExit()?ie=s.getExitCode():await WV(u),delete O.__slicc_compileWasm,u.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:ie})}async function UV(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 WV(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 GV(){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 KV(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=GV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&HV(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 qV(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=GV(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&eN(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 JV=KV(),YV=qV();function XV(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?QV():YV({kind:e,ctx:t}):typeof Worker<`u`?ZV():JV({kind:e,ctx:t})}function ZV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return $V(new Worker(new URL(`/assets/js-realm-worker-DrcpR5sl.js`,``+import.meta.url),{type:`module`}))}function QV(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return $V(new Worker(new URL(`/assets/py-realm-worker-B2OTI7Xc.js`,``+import.meta.url),{type:`module`}))}function $V(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,isolatedThread:!0,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function eH(){if(Dr())return decodeURIComponent(kr(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}function tH(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function nH(e){return e instanceof Error?e.message:String(e)}function rH(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function iH(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:rH(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function aH(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:rH(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const oH=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,sH=/\bimport\s*\.\s*meta\b/g;function cH(e,t){let n=JSON.stringify(t);return e.replace(oH,n).replace(sH,`({ url: ${n} })`)}async function lH(e,t,n,r){let i=await e();return i.transpileModule(cH(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function uH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Br(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!wr(e))return e;let a=tH(t),o;try{return await iH(n,e,t,a)}catch(e){o=e}try{return await lH(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${nH(o)}; typescript fallback: ${nH(e)}`)}}}function dH(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>Wr(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>Br(t));return async({source:e,filename:t})=>{if(!wr(e)&&!Ur(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?tH(t):void 0,o=i?t:`[eval].js`,s;try{return await aH(n,e,t,a)}catch(e){s=e}try{return await lH(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${nH(s)}; typescript fallback: ${nH(e)}`)}}}function fH(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
1654
1654
|
`);return t===-1?``:e.slice(t+1)}function pH(e){return Mt(e).dir}const mH=[`node`,`require`,`default`],hH=[`node`,`import`,`default`],gH=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,_H=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,vH=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,yH=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,bH=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function xH(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function SH(e){let t=Hr(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!xH(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(gH,`require`,`require`),r(_H,`import`,`import`),r(vH,`import`,`import`),r(yH,`import`,`export`),r(bH,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function CH(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=fH(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 wH(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??mH,s=e.importConditions??hH,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 CH(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=pH(e),p={};for(let{specifier:t,kind:i}of SH(n)){let n;try{n=await br(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 br(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 TH(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||xr.has(e)||SB.has(e))}async function EH(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 SH(t))if(TH(e))try{let t=await wH({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?hH:mH,requireConditions:mH,importConditions:hH});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&&(wr(t)||Ur(t))&&(f=await o({source:t,filename:r??`[eval]`,fromDir:n}));let p={files:c.map(e=>{let t=s.get(e);if(!t)throw Error(`module-loader: missing built module for '${e}'`);return{path:t.path,cjsSource:t.cjsSource,kind:t.kind}}),entryMap:l,edges:u,errors:d};return f!==void 0&&(p.entrySource=f),p}function DH(){return globalThis.navigator?.hid??null}function OH(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function kH(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&OH(e)===OH(t)&&!!e.productName}var AH=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(kH(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 jH=null;function MH(){return jH||=new AH,jH}const NH=4194304;function PH(e,t){let n=t.collections?.[0];return{handle:e,vendorId:t.vendorId,productId:t.productId,...t.productName?{productName:t.productName}:{},...n?.usagePage===void 0?{}:{usagePage:n.usagePage},...n?.usage===void 0?{}:{usage:n.usage},opened:t.opened}}function FH(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function IH(e){e.opened||await e.open()}function LH(e,t){if(e>4194304)throw Error(`${t} exceeds the ${NH}-byte (4 MiB) v1 limit`)}function RH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function zH(e,t){return(await t.getDevices()).map(t=>PH(e.register(t),t))}async function BH(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>PH(e.register(t),t))}function VH(e,t){return PH(t,FH(e,t))}async function HH(e,t){await FH(e,t).open()}async function UH(e,t){await FH(e,t).close()}async function WH(e,t,n,r){LH(r.byteLength,`send report payload`);let i=FH(e,t);await IH(i),await i.sendReport(n,r)}async function GH(e,t,n,r){LH(r.byteLength,`send feature report payload`);let i=FH(e,t);await IH(i),await i.sendFeatureReport(n,r)}async function KH(e,t,n){let r=FH(e,t);return await IH(r),{reportId:n,bytes:RH(await r.receiveFeatureReport(n))}}async function qH(e,t,n){let r=FH(e,t);await IH(r);let i=e=>{n({reportId:e.reportId,bytes:RH(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const JH=6e4;function YH(){return Xt()}function XH(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),JH);Yt(`hid-device`,e??[],void 0,{timeoutMs:JH}).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 ZH(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var QH=class{registry;constructor(e){this.registry=e}hid(){let e=DH();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return zH(this.registry,this.hid())}async request(e){if(YH()){let t=await XH(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=>PH(this.registry.register(e),e))}return BH(this.registry,this.hid(),e)}async reacquireAll(e){return(await this.hid().getDevices()).filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId)}info(e){return Promise.resolve(VH(this.registry,e))}open(e){return HH(this.registry,e)}close(e){return UH(this.registry,e)}sendReport(e,t,n){return WH(this.registry,e,t,ZH(n))}sendFeatureReport(e,t,n){return GH(this.registry,e,t,ZH(n))}async receiveFeatureReport(e,t){let n=await KH(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return qH(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},$H=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:ZH(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:ZH(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 eU(e,t){return e&&DH()?new QH(MH()):t?new $H(t):null}function tU(e){return async function(t,n){let r=t instanceof Request?t:null,i=nU(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=iU(r?.headers,n?.headers),s=await sU(n,r,a,o);s.defaultContentType&&!aU(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 nU(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function rU(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 iU(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=rU(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function aU(e,t){return oU(e,t)!==void 0}function oU(e,t){let n=t.toLowerCase(),r;for(let[t,i]of Object.entries(e))t.toLowerCase()===n&&(r=i);return r}async function sU(e,t,n,r){if(e&&`body`in e&&e.body!==void 0){let t=uU(e.body,n);return{body:await cU(e.body,n),defaultContentType:t}}if(t&&n!==`GET`&&n!==`HEAD`){let e=t.body!==null,n=new Uint8Array(await t.arrayBuffer()),i=oU(r,`content-type`)??``,a=e&&(!i||!u(i));return{body:n.byteLength===0?void 0:a?dU(n):new TextDecoder(`utf-8`).decode(n),defaultContentType:a?`application/octet-stream`:void 0}}return{}}async function cU(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 dU(e);if(e instanceof ArrayBuffer)return dU(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return dU(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(typeof Blob<`u`&&e instanceof Blob)return dU(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 lU(e){return e instanceof Uint8Array||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob}function uU(e,t){if(e instanceof URLSearchParams)return`application/x-www-form-urlencoded;charset=UTF-8`;if(!(t===`GET`||t===`HEAD`||!lU(e)))return typeof Blob<`u`&&e instanceof Blob&&e.type?e.type:`application/octet-stream`}function dU(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 fU(){return globalThis.navigator?.serial??null}var pU=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 mU=null;function hU(){return mU||=new pU,mU}const gU=4194304;function _U(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 vU(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function yU(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function bU(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 xU(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return _U(n,e.get(n))})}async function SU(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return _U(i,e.get(i))}function CU(e,t){return _U(t,vU(e,t))}async function wU(e,t,n){let r=vU(e,t);await r.port.open(n),r.opened=!0}async function TU(e,t){let n=vU(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 EU(e){if(!e.reader){if(!e.port.readable)throw Error(`serial port is not readable (is it open?)`);e.reader=e.port.readable.getReader()}return e.reader}function DU(e){if(!e.writer){if(!e.port.writable)throw Error(`serial port is not writable (is it open?)`);e.writer=e.port.writable.getWriter()}return e.writer}async function OU(e,t,n){let r=vU(e,t),i=Math.min(n.maxBytes??4194304,gU),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=bU(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=EU(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=yU(c,a.value);let e=u();if(e)return e}}return c}async function kU(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${gU}-byte (4 MiB) v1 limit`);return await DU(vU(e,t)).write(n),n.length}async function AU(e,t){return vU(e,t).port.getSignals()}async function jU(e,t,n){await vU(e,t).port.setSignals(n)}const MU=6e4;function NU(){return Xt()}function PU(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),MU);Yt(`serial-port`,e??[],void 0,{timeoutMs:MU}).then(e=>{let t=e;t.cancelled?r({cancelled:!0}):typeof t.error==`string`?r({error:t.error}):t.granted&&t.info?r({granted:!0,info:t.info}):r({error:`serial picker returned an unexpected response`})}).catch(e=>{r({error:e instanceof Error?e.message:`Failed to open serial picker`})})})}function FU(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var IU=class{registry;constructor(e){this.registry=e}serial(){let e=fU();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return xU(this.registry,this.serial())}async request(e){if(NU()){let t=await PU(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 _U(r,this.registry.get(r))}return SU(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(CU(this.registry,e))}open(e,t){return wU(this.registry,e,t)}close(e){return TU(this.registry,e)}read(e,t){return OU(this.registry,e,t)}write(e,t){return kU(this.registry,e,t)}getSignals(e){return AU(this.registry,e)}setSignals(e,t){return jU(this.registry,e,t)}},LU=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?FU(n.until):void 0,timeoutMs:n.timeoutMs},{timeoutMs:r});return new Uint8Array(i.bytes)}async write(e,t){return(await this.rpc.call(`serial-write`,{handle:e,bytes:FU(t)})).bytesWritten}async getSignals(e){return(await this.rpc.call(`serial-get-signals`,{handle:e})).signals}async setSignals(e,t){await this.rpc.call(`serial-set-signals`,{handle:e,signals:t})}};function RU(e,t){return e&&fU()?new IU(hU()):t?new LU(t):null}function zU(){return globalThis.navigator?.usb??null}function BU(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var VU=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(BU(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 HU=null;function UU(){return HU||=new VU,HU}const WU=4194304;function GU(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 KU(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function qU(e,t){if(e>4194304)throw Error(`${t} exceeds the ${WU}-byte (4 MiB) v1 limit`)}function JU(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function YU(e,t){return(await t.getDevices()).map(t=>GU(e.register(t),t))}async function XU(e,t,n){let r=await t.requestDevice({filters:n});return GU(e.register(r),r)}function ZU(e,t){return GU(t,KU(e,t))}async function QU(e,t){await KU(e,t).open()}async function $U(e,t){await KU(e,t).close()}async function eW(e,t,n){await KU(e,t).selectConfiguration(n)}async function tW(e,t,n){await KU(e,t).claimInterface(n)}async function nW(e,t,n){await KU(e,t).releaseInterface(n)}async function rW(e,t,n,r){qU(r,`control-in length`);let i=await KU(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?JU(i.data):new ArrayBuffer(0)}}async function iW(e,t,n,r){qU(r.byteLength,`control-out payload`);let i=await KU(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function aW(e,t,n,r){qU(r,`transfer-in length`);let i=await KU(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?JU(i.data):new ArrayBuffer(0)}}async function oW(e,t,n,r){qU(r.byteLength,`transfer-out payload`);let i=await KU(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function sW(e,t){await KU(e,t).reset()}const cW=6e4;function lW(){return Xt()}function uW(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),cW);Yt(`usb-device`,e??[],void 0,{timeoutMs:cW}).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 dW(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var fW=class{registry;constructor(e){this.registry=e}usb(){let e=zU();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return YU(this.registry,this.usb())}async request(e){if(lW()){let t=await uW(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 GU(this.registry.register(n),n)}return XU(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(ZU(this.registry,e))}open(e){return QU(this.registry,e)}close(e){return $U(this.registry,e)}selectConfig(e,t){return eW(this.registry,e,t)}claim(e,t){return tW(this.registry,e,t)}release(e,t){return nW(this.registry,e,t)}async controlIn(e,t,n){let r=await rW(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return iW(this.registry,e,t,dW(n))}async transferIn(e,t,n){let r=await aW(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return oW(this.registry,e,t,dW(n))}reset(e){return sW(this.registry,e)}},pW=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=3e5;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:dW(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:dW(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function mW(e,t){return e&&zU()?new fW(UU()):t?new pW(t):null}function hW(e,t,n,r={}){let{header:i,window:a}=EV(t),o=new Map,s=!1,c=r.dispatch??(e=>oV(e)?lV(e):$B(e));function l(e){let t=o.get(e);t&&(clearTimeout(t.timer),o.delete(e))}function u(e,t,n){let r=Math.min(a.byteLength,t.payload.byteLength-n);r>0&&a.set(t.payload.subarray(n,n+r)),Atomics.store(i,2,t.status),Atomics.store(i,3,t.payload.byteLength),Atomics.store(i,4,r),Atomics.store(i,5,n),Atomics.store(i,1,e),Atomics.store(i,0,2),Atomics.notify(i,0),n+r>=t.payload.byteLength&&l(e)}function d(e,t){if(s)return;let{status:n,payload:r}=wV(t);l(e);let i={status:n,payload:r,timer:setTimeout(()=>l(e),605e3)};o.set(e,i),u(e,i,0)}let f=e=>{let t=e.data;if(!t||typeof t.id!=`number`)return;if(t.type===`sync-sab-next`){let e=o.get(t.id),n=t.offset;if(!e||typeof n!=`number`||!Number.isInteger(n)||n<0||n>e.payload.byteLength){d(t.id,{ok:!1,errno:`EIO`,message:`sync-sab: bad continuation`});return}u(t.id,e,n);return}if(t.type!==`sync-sab-req`||!t.req||typeof t.req!=`object`)return;let r=t.id,i={...t.req,token:n},a;try{a=c(i)}catch(e){d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)});return}a.then(e=>d(r,e),e=>d(r,{ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return e.addEventListener(`message`,f),{dispose:()=>{if(!s){s=!0,e.removeEventListener(`message`,f);for(let e of[...o.keys()])l(e)}}}}const gW=r(`realm-host`);function _W(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?JB({fs:t.fs,...t.exec?{exec:t.exec}:{},cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;vW(e,i,t,n,o,c)};e.addEventListener(`message`,l);let u=i&&n.syncSab?hW(e,n.syncSab,i):void 0;return e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,u?.dispose(),i&&ZB(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 vW(e,t,n,r,i,a){try{let o=await yW(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=cG(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 yW(e,t,n,r,i){switch(e.channel){case`vfs`:return TW(e.op,e.args,t);case`exec`:return RW(e.op,e.args,t,i);case`fetch`:return HW(e.op,e.args,t);case`browser`:return KW(e.op,e.args,bW(n),n);case`usb`:return aG(e.op,e.args,SW(n));case`serial`:return oG(e.op,e.args,CW(n));case`hid`:return sG(e.op,e.args,wW(n),r);case`module`:return WW(e.op,e.args,t);case`wasm`:return GW(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function bW(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 xW(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 SW(e){if(e.usbBackend)return e.usbBackend;let t=mW(a(),i());if(!t)throw Error(`usb is not available in this runtime`);return t}function CW(e){if(e.serialBackend)return e.serialBackend;let t=RU(a(),i());if(!t)throw Error(`serial is not available in this runtime`);return t}function wW(e){if(e.hidBackend)return e.hidBackend;let t=eU(a(),i());if(!t)throw Error(`hid is not available in this runtime`);return t}async function TW(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 PW(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await FW(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const EW=10485760;function DW(e){return e.fileCount>=500||e.totalBytes>=EW}function OW(e){return e.entries.length>=2e4}async function kW(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 AW(e,t,n,r){let i=``;try{i=await e.fs.readlink(t)}catch{return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,isSymbolicLink:!0,symlinkTarget:i,size:n})}async function jW(e,t,n,r,i){if(n>1048576||DW(r)||r.totalBytes+n>EW){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let a;try{a=await e.fs.readFileBuffer(t)}catch{await MW(e,t,i,r);return}r.entries.push({path:t,content:a,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=a.byteLength}async function MW(e,t,n,r){let i;try{i=await e.fs.stat(t)}catch{return}if(i.isDirectory){await kW(e,t,n,r);return}r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:i.size})}async function NW(e,t,n){if(OW(n))return;let r=[t];for(;r.length>0;){if(OW(n))return;let t=r.pop(),i;try{i=await e.fs.lstat(t)}catch{}if(i?.isSymbolicLink){await AW(e,t,i.size,n);continue}let a;try{a=await e.fs.stat(t)}catch{continue}a.isDirectory?await kW(e,t,r,n):a.isFile&&await jW(e,t,a.size,n,r)}}async function PW(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await NW(e,t,n),t!==`/tmp`&&await NW(e,`/tmp`,n),{entries:n.entries}}async function FW(e,t){let n=[],r=async(e,t)=>{try{await t()}catch(t){n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}};for(let n of t.deleted)await r(n,()=>e.fs.rm(n,{recursive:!0}));for(let n of t.created)n.isSymbolicLink?await r(n.path,()=>e.fs.symlink(n.symlinkTarget??``,n.path)):n.isDirectory?await r(n.path,()=>e.fs.mkdir(n.path,{recursive:!0})):await r(n.path,()=>e.fs.writeFile(n.path,n.content));for(let n of t.modified)await r(n.path,()=>e.fs.writeFile(n.path,n.content));if(n.length>0)throw Error(`sync-fs flush failed for ${n.length} path(s): ${n.join(`; `)}`)}const IW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),LW=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function RW(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 BW(t,n,r);if(e===`kill`)return VW(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function zW(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 BW(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??{};zW(l);let u=new AbortController,{pm:d,owner:f}=n.opts,p=0;d&&f&&(p=d.spawn({kind:`shell`,argv:c,cwd:t.cwd,owner:f,...n.opts.ppid===void 0?{}:{ppid:n.opts.ppid},adoptAbort:u}).pid),n.spawns.set(r,{controller:u,pid:p});let m;try{let e={cwd:t.cwd,signal:u.signal};return l.stdin!==void 0&&(e.stdin=l.stdin),l.stdinKind!==void 0&&(e.stdinKind=l.stdinKind),s===void 0?l.args!==void 0&&(e.args=l.args):e.args=s,m=await t.exec(o,e),{stdout:m.stdout,stderr:m.stderr,exitCode:m.exitCode}}finally{if(n.spawns.delete(r),d&&p){let e=d.get(p);d.exit(p,e?.terminatedBy?null:m?.exitCode??1)}}}function VW(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&IW.has(r)?r:`SIGTERM`;LW.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 HW(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?tU(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 UW(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 WW(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=UW(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return EH({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:uH({ipk:s}),transpileEntry:dH({ipk:s})})}async function GW(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);let i=n.fs.resolvePath(n.cwd,r);return qr(e=>n.fs.readFileBuffer(e),i)}async function KW(e,t,n,r){switch(e){case`findTab`:return YW(n,t[0]??{});case`ensureTab`:{let e=t[0];return XW(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return ZW(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return ZW(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return tG(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return nG(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await xW(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return xW(r).update(e,n)}case`wsClose`:{let e=t[0];return xW(r).close(e)}case`wsList`:return xW(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 eG(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function qW(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function JW(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=qW()?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){gW.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function YW(e,t){let n=await JW(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=rG(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 XW(e,t,n){let r=await JW(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=iG(t);if(e){let t=r.find(t=>iG(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function ZW(e,t,n,r){return e.withTab(t,async()=>QW(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function QW(e){if(typeof e!=`string`)return e;let t=$W(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=$W(t);if(typeof e==`object`&&e)return e}return t}return e}function $W(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 eG(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(){
|
|
1655
1655
|
try {
|
|
1656
1656
|
var entries = performance.getEntriesByType('resource');
|
|
@@ -1667,8 +1667,8 @@ except BaseException:
|
|
|
1667
1667
|
})()`,{returnByValue:!0}))return})}async function tG(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 nG(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 rG(e){try{return new URL(e).hostname}catch{return null}}function iG(e){try{return new URL(e).origin}catch{return null}}async function aG(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 oG(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 sG(e,t,n,r){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`sendReport`:return n.sendReport(t[0],t[1],t[2]);case`sendFeatureReport`:return n.sendFeatureReport(t[0],t[1],t[2]);case`receiveFeatureReport`:return n.receiveFeatureReport(t[0],t[1]);case`subscribeInputReports`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=await n.subscribeInputReports(e,t=>{let n=t.bytes instanceof Uint8Array?t.bytes:new Uint8Array(t.bytes),i={type:`realm-event`,channel:`hid-input-report`,payload:{handle:e,reportId:t.reportId,bytes:n}};r.pushEvent(i,[n.buffer])});return r.subscriptions.set(e,i),!0}case`unsubscribeInputReports`:{let e=t[0],n=r.subscriptions.get(e);return!n||(r.subscriptions.delete(e),await n(),!0)}default:throw Error(`realm-host: unknown hid op '${e}'`)}}function cG(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 lG(e){let t=e.procKind??`jsh`,n=e.pm.spawn({kind:t,argv:e.argv,cwd:e.cwd,env:e.env,owner:e.owner,ppid:e.ppid}),r;try{r=await e.realmFactory({kind:e.kind,ctx:e.ctx})}catch(t){let r=t instanceof Error?t.message:String(t);return e.pm.exit(n.pid,1),{stdout:``,stderr:`realm-runner: ${r}\n`,exitCode:1}}let i=r.isolatedThread?uG(e.syncSabBytes):void 0,a=_W(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:!!e.syncFsBridgeEnabled||i!==void 0,...i?{syncSab:i}:{}});return new Promise(t=>{let o=!1,s=null,c=null,l=null,u=null,d=()=>{c&&r.controlPort.removeEventListener(`message`,c),r.removeEventListener&&(l&&r.removeEventListener(`error`,l),u&&r.removeEventListener(`messageerror`,u)),s?.(),a.dispose()},f=(i,a)=>{if(!o){o=!0,d();try{r.terminate()}catch{}e.pm.exit(n.pid,a),t(i)}};c=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;f({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;f({stdout:``,stderr:t.message+`
|
|
1668
1668
|
`,exitCode:1},1)}},l=e=>{let t=e.message??`realm error`;f({stdout:``,stderr:t+`
|
|
1669
1669
|
`,exitCode:1},1)},u=()=>{f({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
1670
|
-
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function uG(e){if(DV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let dG=!1;function fG(e){dG=e}function pG(){return dG}const mG=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function hG(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 mG.decode(n)}function gG(e){return e}function _G(e){if(e.length===0)return``;let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=String.fromCharCode(e[n]);return t.join(``)}const vG=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function yG(e){return vG[e]??null}function bG(e,t){let n=yG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let xG=null;function SG(e){let t=xG;return xG=e,t}async function CG(){if(!xG)return{};try{return await xG()??{}}catch{return{}}}function wG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-PMxICYyx.js`).then(e=>e.r);return bG(t(),e())}}async function TG(e,t,n,r,i={}){return await n.fs.exists(e)?EG(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 EG(e,t,n,r,i={}){let a=i.realmFactory??DG(),o=r?.processManager??AG()??kG(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await lG({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await CG(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:gG(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:pG()})}function DG(){return typeof Worker<`u`||typeof document<`u`?XV():KV()}let OG=null;function kG(){return OG||=new vr,OG}function AG(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function jG(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var MG=class{aggregator=null;now;explicitSink;scrubLabel;ids=new Map;seq=0;constructor(e={}){this.now=e.now??Date.now,this.explicitSink=e.sink,this.scrubLabel=e.scrubLabel}allocateId(e=`p`){return this.seq+=1,`${e}-${this.seq}`}hasSink(){return this.resolveSink()!==null}setAggregator(e){this.aggregator=e}emit(e){let t=this.aggregator;if(t&&e.id!==t.id)return t.onChild(e),!0;let n=this.resolveSink();if(!n)return e.phase===`end`&&this.ids.delete(e.id),!1;let r=this.ids.get(e.id);if(e.phase===`update`){if(!r)return!1;let t=this.now();return t-r.lastUpdateAt<250?!1:(r.lastUpdateAt=t,this.deliver(r,n,e),!0)}if(e.phase===`start`){let t={lastUpdateAt:-1/0,rawLabel:e.label,label:this.scrubbed(e.label),tail:Promise.resolve()};return this.ids.set(e.id,t),this.deliver(t,n,e),!0}return r?(this.ids.delete(e.id),this.deliver(r,n,e),!0):!1}resolveSink(){if(this.explicitSink)return this.explicitSink;let e=Ht();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?NG(this.scrubLabel,e):e}deliver(e,t,n){n.label!==e.rawLabel&&(e.rawLabel=n.label,e.label=this.scrubbed(n.label));let{label:r}=e;if(typeof r==`string`){let e=PG(r);t(e===n.label?n:{...n,label:e});return}e.tail=e.tail.then(async()=>{let i=await r;e.label=i,t({...n,label:PG(i)})})}};async function NG(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function PG(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function FG(e,t){return t.length?`${e} ${t.join(` `)}`:e}function IG(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function LG(e,t=Date.now){let n=new Map,r=e=>n.get(e)?.[0];return{start(r,i){if(!e.hasSink())return;let a={id:e.allocateId(`net`),label:IG(r),startedAt:t()},o=n.get(r);o?o.push(a):n.set(r,[a]),e.emit({id:a.id,label:a.label,fraction:i===void 0?void 0:0,done:0,total:i,unit:`bytes`,phase:`start`})},chunk(n,i,a){let o=r(n);if(!o)return;let s,c;if(a!==void 0&&a>0){s=Math.min(1,i/a);let e=t()-o.startedAt;i>0&&(c=Math.max(0,e/i*(a-i)))}e.emit({id:o.id,label:o.label,fraction:s,etaMs:c,done:i,total:a,unit:`bytes`,phase:`update`})},end(t){let r=n.get(t),i=r?.shift();r&&r.length===0&&n.delete(t),i&&e.emit({id:i.id,label:i.label,fraction:1,etaMs:0,unit:`bytes`,phase:`end`})}}}const RG={timeout:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`)&&e[t]!==`--`;)[`-k`,`--kill-after`,`-s`,`--signal`].includes(e[t])&&(t+=1),t+=1;return e[t]===`--`&&(t+=1),t+1},env:e=>{let t=0;for(;t<e.length&&(e[t].startsWith(`-`)||e[t].includes(`=`));)t+=1;return t},nohup:()=>0,nice:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`);)t+=1;return t}},zG=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function BG(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function VG(e,t){switch(e.type){case`CommandSubstitution`:return QG(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=VG(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function HG(e,t){let n=0;for(let r of e.parts){let e=VG(r,t);if(e===null)return null;n+=e}return n}function UG(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=HG(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=HG(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=BG(e.name);if(r===null||zG.has(r))return null;if(!t.has(r))return n;n+=1;let i=RG[r];if(i){let r=e.args.map(BG);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(zG.has(a))return null;t.has(a)&&(n+=1)}return n}function WG(e){let t=typeof e.start==`number`?e.start:Number(e.start),n=typeof e.end==`number`?e.end:Number(e.end);if(!Number.isFinite(t)||!Number.isFinite(n)){let t=String(e.start),n=String(e.end);return t.length!==1||n.length!==1?null:Math.abs(n.charCodeAt(0)-t.charCodeAt(0))+1}let r=Math.abs(e.step??1)||1;return Math.floor(Math.abs(n-t)/r)+1}function GG(e){if(e.parts.length!==1||e.parts[0].type!==`CommandSubstitution`)return null;let t=e.parts[0].body;if(t.statements.length!==1)return null;let n=t.statements[0];if(n.pipelines.length!==1||n.pipelines[0].commands.length!==1)return null;let r=n.pipelines[0].commands[0];if(r.type!==`SimpleCommand`||!r.name||BG(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=BG(e);return t===null?NaN:Number(t)});if(i.some(e=>!Number.isFinite(e)))return null;let a=1,o=1,s;if(i.length===1)[s]=i;else if(i.length===2)[a,s]=i;else if(i.length===3)[a,o,s]=i;else return null;if(o===0)return null;let c=Math.floor((s-a)/o)+1;return c>0?c:0}function KG(e){let t=0;for(let n of e){let e=n.type===`Word`?qG(n.word):WG(n);if(e===null)return null;t+=e}return t}function qG(e){let t=GG(e);if(t!==null)return t;let n=1;for(let t of e.parts)switch(t.type){case`Literal`:case`SingleQuoted`:case`Escaped`:break;case`DoubleQuoted`:if(t.parts.some(e=>e.type!==`Literal`&&e.type!==`Escaped`))return null;break;case`BraceExpansion`:{let e=KG(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function JG(e){let t=0;for(let n of e){let e=qG(n);if(e===null)return null;t+=e}return t}function YG(e,t){let n=0;for(let r of e){let e=ZG(r,t);if(e===null)return null;n+=e}return n}function XG(e,t){switch(e.type){case`SimpleCommand`:return UG(e,t);case`For`:{if(!e.words)return null;let n=JG(e.words),r=YG(e.body,t);return n===null||r===null?null:e.words.filter(e=>GG(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return YG(e.body,t);case`FunctionDef`:return 0;default:return null}}function ZG(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=XG(e,t);if(r===null)return null;n+=r}return n}function QG(e,t){return YG(e.statements,t)}function $G(e,t){let n=QG(e,t);return{totalSteps:n!==null&&n>0?n:null}}function eK(e){return e.split(`
|
|
1671
|
-
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var tK=class{plan;emitter;label;now;id;steps=0;startedAt;finished=!1;children=new Map;constructor(e,t,n,r=Date.now){this.plan=e,this.emitter=t,this.label=n,this.now=r,this.id=t.allocateId(`script`),this.startedAt=r(),this.emitter.setAggregator(this),this.publish(`start`)}stepDone(){this.finished||(this.steps+=1,this.publish(`update`))}onChild(e){if(!this.finished){if(e.phase===`end`){this.children.delete(e.id);return}this.children.set(e.id,{fraction:e.fraction,label:e.label}),(e.fraction!==void 0||e.phase===`start`)&&this.publish(`update`)}}end(){this.finished||(this.finished=!0,this.emitter.setAggregator(null),this.emitter.emit({id:this.id,label:this.label,fraction:1,etaMs:0,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:`end`}))}fraction(){let e=[...this.children.values()].at(-1)?.fraction,t=this.plan.totalSteps;if(t===null)return e;let n=e??0;return Math.min(1,(this.steps+n)/t)}publish(e){let t=this.fraction(),n=this.now()-this.startedAt,r=t!==void 0&&t>0&&t<1?Math.max(0,n/t*(1-t)):t===1?0:void 0,i=[...this.children.values()].at(-1);this.emitter.emit({id:this.id,label:i?`${this.label} · ${i.label}`:this.label,fraction:t,etaMs:r,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:e})}};const nK=globalThis.setTimeout.bind(globalThis);function rK(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function iK(e,t={}){let n=t.now??Date.now,r=t.setTimeout??nK,i=t.isAborted??(()=>!1),a=t.label??rK,o=e=>new Promise(t=>r(t,e));return async t=>{let r=Math.max(0,t),s=e.allocateId(`sleep`),c=a(r),l=n();e.emit({id:s,label:c,fraction:0,etaMs:r,done:0,total:r,unit:`ms`,phase:`start`});try{let t=0;for(;t<r;){if(i())return;if(await o(Math.min(250,r-t)),t=n()-l,t<r){let n=Math.min(1,t/r);e.emit({id:s,label:c,fraction:n,etaMs:Math.max(0,r-t),done:Math.min(t,r),total:r,unit:`ms`,phase:`update`})}}}finally{e.emit({id:s,label:c,fraction:1,etaMs:0,done:r,total:r,unit:`ms`,phase:`end`})}}}const aK=globalThis.setTimeout.bind(globalThis);function oK(e){let t=/^(\d+(?:\.\d+)?|\.\d+)([smhd]?)$/.exec(e.trim());return t?Number(t[1])*({"":1e3,s:1e3,m:6e4,h:36e5,d:864e5}[t[2]]??1e3):null}function sK(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`--`)return t+1<e.length?t+1:-1;if(!n.startsWith(`-`))return t;[`-k`,`--kill-after`,`-s`,`--signal`].includes(n)&&(t+=1),t+=1}return-1}function cK(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??aK;return{...e,async execute(n,a){let o=sK(n),s=o>=0?oK(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=FG(e.name,n),u=r(),d=!0,f=()=>{if(!d)return;let e=r()-u,n=Math.min(1,e/s);t.emit({id:c,label:l,fraction:n,etaMs:Math.max(0,s-e),done:Math.min(e,s),total:s,unit:`ms`,phase:`update`}),e<s&&i(f,250)};t.emit({id:c,label:l,fraction:0,etaMs:s,done:0,total:s,unit:`ms`,phase:`start`}),i(f,250);try{return await e.execute(n,a)}finally{d=!1,t.emit({id:c,label:l,fraction:1,etaMs:0,done:s,total:s,unit:`ms`,phase:`end`})}}}}const lK=new Set(`sleep,echo,printf,true,false,test,[,cd,pwd,export,unset,set,shift,local,return,break,continue,exit,:,read,let,declare,typeset,readonly,eval,exec,source,.,alias,unalias,type,command,builtin,wait,trap,basename,dirname,seq,expr`.split(`,`));function uK(e,t,n={}){if((n.skip??lK).has(e.name))return e;let r=e.name;return{...e,async execute(n,i){if(!t.hasSink())return e.execute(n,i);let a=t.allocateId(`cmd`),o=FG(r,n);t.emit({id:a,label:o,phase:`start`});try{return await e.execute(n,i)}finally{t.emit({id:a,label:o,phase:`end`})}}}}function dK(e){return Xn(`sudo`,e)}async function fK(e,t){let n=e.trim();if(!n||zee(Nee(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:dK(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}function pK(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function mK(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function hK(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:mK(e.installAll)},affinity:{apps:pK(e.apps),tasks:pK(e.tasks),role:pK(e.role),purpose:pK(e.purpose)},priority:n}})}const gK={apps:3,tasks:2,role:1,purpose:1};function _K(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*gK.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*gK.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=gK.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=gK.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 vK(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 yK(e){let t=new Set;try{let n=await e.readDir(Xr);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 bK(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 xK(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function SK(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}async function CK(e,t){try{let n=xK(t);if(!n)return[];let r=await e(`${Xee}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?hK(Ot(r.body).data):[]}catch{return[]}}async function wK(e){let t;try{t=await e(ti,{headers:{Accept:`application/json`}})}catch(e){throw Error(ei(e,ti))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return hK(Ot(t.body).data)}function TK(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 EK(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 ui(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 DK(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 fi(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 li(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 OK(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 EK(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=TK(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 ui(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 kK(e,t,n,r,i,a,o,s,c,l){let u=await Qr(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 DK(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 li(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 AK(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 jK(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=bK(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=bK(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([wK(t),CK(t,a.company),yK(e)]);o=SK(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${ti}: ${e instanceof Error?e.message:String(e)}`])}let c=_K(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=AK(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await $r(a,o,t);return c.status===`error`?kK(n,i,a,o,d,u,r,s,t,e):OK(n,i,Jr(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await ii(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function MK(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let NK,PK;async function FK(e){if(NK)return NK;if(PK!==void 0)return PK;PK=(async()=>{let t;try{t=await e(Zr,{headers:{Accept:`application/json`}})}catch(e){throw Error(ei(e,Zr))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=Ot(t.body),r=Array.isArray(n)?n:n.skills??[];return NK=r,r})();try{return await PK}catch(e){throw PK=void 0,e}}async function IK(e,t){let n=await FK(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 LK=/^[A-Za-z0-9._-]+$/;function RK(e){return!e||e===`.`||e===`..`?!1:LK.test(e)}function zK(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(`/`)||!RK(r)||!RK(i))return null;let a=MK(r);return RK(a)?{hostname:a,task:i}:null}function BK(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 VK(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(`
|
|
1670
|
+
`,exitCode:1},1)},s=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?f({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?f({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&f({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,c),r.addEventListener&&(r.addEventListener(`error`,l),r.addEventListener(`messageerror`,u));let p={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...a.syncFsToken===void 0?{}:{syncFsToken:a.syncFsToken},...i?{syncSab:i}:{}};r.controlPort.postMessage(p)})}function uG(e){if(DV())try{return new SharedArrayBuffer(64+(e??1048576))}catch{return}}let dG=!1;function fG(e){dG=e}function pG(){return dG}const mG=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function hG(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 mG.decode(n)}function gG(e){return e}function _G(e){if(e.length===0)return``;let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=String.fromCharCode(e[n]);return t.join(``)}const vG=Object.freeze({anthropic:`ANTHROPIC_API_KEY`,"ant-ling":`ANT_LING_API_KEY`,"qwen-token-plan":`QWEN_TOKEN_PLAN_API_KEY`,"qwen-token-plan-cn":`QWEN_TOKEN_PLAN_CN_API_KEY`,"qwen-token-plan-individual":`QWEN_TOKEN_PLAN_API_KEY`,openai:`OPENAI_API_KEY`,"azure-openai-responses":`AZURE_OPENAI_API_KEY`,nvidia:`NVIDIA_API_KEY`,deepseek:`DEEPSEEK_API_KEY`,google:`GEMINI_API_KEY`,"google-vertex":`GOOGLE_CLOUD_API_KEY`,groq:`GROQ_API_KEY`,cerebras:`CEREBRAS_API_KEY`,xai:`XAI_API_KEY`,radius:`RADIUS_API_KEY`,openrouter:`OPENROUTER_API_KEY`,"vercel-ai-gateway":`AI_GATEWAY_API_KEY`,zai:`ZAI_API_KEY`,"zai-coding-cn":`ZAI_CODING_CN_API_KEY`,mistral:`MISTRAL_API_KEY`,minimax:`MINIMAX_API_KEY`,"minimax-cn":`MINIMAX_CN_API_KEY`,moonshotai:`MOONSHOT_API_KEY`,"moonshotai-cn":`MOONSHOT_API_KEY`,huggingface:`HF_TOKEN`,fireworks:`FIREWORKS_API_KEY`,together:`TOGETHER_API_KEY`,baseten:`BASETEN_API_KEY`,opencode:`OPENCODE_API_KEY`,"opencode-go":`OPENCODE_API_KEY`,"kimi-coding":`KIMI_API_KEY`,"cloudflare-workers-ai":`CLOUDFLARE_API_KEY`,"cloudflare-ai-gateway":`CLOUDFLARE_API_KEY`,xiaomi:`XIAOMI_API_KEY`,"xiaomi-token-plan-cn":`XIAOMI_TOKEN_PLAN_CN_API_KEY`,"xiaomi-token-plan-ams":`XIAOMI_TOKEN_PLAN_AMS_API_KEY`,"xiaomi-token-plan-sgp":`XIAOMI_TOKEN_PLAN_SGP_API_KEY`});function yG(e){return vG[e]??null}function bG(e,t){let n=yG(e);if(!n)return{};let r=t.find(t=>t.providerId===e)?.apiKey?.trim();return r?{[n]:r}:{}}let xG=null;function SG(e){let t=xG;return xG=e,t}async function CG(){if(!xG)return{};try{return await xG()??{}}catch{return{}}}function wG(){return async()=>{let{getAccounts:e,getSelectedProvider:t}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r);return bG(t(),e())}}async function TG(e,t,n,r,i={}){return await n.fs.exists(e)?EG(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 EG(e,t,n,r,i={}){let a=i.realmFactory??DG(),o=r?.processManager??AG()??kG(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await lG({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:{...s.kind===`scoop`?{}:await CG(),...Object.fromEntries(n.env.entries())},cwd:n.cwd,filename:c,stdin:gG(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:pG()})}function DG(){return typeof Worker<`u`||typeof document<`u`?XV():KV()}let OG=null;function kG(){return OG||=new vr,OG}function AG(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function jG(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}var MG=class{aggregator=null;now;explicitSink;scrubLabel;ids=new Map;seq=0;constructor(e={}){this.now=e.now??Date.now,this.explicitSink=e.sink,this.scrubLabel=e.scrubLabel}allocateId(e=`p`){return this.seq+=1,`${e}-${this.seq}`}hasSink(){return this.resolveSink()!==null}setAggregator(e){this.aggregator=e}emit(e){let t=this.aggregator;if(t&&e.id!==t.id)return t.onChild(e),!0;let n=this.resolveSink();if(!n)return e.phase===`end`&&this.ids.delete(e.id),!1;let r=this.ids.get(e.id);if(e.phase===`update`){if(!r)return!1;let t=this.now();return t-r.lastUpdateAt<250?!1:(r.lastUpdateAt=t,this.deliver(r,n,e),!0)}if(e.phase===`start`){let t={lastUpdateAt:-1/0,rawLabel:e.label,label:this.scrubbed(e.label),tail:Promise.resolve()};return this.ids.set(e.id,t),this.deliver(t,n,e),!0}return r?(this.ids.delete(e.id),this.deliver(r,n,e),!0):!1}resolveSink(){if(this.explicitSink)return this.explicitSink;let e=Ht();if(!e)return null;let t=e.onUpdate;return e=>{t({content:[{type:`progress`,progress:e}]})}}scrubbed(e){return this.scrubLabel?NG(this.scrubLabel,e):e}deliver(e,t,n){n.label!==e.rawLabel&&(e.rawLabel=n.label,e.label=this.scrubbed(n.label));let{label:r}=e;if(typeof r==`string`){let e=PG(r);t(e===n.label?n:{...n,label:e});return}e.tail=e.tail.then(async()=>{let i=await r;e.label=i,t({...n,label:PG(i)})})}};async function NG(e,t){if(!t)return t;try{return await e(t)}catch{return`[label withheld: secret scrub unavailable]`}}function PG(e,t=80){return e.length>t?`${e.slice(0,t-1)}…`:e}function FG(e,t){return t.length?`${e} ${t.join(` `)}`:e}function IG(e){try{let t=new URL(e);return`↓ ${t.host}${t.pathname===`/`?``:t.pathname}`}catch{return`↓ ${e}`}}function LG(e,t=Date.now){let n=new Map,r=e=>n.get(e)?.[0];return{start(r,i){if(!e.hasSink())return;let a={id:e.allocateId(`net`),label:IG(r),startedAt:t()},o=n.get(r);o?o.push(a):n.set(r,[a]),e.emit({id:a.id,label:a.label,fraction:i===void 0?void 0:0,done:0,total:i,unit:`bytes`,phase:`start`})},chunk(n,i,a){let o=r(n);if(!o)return;let s,c;if(a!==void 0&&a>0){s=Math.min(1,i/a);let e=t()-o.startedAt;i>0&&(c=Math.max(0,e/i*(a-i)))}e.emit({id:o.id,label:o.label,fraction:s,etaMs:c,done:i,total:a,unit:`bytes`,phase:`update`})},end(t){let r=n.get(t),i=r?.shift();r&&r.length===0&&n.delete(t),i&&e.emit({id:i.id,label:i.label,fraction:1,etaMs:0,unit:`bytes`,phase:`end`})}}}const RG={timeout:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`)&&e[t]!==`--`;)[`-k`,`--kill-after`,`-s`,`--signal`].includes(e[t])&&(t+=1),t+=1;return e[t]===`--`&&(t+=1),t+1},env:e=>{let t=0;for(;t<e.length&&(e[t].startsWith(`-`)||e[t].includes(`=`));)t+=1;return t},nohup:()=>0,nice:e=>{let t=0;for(;t<e.length&&e[t].startsWith(`-`);)t+=1;return t}},zG=new Set([`xargs`,`watch`,`parallel`,`bash`,`sh`,`eval`,`source`,`.`]);function BG(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:case`SingleQuoted`:case`Escaped`:t+=n.value;break;case`DoubleQuoted`:for(let e of n.parts){if(e.type!==`Literal`&&e.type!==`Escaped`)return null;t+=e.value}break;default:return null}return t}function VG(e,t){switch(e.type){case`CommandSubstitution`:return QG(e.body,t);case`DoubleQuoted`:{let n=0;for(let r of e.parts){let e=VG(r,t);if(e===null)return null;n+=e}return n}case`ProcessSubstitution`:return null;default:return 0}}function HG(e,t){let n=0;for(let r of e.parts){let e=VG(r,t);if(e===null)return null;n+=e}return n}function UG(e,t){let n=0;for(let r of e.assignments){if(!r.value)continue;let e=HG(r.value,t);if(e===null)return null;n+=e}for(let r of e.args){let e=HG(r,t);if(e===null)return null;n+=e}if(!e.name)return n;let r=BG(e.name);if(r===null||zG.has(r))return null;if(!t.has(r))return n;n+=1;let i=RG[r];if(i){let r=e.args.map(BG);if(r.some(e=>e===null))return null;let a=r[i(r)];if(a===void 0)return n;if(zG.has(a))return null;t.has(a)&&(n+=1)}return n}function WG(e){let t=typeof e.start==`number`?e.start:Number(e.start),n=typeof e.end==`number`?e.end:Number(e.end);if(!Number.isFinite(t)||!Number.isFinite(n)){let t=String(e.start),n=String(e.end);return t.length!==1||n.length!==1?null:Math.abs(n.charCodeAt(0)-t.charCodeAt(0))+1}let r=Math.abs(e.step??1)||1;return Math.floor(Math.abs(n-t)/r)+1}function GG(e){if(e.parts.length!==1||e.parts[0].type!==`CommandSubstitution`)return null;let t=e.parts[0].body;if(t.statements.length!==1)return null;let n=t.statements[0];if(n.pipelines.length!==1||n.pipelines[0].commands.length!==1)return null;let r=n.pipelines[0].commands[0];if(r.type!==`SimpleCommand`||!r.name||BG(r.name)!==`seq`)return null;let i=r.args.map(e=>{let t=BG(e);return t===null?NaN:Number(t)});if(i.some(e=>!Number.isFinite(e)))return null;let a=1,o=1,s;if(i.length===1)[s]=i;else if(i.length===2)[a,s]=i;else if(i.length===3)[a,o,s]=i;else return null;if(o===0)return null;let c=Math.floor((s-a)/o)+1;return c>0?c:0}function KG(e){let t=0;for(let n of e){let e=n.type===`Word`?qG(n.word):WG(n);if(e===null)return null;t+=e}return t}function qG(e){let t=GG(e);if(t!==null)return t;let n=1;for(let t of e.parts)switch(t.type){case`Literal`:case`SingleQuoted`:case`Escaped`:break;case`DoubleQuoted`:if(t.parts.some(e=>e.type!==`Literal`&&e.type!==`Escaped`))return null;break;case`BraceExpansion`:{let e=KG(t.items);if(e===null)return null;n*=e;break}default:return null}return n}function JG(e){let t=0;for(let n of e){let e=qG(n);if(e===null)return null;t+=e}return t}function YG(e,t){let n=0;for(let r of e){let e=ZG(r,t);if(e===null)return null;n+=e}return n}function XG(e,t){switch(e.type){case`SimpleCommand`:return UG(e,t);case`For`:{if(!e.words)return null;let n=JG(e.words),r=YG(e.body,t);return n===null||r===null?null:e.words.filter(e=>GG(e)!==null&&t.has(`seq`)).length+n*r}case`Subshell`:case`Group`:return YG(e.body,t);case`FunctionDef`:return 0;default:return null}}function ZG(e,t){let n=0;for(let r of e.pipelines)for(let e of r.commands){let r=XG(e,t);if(r===null)return null;n+=r}return n}function QG(e,t){return YG(e.statements,t)}function $G(e,t){let n=QG(e,t);return{totalSteps:n!==null&&n>0?n:null}}function eK(e){return e.split(`
|
|
1671
|
+
`).map(e=>e.trim()).find(e=>e.length>0&&!e.startsWith(`#`))||`bash`}var tK=class{plan;emitter;label;now;id;steps=0;startedAt;finished=!1;children=new Map;constructor(e,t,n,r=Date.now){this.plan=e,this.emitter=t,this.label=n,this.now=r,this.id=t.allocateId(`script`),this.startedAt=r(),this.emitter.setAggregator(this),this.publish(`start`)}stepDone(){this.finished||(this.steps+=1,this.publish(`update`))}onChild(e){if(!this.finished){if(e.phase===`end`){this.children.delete(e.id);return}this.children.set(e.id,{fraction:e.fraction,label:e.label}),(e.fraction!==void 0||e.phase===`start`)&&this.publish(`update`)}}end(){this.finished||(this.finished=!0,this.emitter.setAggregator(null),this.emitter.emit({id:this.id,label:this.label,fraction:1,etaMs:0,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:`end`}))}fraction(){let e=[...this.children.values()].at(-1)?.fraction,t=this.plan.totalSteps;if(t===null)return e;let n=e??0;return Math.min(1,(this.steps+n)/t)}publish(e){let t=this.fraction(),n=this.now()-this.startedAt,r=t!==void 0&&t>0&&t<1?Math.max(0,n/t*(1-t)):t===1?0:void 0,i=[...this.children.values()].at(-1);this.emitter.emit({id:this.id,label:i?`${this.label} · ${i.label}`:this.label,fraction:t,etaMs:r,done:this.steps,total:this.plan.totalSteps??void 0,unit:`iterations`,phase:e})}};const nK=globalThis.setTimeout.bind(globalThis);function rK(e){let t=e/1e3;return`sleep ${Number.isInteger(t)?t:t.toFixed(1)}`}function iK(e,t={}){let n=t.now??Date.now,r=t.setTimeout??nK,i=t.isAborted??(()=>!1),a=t.label??rK,o=e=>new Promise(t=>r(t,e));return async t=>{let r=Math.max(0,t),s=e.allocateId(`sleep`),c=a(r),l=n();e.emit({id:s,label:c,fraction:0,etaMs:r,done:0,total:r,unit:`ms`,phase:`start`});try{let t=0;for(;t<r;){if(i())return;if(await o(Math.min(250,r-t)),t=n()-l,t<r){let n=Math.min(1,t/r);e.emit({id:s,label:c,fraction:n,etaMs:Math.max(0,r-t),done:Math.min(t,r),total:r,unit:`ms`,phase:`update`})}}}finally{e.emit({id:s,label:c,fraction:1,etaMs:0,done:r,total:r,unit:`ms`,phase:`end`})}}}const aK=globalThis.setTimeout.bind(globalThis);function oK(e){let t=/^(\d+(?:\.\d+)?|\.\d+)([smhd]?)$/.exec(e.trim());return t?Number(t[1])*({"":1e3,s:1e3,m:6e4,h:36e5,d:864e5}[t[2]]??1e3):null}function sK(e){let t=0;for(;t<e.length;){let n=e[t];if(n===`--`)return t+1<e.length?t+1:-1;if(!n.startsWith(`-`))return t;[`-k`,`--kill-after`,`-s`,`--signal`].includes(n)&&(t+=1),t+=1}return-1}function cK(e,t,n={}){let r=n.now??Date.now,i=n.setTimeout??aK;return{...e,async execute(n,a){let o=sK(n),s=o>=0?oK(n[o]):null;if(!t.hasSink()||s===null||s<=0)return e.execute(n,a);let c=t.allocateId(`timeout`),l=FG(e.name,n),u=r(),d=!0,f=()=>{if(!d)return;let e=r()-u,n=Math.min(1,e/s);t.emit({id:c,label:l,fraction:n,etaMs:Math.max(0,s-e),done:Math.min(e,s),total:s,unit:`ms`,phase:`update`}),e<s&&i(f,250)};t.emit({id:c,label:l,fraction:0,etaMs:s,done:0,total:s,unit:`ms`,phase:`start`}),i(f,250);try{return await e.execute(n,a)}finally{d=!1,t.emit({id:c,label:l,fraction:1,etaMs:0,done:s,total:s,unit:`ms`,phase:`end`})}}}}const lK=new Set(`sleep,echo,printf,true,false,test,[,cd,pwd,export,unset,set,shift,local,return,break,continue,exit,:,read,let,declare,typeset,readonly,eval,exec,source,.,alias,unalias,type,command,builtin,wait,trap,basename,dirname,seq,expr`.split(`,`));function uK(e,t,n={}){if((n.skip??lK).has(e.name))return e;let r=e.name;return{...e,async execute(n,i){if(!t.hasSink())return e.execute(n,i);let a=t.allocateId(`cmd`),o=FG(r,n);t.emit({id:a,label:o,phase:`start`});try{return await e.execute(n,i)}finally{t.emit({id:a,label:o,phase:`end`})}}}}function dK(e){return Zn(`sudo`,e)}async function fK(e,t){let n=e.trim();if(!n||Ree(Mee(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:dK(r)};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}function pK(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function mK(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function hK(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:mK(e.installAll)},affinity:{apps:pK(e.apps),tasks:pK(e.tasks),role:pK(e.role),purpose:pK(e.purpose)},priority:n}})}const gK={apps:3,tasks:2,role:1,purpose:1};function _K(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*gK.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*gK.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=gK.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=gK.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 vK(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 yK(e){let t=new Set;try{let n=await e.readDir(Xr);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 bK(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 xK(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function SK(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}async function CK(e,t){try{let n=xK(t);if(!n)return[];let r=await e(`${Xee}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?hK(Ot(r.body).data):[]}catch{return[]}}async function wK(e){let t;try{t=await e(ti,{headers:{Accept:`application/json`}})}catch(e){throw Error(ei(e,ti))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return hK(Ot(t.body).data)}function TK(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 EK(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 ui(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 DK(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 fi(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 li(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 OK(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 EK(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=TK(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 ui(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 kK(e,t,n,r,i,a,o,s,c,l){let u=await Qr(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 DK(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 li(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 AK(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 jK(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=bK(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=bK(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([wK(t),CK(t,a.company),yK(e)]);o=SK(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${ti}: ${e instanceof Error?e.message:String(e)}`])}let c=_K(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=AK(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await $r(a,o,t);return c.status===`error`?kK(n,i,a,o,d,u,r,s,t,e):OK(n,i,Jr(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await ii(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function MK(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let NK,PK;async function FK(e){if(NK)return NK;if(PK!==void 0)return PK;PK=(async()=>{let t;try{t=await e(Zr,{headers:{Accept:`application/json`}})}catch(e){throw Error(ei(e,Zr))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=Ot(t.body),r=Array.isArray(n)?n:n.skills??[];return NK=r,r})();try{return await PK}catch(e){throw PK=void 0,e}}async function IK(e,t){let n=await FK(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 LK=/^[A-Za-z0-9._-]+$/;function RK(e){return!e||e===`.`||e===`..`?!1:LK.test(e)}function zK(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(`/`)||!RK(r)||!RK(i))return null;let a=MK(r);return RK(a)?{hostname:a,task:i}:null}function BK(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 VK(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(`
|
|
1672
1672
|
`)}function HK(e){return e.replace(/(?:^|\n)> \[!NOTE\] \*\*Imported from browse\.sh\*\*[\s\S]*?(?:\n\n|$)/,`
|
|
1673
1673
|
`)}function UK(e,t){let n=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return n?`${n[1]}${n[2]||`
|
|
1674
1674
|
`}\n${t}\n\n${e.slice(n[0].length)}`:`${t}\n\n${e}`}async function WK(e,t,n){let r=`${e}/${t}`,i=`${Zr}/${e}/${t}`,a;try{let e=await n(i,{headers:{Accept:`application/json`}});if(e.status===404)return{ok:!1,error:`browse.sh skill "${r}" not found`};if(e.status!==200)return{ok:!1,error:`browse.sh returned HTTP ${e.status} for "${r}"`};a=Ot(e.body)}catch(e){return{ok:!1,error:`failed to fetch browse.sh skill "${r}": ${ei(e,i)}`}}let o;if(a.skillMdUrl)try{let e=await n(a.skillMdUrl,{headers:{Accept:`text/plain`}});e.status===200&&(o=kt(e.body))}catch{}if(!o&&a.skillMd&&(o=a.skillMd),!o)return{ok:!1,error:`browse.sh skill "${r}" has no SKILL.md content`};let s=BK(o,`name`),c=t.replace(/-[A-Za-z0-9]{4,8}$/,``),l=s||c||t;if(!RK(l)||l.length>64)return{ok:!1,error:`refusing to install browse.sh skill with unsafe name "${l}"`};if(!RK(e))return{ok:!1,error:`refusing to install browse.sh skill with unsafe hostname "${e}"`};let u=VK(a,r);return{ok:!0,dirName:`browse-${e}-${l}`,slug:r,content:UK(o,u)}}async function GK(e,t,n,r,i=!1){let a=await WK(e,t,r);if(!a.ok)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let{dirName:o,slug:s,content:c}=a,l=`${Xr}/${o}`;try{if(await n.stat(l),!i)return{stdout:``,stderr:`upskill: skill "${o}" already exists (use --force to overwrite)\n`,exitCode:1};await Zee(n,l,await pi(n,o))}catch{}return await n.mkdir(l,{recursive:!0}),await n.writeFile(`${l}/SKILL.md`,c),await di(n,o,{kind:`browse.sh`,source:s,skill:o,files:[`SKILL.md`]}),await ii(),{stdout:`Installed skill "${o}" from browse.sh (${s})\n`,stderr:``,exitCode:0}}function KK(){return"Discovery roots: /workspace/skills plus accessible **/.agents/skills/*, **/.claude/skills/*, **/.claude-plugin/marketplace.json skill collections anywhere in the VFS, and installed agent plugins (`plugin list`).\n"}function qK(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`;case`marketplace`:return`marketplace`;case`plugin`:return`plugin`}}function JK(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)} ${qK(t.source).padEnd(11)} ${i}\n`}return o+=`\n${KK()}`,o}function YK(e){let t=`Skill: ${e.name}\n`;if(t+=`Description: ${e.description||`(none)`}\n`,t+=`Source: ${qK(e.source)}\n`,t+=`Source root: ${e.sourceRoot}\n`,e.skillFilePath&&(t+=`Instructions: ${e.skillFilePath}\n`),e.shadowedPaths?.length){t+=`Shadowed paths:
|
|
@@ -1774,10 +1774,10 @@ Examples:
|
|
|
1774
1774
|
skill list
|
|
1775
1775
|
skill info bluebubbles
|
|
1776
1776
|
skill read bluebubbles
|
|
1777
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
1777
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-BeciHeJd.js`).then(e=>e.t);try{switch(r){case`list`:{let t=await i.discoverSkills(e);return t.length===0?{stdout:`No discoverable skills found.\n\n${KK()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:JK(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
1778
1778
|
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:YK(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
|
|
1779
1779
|
`,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+`
|
|
1780
|
-
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const QK=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&
|
|
1780
|
+
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const QK=[{names:[`--branch`,`-b`],validate:e=>!e.startsWith(`-`)&&Hn(e),error:`upskill: --branch must be a git ref of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", trailing "/" or ".lock", or shell metacharacters`,apply:(e,t)=>{e.branch=t}},{names:[`--from`],validate:e=>si(e)!==null,error:`upskill: --from requires a GitHub source (owner/repo, owner/repo@branch, or a github.com URL)`,apply:(e,t)=>{e.from=t}},{names:[`--path`,`-p`],validate:e=>Wn(e),error:`upskill: --path must be a repo-relative sub-path of [A-Za-z0-9._/-]+ with no "..", leading "-"/"/", or shell metacharacters`,apply:(e,t)=>{e.path=t}}];function $K(e){let t={skills:[],dryRun:!1,json:!1};for(let n=0;n<e.length;n++){let r=e[n],i=QK.find(e=>e.names.includes(r));if(i){let r=e[++n];if(!r||!i.validate(r))return t.error=i.error,t;i.apply(t,r)}else if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--json`)t.json=!0;else if(r.startsWith(`-`))return t.error=`upskill: unknown option "${r}" for update`,t;else t.skills.push(r)}return t}function eq(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}async function tq(e,t){try{let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(String(n))}catch{return}}async function nq(e,t,n,r){let i=await tq(e,t);return ete(n)?i?{status:`kept-local`,write:!1}:{status:`added`,write:!0}:i?eq(i,r)?{status:`unchanged`,write:!1}:{status:`updated`,write:!0}:{status:`added`,write:!0}}async function rq(e,t,n,r){let i={changes:[],writes:[],removals:[]};for(let[r,a]of n){let n=`${t}/${r}`,{status:o,write:s}=await nq(e,n,r,a);i.changes.push({path:r,status:o}),s&&i.writes.push({path:n,content:a})}let a=new Set(r.files??[]);for(let r of await Qee(e,t)){if(n.has(r))continue;let e=a.has(r);i.changes.push({path:r,status:e?`removed`:`kept-local`}),e&&i.removals.push(`${t}/${r}`)}return i.changes.sort((e,t)=>e.path.localeCompare(t.path)),i}async function iq(e,t,n,r,i,a){let o={skill:n,source:`${r.kind}:${r.source}`,ref:i??r.ref,from:r.sha,outcome:`current`,changes:[]},[s,c]=r.source.split(`/`);if(!s||!c)return{...o,outcome:`error`,error:`unusable source "${r.source}"`};let l=(r.path??``).replace(/^\/|\/$/g,``),u=await Qr(t),d=await oi(s,c,o.ref,u,!0);if(d&&r.sha===d&&await aq(e,n,r))return{...o,to:d,outcome:`current`,changes:[]};let f=await oq(s,c,l,n,o.ref,t,u);if(`error`in f)return{...o,outcome:`error`,error:f.error};let p=f.files,m=f.path;if(p.size===0)return{...o,outcome:`error`,error:`no files at ${s}/${c}${m?`/${m}`:``} — the skill may have moved or been removed upstream`};let{changes:h,writes:g,removals:_}=await rq(e,`${Xr}/${n}`,p,r),v=g.length>0||_.length>0;if(a)return{...o,outcome:v?`updated`:`current`,changes:h};let y=d??r.sha;return v&&await dq(e,{changes:h,writes:g,removals:_}),await di(e,n,{...r,ref:o.ref,path:m,sha:y,files:[...p.keys()].sort()}),{...o,to:y,outcome:v?`updated`:`current`,changes:h}}async function aq(e,t,n){if(!n.files?.length)return!1;for(let r of n.files)if(!await e.exists(`/workspace/skills/${t}/${r}`))return!1;return!0}async function oq(e,t,n,r,i,a,o){let s=await $r(e,t,a,i??`main`);if(s.status===`ok`){let i=Jr(s.files),a=n||sq(i,r);return a===null?{error:`could not find "${r}/SKILL.md" in ${e}/${t} — pass --path <dir> to say where the skill lives`}:{files:uq(i,a),path:a}}try{return{files:lq(cq(await $ee(e,t,n,i,o))),path:n}}catch(e){let t=e instanceof Error?e.message:String(e);return{error:`${s.message}; Contents API fallback failed: ${t}`}}}function sq(e,t){let n=[];for(let r of Object.keys(e))r===`SKILL.md`?n.push(``):(r.endsWith(`/${t}/SKILL.md`)||r===`${t}/SKILL.md`)&&n.push(r.slice(0,-9));return n.length===0?null:(n.sort((e,t)=>e.split(`/`).length-t.split(`/`).length||e.localeCompare(t)),n[0])}function cq(e){return new Map([...e].filter(([e])=>Yr(e)))}function lq(e){return new Map([...e].sort(([e],[t])=>e.localeCompare(t)))}function uq(e,t){let n=t?`${t}/`:``,r=new Map;for(let[t,i]of Object.entries(e)){if(!t.startsWith(n)||t.endsWith(`/`))continue;let e=t.slice(n.length);Yr(e)&&r.set(e,i)}return lq(r)}async function dq(e,t){for(let n of t.writes){let t=n.path.slice(0,n.path.lastIndexOf(`/`));await e.mkdir(t,{recursive:!0}),await e.writeFile(n.path,n.content)}for(let n of t.removals)await e.rm(n).catch(()=>{})}async function fq(e,t,n,r,i){let a={skill:n,source:`${r.kind}:${r.source}`,outcome:`current`,changes:[]},[o,s]=r.source.split(`/`);if(!o||!s)return{...a,outcome:`error`,error:`unusable source "${r.source}"`};let c=await WK(o,s,t);if(!c.ok)return{...a,outcome:`error`,error:c.error};let l=`${Xr}/${n}/SKILL.md`,u=await tq(e,l),d=new TextEncoder().encode(c.content),f=u!==void 0&&HK(new TextDecoder().decode(u))===HK(c.content);if(eq(u,d)||f)return{...a,changes:[{path:`SKILL.md`,status:`unchanged`}]};let p=u?`updated`:`added`;return i||(await e.mkdir(`${Xr}/${n}`,{recursive:!0}),await e.writeFile(l,d),await di(e,n,{...r,files:[`SKILL.md`]})),{...a,outcome:`updated`,changes:[{path:`SKILL.md`,status:p}]}}function pq(e,t){if(e.outcome===`error`)return` ${e.skill}: failed — ${e.error}\n`;let n=new Map;for(let t of e.changes)n.set(t.status,(n.get(t.status)??0)+1);let r=e.to&&e.to!==e.from?` → ${e.to.slice(0,7)}`:``;if(e.outcome===`current`)return` ${e.skill}: already current (${e.source}${r})\n`;let i=t?`would update`:`updated`,a=` ${e.skill}: ${i} from ${e.source}${r}\n`;for(let t of e.changes)t.status!==`unchanged`&&(a+=` ${t.status.padEnd(10)} ${t.path}\n`);let o=n.get(`kept-local`)??0;return o>0&&(a+=` (${o} kept-local — dotfiles and local additions are never touched)\n`),a}function mq(e,t,n,r){let i=si(t);return i?{version:1,kind:`github`,source:`${i.owner}/${i.repo}`,skill:e,ref:r??i.branch,path:n??i.path,installed:new Date().toISOString()}:null}async function hq(e,t,n){if(t.length===0)return{targets:await mi(e),missing:[]};let r=[],i=[];for(let a of t){let t=await ai(e,a);if(t){r.push({name:a,provenance:t});continue}if(!await e.exists(`/workspace/skills/${a}`)){i.push({name:a,reason:`not-installed`});continue}let o=n.from?mq(a,n.from,n.path,n.branch):null;o?r.push({name:a,provenance:o}):i.push({name:a,reason:`no-provenance`})}return{targets:r,missing:i}}function gq(e){return e.reason===`not-installed`?`upskill: no skill named "${e.name}" is installed — check \`upskill list\`
|
|
1781
1781
|
`:`upskill: no install provenance for "${e.name}" — re-run with --from <owner>/<repo> (optionally --path <dir>) to record its source, or reinstall it once
|
|
1782
1782
|
`}function _q(e,t,n,r){let i=t?`Skill update (dry run — nothing written):
|
|
1783
1783
|
`:`Skill update:
|
|
@@ -1789,7 +1789,7 @@ Nothing to update — all skills are current.
|
|
|
1789
1789
|
`}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:
|
|
1790
1790
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
1791
1791
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
1792
|
-
`,{stdout:p,stderr:``,exitCode:0}}function wq(e,t,n){let r=`upskill ${e}`;return t&&(r+=` --branch ${t}`),n&&(r+=` --path ${n}`),r}async function Tq(e,t){let n=[],r;try{r=await t(e,{method:`GET`})}catch(t){return n.push({rel:
|
|
1792
|
+
`,{stdout:p,stderr:``,exitCode:0}}function wq(e,t,n){let r=`upskill ${e}`;return t&&(r+=` --branch ${t}`),n&&(r+=` --path ${n}`),r}async function Tq(e,t){let n=[],r;try{r=await t(e,{method:`GET`})}catch(t){return n.push({rel:Vn,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=Un(i,e),o=[];for(let e of a){if(!e.rel.includes(Vn))continue;let t=Gn([e]);t?.verb===`upskill`&&o.push({target:t.target,branch:t.branch,path:t.path,instruction:t.instruction,installHint:wq(t.target,t.branch,t.path)})}return{links:o,failures:n}}function Eq(e,t,n){if(!e||t.length===0)return[];let r=[];for(let i of t){if(!i.hostname||MK(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 Dq(e){let t=e.active?` [active]`:``,n=`${e.title||`(untitled)`}${t}\n`;if(n+=` ${e.url}\n`,e.origin.length>0){n+=` Origin-advertised:
|
|
1793
1793
|
`;for(let t of e.origin)n+=` ${t.installHint}`,t.instruction&&(n+=` # ${t.instruction}`),n+=`
|
|
1794
1794
|
`}if(e.catalog.length>0){n+=` Browse.sh catalog:
|
|
1795
1795
|
`;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.
|
|
@@ -1806,9 +1806,9 @@ Nothing to update — all skills are current.
|
|
|
1806
1806
|
|
|
1807
1807
|
`,c=0;for(let e of o){c++;let t=vK(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
|
|
1808
1808
|
`,{stdout:s,stderr:``,exitCode:0}}function Aq(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
1809
|
-
`,exitCode:1}:
|
|
1810
|
-
`,exitCode:1}}function jq(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`||!
|
|
1811
|
-
`,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=Aq(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 Mq(e){let t=await(await import(`./skills-
|
|
1809
|
+
`,exitCode:1}:Hn(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
|
|
1810
|
+
`,exitCode:1}}function jq(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`||!Wn(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
|
|
1811
|
+
`,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=Aq(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 Mq(e){let t=await(await import(`./skills-BeciHeJd.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${KK()}`,stderr:``,exitCode:0}:{stdout:JK(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function Nq(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-BeciHeJd.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);if(!e)return{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1};let i=await ai(n,t),a=i?ci(i):"Installed from: (no provenance recorded — reinstall to enable `upskill update`)\n";return{stdout:YK(e)+a,stderr:``,exitCode:0}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
1812
1812
|
`,stderr:``,exitCode:0}}async function Pq(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 ui(p.path,p.name,r,i,a,s?{...s,path:p.path}:void 0),h=f+1,g=((Date.now()-o)/1e3).toFixed(1),_=(Date.now()-o)/h,v=h<d?` (~${Math.round((d-h)*_/1e3)}s remaining)`:``;m.ok?(c+=`[${h}/${d}] Installed "${p.name}" from ${t}/${n} (${g}s)${v}\n`,u++):(c+=`[${h}/${d}] Failed "${p.name}": ${m.error}${v}\n`,l+=`upskill: ${m.error}\n`)}return{output:c,errors:l,successCount:u}}async function Fq(e,t,n,r,i,a,o,s){let c=``,l=``,u=0,d=e.length;for(let f=0;f<e.length;f++){let p=e[f],m=await li(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 Iq(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await li(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 Lq(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 Rq(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await Qr(r),l=await fi(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:Lq(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:Lq(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 $r(i,a,r,o);if(e.status===`ok`){let r=await oi(i,a,o,c),s=await Pq(u,i,a,Jr(e.files),n,t.force,f,{kind:`github`,source:`${i}/${a}`,ref:o,sha:r});({output:p,errors:m,successCount:h}=s)}else{let e=await Fq(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await Iq(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 ii()),{stdout:p,stderr:m,exitCode:+!!m}}async function zq(e,t,n,r){switch(e[0]){case`tabs`:return Oq(t,n,r,e.includes(`--json`));case`recommendations`:return kq(t,n,e.includes(`--install`));case`update`:case`upgrade`:return vq(e.slice(1),t,n);case`list`:return Mq(t);case`info`:case`read`:return Nq(e[0],e[1],t);case`search`:return Vq(e,n);default:return null}}function Bq(e,t,n){return V(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return XK();let a=await zq(r,e,t,n);if(a)return a;let o=jq(r);if(o.earlyReturn)return o.earlyReturn;if(!o.sourceRef)return XK();if(o.sourceRef.startsWith(`tessl:`))return Hq(o.sourceRef,o.force,e,t);let s=zK(o.sourceRef);if(s)return GK(s.hostname,s.task,e,t,o.force);let c=si(o.sourceRef);return c?Rq(c,o,e,t):{stdout:``,stderr:`upskill: unrecognized source "${o.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function Vq(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?Cq(a,t,i):XK()}async function Hq(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
1813
1813
|
`,exitCode:1};let a=await bq(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await Qr(r);return li(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function Uq(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
1814
1814
|
|
|
@@ -2097,7 +2097,7 @@ async function main() {
|
|
|
2097
2097
|
main().catch((err) => { process.stderr.write(String(err && err.message || err) + '\\n'); process.exit(1); });
|
|
2098
2098
|
`;function aY(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}); ${GJ}\n`}async function oY(e,t,n,r,i,a,o,s,c){let l={op:t,write:n,check:r,configuration:i,configurationRoot:a,reporter:o,files:s.map(e=>({path:e.path,biomePath:rY(e.path,a),source:e.source,wrap:PJ(e.path)}))},u=[`node`,`[biome-helper]`,JSON.stringify(l),c],d=await EG(iY,u,e,void 0,{filename:`[biome-helper]`});if(d.exitCode!==0)return{results:[],stderr:aY(d.stderr)??d.stderr,exitCode:d.exitCode};try{return{results:JSON.parse(d.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}}}function sY(e,t,n,r=``){if(e===`plain`)return t;let i=(t.stderr||t.stdout).trimEnd(),a=i?[{severity:t.exitCode===0?`information`:`error`,category:n,message:i,filePath:r,line:null,column:null}]:[],o={summary:{errors:t.exitCode===0?0:1,warnings:0,filesChecked:0,unformattedFiles:0},diagnostics:a,files:[]};return{stdout:`${JSON.stringify(o)}\n`,stderr:``,exitCode:t.exitCode}}async function cY(e,t){let n=await nY(t);if(!n.ok)return{stdout:``,stderr:`biome: ${n.missing} is not installed (run: ipk add ${WJ[n.missing]??n.missing}); ${GJ}\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 ${WJ[`@biomejs/wasm-web`]})\n`,exitCode:1}}async function lY(e,t){if(t.paths.length===0&&e.stdin)return{inputs:[{path:t.stdinFilePath??`/stdin.ts`,source:hG(e.stdin)}],missingErrText:``};if(t.paths.length===0)return{stdout:``,stderr:`biome: no files or directories specified
|
|
2099
2099
|
`,exitCode:2};let n=await $J(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 uY(e,t,n,r,i){let a=[],o=[i],s=0,c=0,l=0;for(let i of r.results)t.reporter===`plain`&&i.diagnosticsText&&o.push(OJ(i.diagnosticsText)),s+=i.errorCount,c+=i.warningCount,t.write&&i.formatted!==null&&!i.unchanged?(await e.fs.writeFile(i.path,i.formatted),l++):!t.write&&t.subcommand===`format`&&!t.check&&n.length===1&&n[0].path===i.path&&a.push(i.formatted??n[0].source);t.write&&l>0&&o.push(`biome: wrote ${l} file(s)\n`);let u=+(s>0||c>0||i.length>0);if(t.reporter===`json`){let e=i?[{severity:`error`,category:`io`,message:i.trimEnd(),filePath:``,line:null,column:null}]:[],t={summary:{errors:s+e.length,warnings:c,filesChecked:r.results.length,unformattedFiles:r.results.filter(e=>!e.unchanged).length},diagnostics:[...r.results.flatMap(e=>e.diagnostics),...e],files:r.results.map(e=>({path:e.path,unchanged:e.unchanged}))};return{stdout:`${JSON.stringify(t)}\n`,stderr:``,exitCode:u}}return{stdout:a.join(``),stderr:o.join(``),exitCode:u}}async function dY(e){let t=await tY(e);return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`biome: @biomejs/wasm-web is not installed (run: ipk add @biomejs/wasm-web@${BJ}); ${GJ}\n`,exitCode:1}}async function fY(e,t){return e.showHelp?sY(e.reporter,{stdout:KJ,stderr:``,exitCode:0},`usage`):e.showVersion?sY(e.reporter,await dY(t),`runtime`):null}function pY(e,t){let n=e.paths[0];if(!n)return``;try{return t.fs.resolvePath(t.cwd,n)}catch{return``}}async function mY(e,t){let n=LJ(t),r=await fY(e,n);if(r)return r;if(e.subcommand===null)return sY(e.reporter,{stdout:``,stderr:`biome: missing subcommand (expected check, lint, or format)
|
|
2100
|
-
`,exitCode:2},`usage`);let i=await lY(t,e);if(`exitCode`in i)return sY(e.reporter,i,`io`);let a=e.paths.length===0&&t.stdin?t.cwd:Mt(i.inputs[0].path).dir,o=await wJ(t.fs,t.cwd,a,e.configPath);if(!o.ok)return sY(e.reporter,{stdout:``,stderr:`${o.error}\n`,exitCode:o.exitCode},`configuration`,i.inputs[0].path);let s=await cY(t,n);if(`exitCode`in s)return sY(e.reporter,s,`runtime`,i.inputs[0].path);let c=await oY(t,e.subcommand,e.write,e.check,o.resolved?.configuration??null,o.resolved===null?null:Mt(o.resolved.path).dir,e.reporter,i.inputs,s.wasmPath);return c.exitCode===0?uY(t,e,i.inputs,c,i.missingErrText):sY(e.reporter,{stdout:``,stderr:i.missingErrText+c.stderr,exitCode:c.exitCode},`runtime`,i.inputs[0].path)}function hY(){return V(`biome`,async(e,t)=>{let n;try{n=QJ(e)}catch(t){return sY(YJ(e)?`json`:`plain`,{stdout:``,stderr:`${t instanceof Error?t.message:String(t)}\n`,exitCode:2},`usage`)}try{return await mY(n,t)}catch(e){if(n.reporter===`plain`)throw e;return sY(`json`,{stdout:``,stderr:`biome: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1},`runtime`,pY(n,t))}})}r(`tray-sync`),new TextEncoder;const gY=r(`scoops.tray-leave`);function _Y(){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 vY(e={},t=_Y()){let n=e.workerBaseUrl??null;if(t.storage)try{t.storage.removeItem(
|
|
2100
|
+
`,exitCode:2},`usage`);let i=await lY(t,e);if(`exitCode`in i)return sY(e.reporter,i,`io`);let a=e.paths.length===0&&t.stdin?t.cwd:Mt(i.inputs[0].path).dir,o=await wJ(t.fs,t.cwd,a,e.configPath);if(!o.ok)return sY(e.reporter,{stdout:``,stderr:`${o.error}\n`,exitCode:o.exitCode},`configuration`,i.inputs[0].path);let s=await cY(t,n);if(`exitCode`in s)return sY(e.reporter,s,`runtime`,i.inputs[0].path);let c=await oY(t,e.subcommand,e.write,e.check,o.resolved?.configuration??null,o.resolved===null?null:Mt(o.resolved.path).dir,e.reporter,i.inputs,s.wasmPath);return c.exitCode===0?uY(t,e,i.inputs,c,i.missingErrText):sY(e.reporter,{stdout:``,stderr:i.missingErrText+c.stderr,exitCode:c.exitCode},`runtime`,i.inputs[0].path)}function hY(){return V(`biome`,async(e,t)=>{let n;try{n=QJ(e)}catch(t){return sY(YJ(e)?`json`:`plain`,{stdout:``,stderr:`${t instanceof Error?t.message:String(t)}\n`,exitCode:2},`usage`)}try{return await mY(n,t)}catch(e){if(n.reporter===`plain`)throw e;return sY(`json`,{stdout:``,stderr:`biome: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1},`runtime`,pY(n,t))}})}r(`tray-sync`),new TextEncoder;const gY=r(`scoops.tray-leave`);function _Y(){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 vY(e={},t=_Y()){let n=e.workerBaseUrl??null;if(t.storage)try{t.storage.removeItem(In),n===null?t.storage.removeItem(Ln):t.storage.setItem(Ln,n)}catch(t){gY.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 yY=r(`scoops.tray-join`);async function bY(e,t={},n=_Y()){if(n.storage){let r=Fn(e);try{n.storage.setItem(In,r?.joinUrl??e),r&&n.storage.setItem(Ln,r.workerBaseUrl)}catch(e){yY.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 xY(){return SY()}function SY(){try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayFollowers`);if(e)return JSON.parse(e)}catch{}return[]}function CY(){let e=i();if(e)return async()=>await e.call(`tray-reset`,void 0)}function wY(){return{stdout:`host - display or manage the current tray host status
|
|
2101
2101
|
|
|
2102
2102
|
Usage: host [join <join-url> | reset | leave [--leader <worker-url>]]
|
|
2103
2103
|
|
|
@@ -2110,12 +2110,12 @@ Subcommands:
|
|
|
2110
2110
|
leave --leader <worker-url> Leave the current role and immediately become a leader on <worker-url>
|
|
2111
2111
|
`,stderr:``,exitCode:0}}function TY(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 EY(e){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 ${TY(n)}`)}let n=[];e.exec&&n.push(`[ssh]`),e.cdp&&n.push(`[playwright]`),n.length>0&&t.push(n.join(` `));let r=[` - ${t.join(` `)}`];return e.exec&&e.motd&&r.push(` ${e.motd}`),r}function DY(e){let t=e.filter(e=>e.exec||e.cdp),n=e.length-t.length,r=[];if(t.length>0){r.push(`followers:`);for(let e of t)r.push(...EY(e))}return n>0&&r.push(`(${n} other follower${n===1?``:`s`} with no exec/browser capability)`),r}function OY(e,t){let n=[`status: ${e.state}`];return e.session?n.push(`join_url: ${e.session.joinUrl}`):n.push(`join_url: unavailable`),e.error&&n.push(`error: ${e.error}`),e.session&&n.push(...DY(t)),`${n.join(`
|
|
2112
2112
|
`)}\n`}function kY(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: ${TY(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(`
|
|
2113
|
-
`)}\n`}function AY(e={}){let t=e.getStatus??
|
|
2114
|
-
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:OY(t(),r()),stderr:``,exitCode:0}:{stdout:kY(a),stderr:``,exitCode:0}})}function jY(){return async({workerBaseUrl:e,requestId:t})=>{let n=i();if(n)return await n.call(`tray-leave`,{workerBaseUrl:e,requestId:t});let r=Jg(),a=
|
|
2113
|
+
`)}\n`}function AY(e={}){let t=e.getStatus??un,n=e.getFollowerStatus??Ore,r=e.getFollowers??SY;return V(`host`,async i=>{if(i.includes(`--help`)||i.includes(`-h`))return wY();if(i[0]===`reset`){let r=e.resetTray??void 0??CY();return zY(n,t,r)}if(i[0]===`join`){let t=e.joinTray??PY();return FY(i.slice(1),t)}if(i[0]===`leave`){let r=e.leaveTray??jY();return IY(i.slice(1),t,n,r)}if(i.length>0)return{stdout:``,stderr:`host: unsupported arguments
|
|
2114
|
+
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:OY(t(),r()),stderr:``,exitCode:0}:{stdout:kY(a),stderr:``,exitCode:0}})}function jY(){return async({workerBaseUrl:e,requestId:t})=>{let n=i();if(n)return await n.call(`tray-leave`,{workerBaseUrl:e,requestId:t});let r=Jg(),a=un(),o=r.state===`inactive`?a.state===`inactive`?`inactive`:`leader`:`follower`;return await vY({workerBaseUrl:e,requestId:t}),e===null?o===`inactive`?{kind:`noop`}:{kind:`left`,previousMode:o}:{kind:`switched`,previousMode:o,workerBaseUrl:e}}}function MY(){return`host-leave-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function NY(){return`host-join-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function PY(){return async({joinUrl:e,requestId:t})=>{let n=i();if(n){await n.call(`tray-join`,{joinUrl:e,requestId:t});return}await bY(e,{requestId:t})}}async function FY(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
|
|
2115
2115
|
Usage: host join <join-url>
|
|
2116
|
-
`,exitCode:1};let r=
|
|
2116
|
+
`,exitCode:1};let r=Fn(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".
|
|
2117
2117
|
`,exitCode:1};try{return await t({joinUrl:r.joinUrl,requestId:NY()}),{stdout:`Joining tray as follower: ${r.joinUrl}\nRun \`host\` to check connection status.
|
|
2118
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function IY(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=
|
|
2118
|
+
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function IY(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=Pn(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
|
|
2119
2119
|
`,exitCode:0}}try{return{stdout:LY(await r({workerBaseUrl:i,requestId:MY()})),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.
|
|
2120
2120
|
`,exitCode:1}}}function LY(e){switch(e.kind){case`noop`:return`No active tray session.
|
|
2121
2121
|
`;case`left`:{let t=e.previousMode;switch(t){case`leader`:return`Stopped leader. Tray runtime is now dormant.
|
|
@@ -2307,7 +2307,7 @@ Examples:
|
|
|
2307
2307
|
discover ${v}/handoff?handoff=demo
|
|
2308
2308
|
discover --follow ${v}/llms.txt
|
|
2309
2309
|
`}function YQ(){return V(`discover`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return{stdout:JQ(),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
|
|
2310
|
-
`,exitCode:2};let r=n[0],i=p(),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=
|
|
2310
|
+
`,exitCode:2};let r=n[0],i=p(),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=Un(o,r),c=Gn(s),l={url:r,status:a.status,links:s,handoff:c};if(t&&s.length>0){let e=await WQ(s,{fetchImpl:qQ(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)+`
|
|
2311
2311
|
`,stderr:``,exitCode:0}})}function XQ(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 ZQ=`esbuild - thin wrapper over the ipk-loaded esbuild-wasm
|
|
2312
2312
|
|
|
2313
2313
|
Usage:
|
|
@@ -2601,7 +2601,7 @@ Options:
|
|
|
2601
2601
|
`,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 r2(e,r),n=await w2(t?n=>e.evaluateInFrame(t.frameId,n,{world:`main`}):t=>e.evaluate(t),a);return typeof n==`string`?n:JSON.stringify(n,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`)+`
|
|
2602
2602
|
`,stderr:``,exitCode:0}},E2=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`eval-file requires a file path
|
|
2603
2603
|
`,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 w2(t=>e.evaluate(t),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`)+`
|
|
2604
|
-
`,stderr:``,exitCode:0}};function D2(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=f(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 O2(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 k2(e,t,n){let r=``;try{r=new URL(e).hostname}catch{return{}}let i=r?MK(r):``;if(!i)return{};let a;try{a=await FK(n)}catch(e){return{warning:`playwright-cli: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}`}}let o=await O2(t),s=[];for(let e of a){if(!e.hostname||MK(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 A2(e,t={}){let n=t.fetchImpl??p(),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=
|
|
2604
|
+
`,stderr:``,exitCode:0}};function D2(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=f(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 O2(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 k2(e,t,n){let r=``;try{r=new URL(e).hostname}catch{return{}}let i=r?MK(r):``;if(!i)return{};let a;try{a=await FK(n)}catch(e){return{warning:`playwright-cli: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}`}}let o=await O2(t),s=[];for(let e of a){if(!e.hostname||MK(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 A2(e,t={}){let n=t.fetchImpl??p(),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=Un(i,e),o=Gn(a),s={url:e,status:r.status,links:a,handoff:o};if(t.discover&&a.length>0){let e=await WQ(a,{fetchImpl:D2(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 k2(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 j2=async({fs:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`fetch requires a URL
|
|
2605
2605
|
`,exitCode:1};let r=t[0],{browseShWarning:i,...a}=await A2(r,{discover:n.discover===`true`,method:n.method??`GET`,fs:e});return{stdout:JSON.stringify(a,null,2)+`
|
|
2606
2606
|
`,stderr:i?`${i}\n`:``,exitCode:+!!a.error}};function M2(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 N2(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 P2(e,t,n){let r=e.getTransport(),i=e.getSessionId();((await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:Q0,returnByValue:!0},i)).result?.value??``)!==n&&await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:Z0,arguments:[{value:n}],returnByValue:!0},i)}async function F2(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:$0,returnByValue:!0},i),await e.insertText(n),a?.objectId&&await P2(e,a.objectId,n)}async function I2(e,t,n){await e.click(t),await e.evaluate(`(function() {
|
|
2607
2607
|
const el = document.querySelector(${JSON.stringify(t)});
|
|
@@ -3212,7 +3212,7 @@ Common base URLs:
|
|
|
3212
3212
|
llama.cpp http://localhost:8080/v1
|
|
3213
3213
|
vLLM http://localhost:8000/v1
|
|
3214
3214
|
Jan http://localhost:1337/v1
|
|
3215
|
-
`}function Woe(){return V(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Uoe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
3215
|
+
`}function Woe(){return V(Q6,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Uoe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-wn9tOS6g.js`),{verifyConnection:a}=await import(`./local-llm-djwmLEi-.js`).then(e=>e.n),o=e[0]??`status`;if(o!==`status`&&o!==`discover`)return{stdout:``,stderr:`Unknown subcommand: ${o}. See \`local-llm --help\`.\n`,exitCode:2};let s=r(Q6);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
3216
3216
|
`,exitCode:1};let c=await a(s,t(Q6)??void 0);if(!c.ok){let e=[`✗ Could not reach ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` error: ${c.error?.message??`unknown`}`];return c.error?.hint&&e.push(` hint: ${c.error.hint}`),{stdout:``,stderr:e.join(`
|
|
3217
3217
|
`)+`
|
|
3218
3218
|
`,exitCode:1}}if(o===`discover`){let e=n(Q6)??``;return i(Q6,e,s,c.models.join(`, `)),{stdout:[`✓ ${s} (${c.runtime.kind}${c.runtime.version?` ${c.runtime.version}`:``})`,` Saved ${c.models.length} model${c.models.length===1?``:`s`} to Settings:`,...c.models.map(e=>` • ${e}`)].join(`
|
|
@@ -3256,20 +3256,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
3256
3256
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
3257
3257
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
3258
3258
|
short name resolves on the PATH.
|
|
3259
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
3259
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return n8(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return n8(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return n8(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-_EfBoYjW.js`).then(e=>e.r);if(await a(i,t.fs))return n8(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-DVC0x03n.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 Zoe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>s8(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,protocolVersion:l.getNegotiatedProtocolVersion(),tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await gse(i,t);let m=await u8(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-DePb9O4W.js`);e({name:i,serverUrl:r,auth:u})}return t8([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${e8}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
3260
3260
|
`)+`
|
|
3261
|
-
`)}async function Zoe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-
|
|
3262
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
3261
|
+
`)}async function Zoe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-DR6XMm1M.js`),{saveOAuthAccount:s}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r),c=await mse(r.oauthFetchImpl),l=r.oauthLauncher??await c8(),u=await i(e,n,c);$6.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await ki(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt,scopes:m.scope}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,redirectUri:d,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function Qoe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp list
|
|
3262
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-DePb9O4W.js`);await n();let{listServers:r}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let o=[[`NAME`,`URL`,`AUTH`,`TOOLS`,`APPS`,`ADDED`]];for(let e of a){let t=i[e];o.push([e,t.url,t.auth?`yes`:`no`,String(t.tools?.length??0),String(t.apps?.length??0),t.addedAt?t.addedAt.slice(0,10):`-`])}return t8(r8(o))}function r8(e){let t=e[0].map((t,n)=>e.reduce((e,t)=>Math.max(e,(t[n]??``).length),0));return e.map(e=>e.map((e,n)=>e.padEnd(t[n])).join(` `).trimEnd()).join(`
|
|
3263
3263
|
`)+`
|
|
3264
3264
|
`}async function $oe(e,t){if(WZ(e))return t8(`usage: mcp search <query>
|
|
3265
3265
|
|
|
3266
3266
|
Case-insensitive substring search across the cached tools of every
|
|
3267
3267
|
registered MCP server. Matches tool name OR description and prints a
|
|
3268
3268
|
table of (server, tool, description, match-field) rows.
|
|
3269
|
-
`);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
3270
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
3269
|
+
`);if(e.length===0)return n8(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-DePb9O4W.js`);await i();let{listServers:a}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return t8("No MCP servers configured. Use `mcp add <url> <name>`.\n");let c=[];for(let e of s){let t=o[e].tools??[];for(let n of t){let t=n.description??``,i=n.name.toLowerCase().includes(r),a=t.toLowerCase().includes(r);if(!i&&!a)continue;let o=i&&a?`name+description`:i?`name`:`description`;c.push({server:e,tool:n.name,description:t,match:o})}}if(c.length===0)return t8(`No tools matched "${n}".\n`);c.sort((e,t)=>e.server===t.server?e.tool.localeCompare(t.tool):e.server.localeCompare(t.server));let l=[[`SERVER`,`TOOL`,`DESCRIPTION`,`MATCH`]];for(let e of c)l.push([e.server,e.tool,ese(e.description),e.match]);return t8(r8(l))}function ese(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function tse(e,t){if(e.length===0||WZ(e))return e.length===0?n8(`mcp delete: expected <name>`):t8(`usage: mcp delete <name>
|
|
3270
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-DePb9O4W.js`);await r(n);let{deleteServer:a}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),o=await a(n,t.fs);await _se(n,t),await vse(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){$6.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?n8(`mcp delete: no server, alias, or account found for "${n}"`):t8([`Removed MCP server "${n}"`,` servers.json: ${o?`removed`:`not present`}`,` alias: cleaned`,` sprinkles: cleaned`,` oauth: ${c?`removed`:`not present`}`,` provider: ${l?`unregistered`:`not registered`}`].join(`
|
|
3271
3271
|
`)+`
|
|
3272
|
-
`)}async function nse(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(ise());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
3272
|
+
`)}async function nse(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?n8(`mcp invoke: expected <name>`):t8(ise());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-DePb9O4W.js`);await i(n);let{getServer:a}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return n8(`mcp invoke: unknown server "${n}" (run \`mcp add <url> ${n}\` first)`);let s=o.tools??[];if(r.length===0||r[0]===`--help`||r[0]===`-h`)return t8(ase(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return n8(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=rse(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return t8(ose(n,l));let p=sse(d,l.inputSchema);if(!p.ok)return n8(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-DVC0x03n.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=dse(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function rse(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=i8(a.slice(10));e.ok?r=e.value:n.push(e.error),i+=1;continue}if(a===`--timeout`){let t=e[i+1];if(t===void 0||t.startsWith(`--`)){n.push(`mcp invoke: --timeout requires a value (got ${t===void 0?`nothing`:`"${t}"`}); using default.`),i+=1;continue}let a=i8(t);a.ok?r=a.value:n.push(a.error),i+=2;continue}t.push(a),i+=1}return{timeoutMs:r,remaining:t,warnings:n}}function i8(e){if(!/^-?\d+$/.test(e))return{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (expected positive integer seconds); using default.`};let t=Number(e);return!Number.isFinite(t)||t<1?{ok:!1,error:`mcp invoke: invalid --timeout value "${e}" (must be >= 1 second); using default.`}:{ok:!0,value:t*1e3}}function ise(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
3273
3273
|
|
|
3274
3274
|
mcp invoke <name> List tools on <name>.
|
|
3275
3275
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -3299,7 +3299,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
3299
3299
|
|
|
3300
3300
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
3301
3301
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
3302
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
3302
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-DePb9O4W.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return n8(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-DVC0x03n.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>s8(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return n8(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,protocolVersion:l.getNegotiatedProtocolVersion(),tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await u8(n,d,t);return t8(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function pse(e,t){if(e.includes(`--help`)||e.includes(`-h`))return t8(`usage: mcp auth <name> [--silent | --interactive]
|
|
3303
3303
|
|
|
3304
3304
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
3305
3305
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -3311,7 +3311,7 @@ Options:
|
|
|
3311
3311
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
3312
3312
|
directly. Use after revoking a refresh token or
|
|
3313
3313
|
when the AS no longer accepts the cached one.
|
|
3314
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
3314
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return n8(`mcp auth: expected <name>`);let r=n[0],i=e.includes(`--silent`)||e.includes(`-s`),a=e.includes(`--interactive`)||e.includes(`-i`);if(i&&a)return n8(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-DePb9O4W.js`),s=await o(r,{fetchImpl:t.oauthFetchImpl,launcher:t.oauthLauncher}),{getServer:c}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return n8(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return n8(`mcp auth: server "${r}" does not use OAuth`);if(!s)return n8(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-CdbrXnHp.js`).then(e=>e.r),f=d(u);if(!f)return n8(`mcp auth: provider "${u}" is not registered`);if(a)return await o8(r,f,t);if(!f.onSilentRenew)return i?n8(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await o8(r,f,t);let p=null;try{p=await f.onSilentRenew()}catch(e){let t=e instanceof Error?e.message:String(e);if(i)return n8(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);$6.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?t8(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?n8(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await o8(r,f,t)}async function o8(e,t,n){if(!t.onOAuthLogin)return n8(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await c8(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?t8(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):n8(`mcp auth: interactive login for "${e}" did not complete`)}async function s8(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-CdbrXnHp.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){$6.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function c8(){let{createOAuthLauncher:e}=await import(`./oauth-service-CTntqv0R.js`);return e()}async function mse(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-Co-pb0x0.js`).then(e=>e.n),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function l8(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-Dnva5HZ3.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return await t.create({dbName:n})}function hse(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
3315
3315
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
3316
3316
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
3317
3317
|
const escape = (s) => {
|
|
@@ -3325,7 +3325,7 @@ const r = await exec(cmd);
|
|
|
3325
3325
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
3326
3326
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
3327
3327
|
process.exit(r.exitCode || 0);
|
|
3328
|
-
`}async function gse(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,hse(e)),t.scriptCatalog?.invalidateJsh()}async function _se(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function vse(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
3328
|
+
`}async function gse(e,t){let n=await l8(t.fs);await n.mkdir(e8,{recursive:!0}),await n.writeFile(`${e8}/${e}.jsh`,hse(e)),t.scriptCatalog?.invalidateJsh()}async function _se(e,t){let n=await l8(t.fs),r=`${e8}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){$6.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function vse(e,t){let{removeAppSprinkles:n}=await import(`./apps-pxc-GoM0.js`);await n(e,t.fs)}async function u8(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-pxc-GoM0.js`);return(await r(e,t,n.fs)).length}catch(t){return $6.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}function d8(e){return{stdout:``,stderr:`meminfo: ${e}\n`,exitCode:1}}function f8(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e,r=`B`;for(let e of t){if(n<1024)break;n/=1024,r=e}return`${n.toFixed(1)} ${r}`}function yse(e){return e.attribution.length===0?`(shared)`:e.attribution.map(e=>{let t=e.container?.src??e.container?.id??e.url??`?`;return e.scope?`${e.scope} ${t}`:t}).join(`, `)}function bse(){let e=globalThis.performance,t=e?.measureUserAgentSpecificMemory;return t?t.bind(e):null}function xse(e){if(e[0]===`--help`||e[0]===`-h`||e[0]===`help`)return{help:!0};let t=!1;for(let n of e){if(n!==`--json`)return{error:`unknown option '${n}' — see \`meminfo --help\``};t=!0}return{help:!1,json:t}}function Sse(e){let t=[`total: ${f8(e.bytes)}`],n=[...e.breakdown].filter(e=>e.bytes>0).sort((e,t)=>t.bytes-e.bytes);if(n.length>0){t.push(``,`BYTES TYPES ATTRIBUTION`);for(let e of n)t.push(`${f8(e.bytes).padEnd(10)} ${e.types.join(`,`).padEnd(20)} ${yse(e)}`)}return`${t.join(`
|
|
3329
3329
|
`)}\n`}function Cse(e={}){return V(`meminfo`,async t=>{let n=xse(t);if(`error`in n)return d8(n.error);if(n.help)return{stdout:`meminfo - agent-cluster memory diagnostics
|
|
3330
3330
|
|
|
3331
3331
|
Usage:
|
|
@@ -3351,7 +3351,7 @@ Options:
|
|
|
3351
3351
|
-h, --help Show this help message
|
|
3352
3352
|
`}function Dse(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function h8(e){return`$${e.toFixed(2)}`}const Ose=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function kse(e){let t=`${e.id} ${e.name??``}`;return!Ose.test(t)}function Ase(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 jse(e){let t=new Map;for(let n of e){let e=Ase(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function Mse(e,t,n,r,i){let a=i?Tse(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 Nse(e,t,n,r){let i=[];i.push(`Models for "${e}" (${t}):\n`);for(let e of n){let t=e.selected?` ► `:` `,n=e.id.padEnd(30),r=`${h8(e.cost.input)} / ${h8(e.cost.output)}`,a=`${Dse(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(`
|
|
3353
3353
|
`)+`
|
|
3354
|
-
`}function Pse(e){return V(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
3354
|
+
`}function Pse(e){return V(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-wn9tOS6g.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:Ese(),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.
|
|
3355
3355
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await wse(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(kse);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>Mse(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=jse(n)),w.push(...n),!l){let t=i(e);T.push(Nse(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
3356
3356
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
3357
3357
|
`);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(`
|
|
@@ -3391,7 +3391,7 @@ Examples:
|
|
|
3391
3391
|
oauth-domain add adobe '*.da.live'
|
|
3392
3392
|
oauth-domain list adobe
|
|
3393
3393
|
oauth-domain remove adobe admin.da.live
|
|
3394
|
-
`}function Wse(){return V(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
3394
|
+
`}function Wse(){return V(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:_8(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-wn9tOS6g.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(`
|
|
3395
3395
|
`)+`
|
|
3396
3396
|
`,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)
|
|
3397
3397
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -3463,7 +3463,7 @@ Examples:
|
|
|
3463
3463
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
3464
3464
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
3465
3465
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
3466
|
-
`}function Zse(){return V(`oauth-token`,Qse)}async function Qse(e,t){let n=await import(`./account-store-
|
|
3466
|
+
`}function Zse(){return V(`oauth-token`,Qse)}async function Qse(e,t){let n=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r),r=await import(`./providers-CdbrXnHp.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Xse(),stderr:``,exitCode:0};if(e.includes(`--list`))return hce(n.getAccounts,r.getRegisteredProviderIds,r.getRegisteredProviderConfig,n.getOAuthAccountInfo);if(e.includes(`--expire`))return cce(e);if(e.includes(`--renew`))return lce(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return uce(e,t);let i=$se(e);if(!i.ok)return i.result;let a=ece(e),o=tce(e,n,r);if(!o.ok)return o.result;let s=nce(o.value,r.getRegisteredProviderConfig);if(!s.ok)return s.result;if(!a){let e=await rce(o.value,s.value,n.getOAuthAccountInfo,i.value);if(e)return e}return ice(o.value,s.value,i.value,n.getOAuthAccountInfo)}function $se(e){let t=e.indexOf(`--scope`);if(t<0)return{ok:!0,value:void 0};let n=e[t+1]?.trim();return!n||n.startsWith(`-`)?{ok:!1,result:T8(`oauth-token: --scope requires a value`)}:(e.splice(t,2),{ok:!0,value:n})}function ece(e){let t=e.indexOf(`--force-login`);return t<0?!1:(e.splice(t,1),!0)}function tce(e,t,n){let r=e.indexOf(`--provider`);if(r>=0){let t=e[r+1];return t?{ok:!0,value:t}:{ok:!1,result:T8(`oauth-token: --provider requires a value`)}}if(e.length>0)return{ok:!0,value:e[0]};let i=t.getSelectedProvider();if(y8(n.getRegisteredProviderConfig(i)))return{ok:!0,value:i};let a=n.getRegisteredProviderIds().find(e=>y8(n.getRegisteredProviderConfig(e)));return a?{ok:!0,value:a}:{ok:!1,result:T8(`oauth-token: no OAuth providers configured`)}}function y8(e){return!!(e?.isOAuth&&(e.onOAuthLogin||e.onOAuthLoginIntercepted))}function nce(e,t){let n=t(e);return n?y8(n)?{ok:!0,value:n}:{ok:!1,result:T8(`oauth-token: provider "${e}" is not an OAuth provider`)}:{ok:!1,result:T8(`oauth-token: unknown provider "${e}"`)}}async function rce(e,t,n,r){let i=n(e);return i&&!i.expired?b8(e,i,r):!i?.expired||!t.onSilentRenew||!await sce(t.onSilentRenew)?null:b8(e,n(e),r)}function b8(e,t,n){return n&&!Yse(t?.scopes,n)?null:x8(e,t?.maskedValue)}function x8(e,t){return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:T8(`oauth-token: no masked value for ${e} (try logging in again)`)}async function ice(e,t,n,r){try{let i=await ace(e,t,n);return i.error?i.error:oce(e,r,i.succeeded)}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof Error&&t.name===`OAuthLaunchError`?(console.error(`[oauth-token] Provider ${e}: login could not be shown:`,n),T8(`oauth-token: ${n}`)):(console.error(`[oauth-token] Provider ${e}: login failed:`,n),T8(`oauth-token: login failed: ${n}`))}}async function ace(e,t,n){let r=n?{scopes:n}:void 0,i=!1,a=()=>{i=!0};if(t.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:n}=await import(`./oauth-service-CTntqv0R.js`),o=await n();return o?(await t.onOAuthLoginIntercepted(o,a,r),{error:null,succeeded:i}):{error:T8(`oauth-token: provider "${e}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.`),succeeded:!1}}if(t.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-CTntqv0R.js`);return await t.onOAuthLogin(e(),a,r),{error:null,succeeded:i}}return{error:T8(`oauth-token: provider "${e}" has no OAuth login hook`),succeeded:!1}}function oce(e,t,n){if(!n)return console.error(`[oauth-token] Provider ${e}: interactive login was not completed`),T8(`oauth-token: interactive login was not completed (cancelled, timed out, or no one could approve it)`);let r=t(e);return r?.token&&!r.expired?x8(e,r.maskedValue):r?.token?T8(`oauth-token: login completed but the saved token is already expired`):(console.error(`[oauth-token] Provider ${e}: login completed but no token was saved`),T8(`oauth-token: login completed but no token was saved`))}async function sce(e){try{return await e()!==null}catch{return!1}}function S8(e,t,n,r){let i=e.filter(e=>!e.startsWith(`-`))[0];if(i)return i;let a=t();return n(a)?.onSilentRenew?a:r().find(e=>n(e)?.onSilentRenew)}async function cce(e){let{getAccounts:t,getSelectedProvider:n,saveOAuthAccount:r}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r),{getRegisteredProviderConfig:i,getRegisteredProviderIds:a}=await import(`./providers-CdbrXnHp.js`).then(e=>e.r),o=S8(e,n,i,a);if(!o)return T8(`oauth-token --expire: no provider supports silent renewal`);let s=i(o);if(!s)return T8(`oauth-token --expire: unknown provider "${o}"`);if(!s.onSilentRenew)return T8(`oauth-token --expire: provider "${o}" has no onSilentRenew hook`);let c=t().find(e=>e.providerId===o);if(!c?.accessToken)return T8(`oauth-token --expire: no stored OAuth account for "${o}"`);try{await r({...c,accessToken:c.accessToken,tokenExpiresAt:Date.now()-1e3})}catch(e){return T8(`oauth-token --expire: failed to update "${o}": ${e instanceof Error?e.message:String(e)}`)}return{stdout:`oauth-token ${o}: stored token marked expired; next network op will trigger silent renewal.\n`,stderr:``,exitCode:0}}async function lce(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./account-store-WnXgLTc8.js`).then(e=>e.r),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-CdbrXnHp.js`).then(e=>e.r),a=S8(e,t,r,i);if(!a)return T8(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return T8(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return T8(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${C8(s)}`);let u=null,d=null;try{u=await o.onSilentRenew()}catch(e){d=e instanceof Error?e.message:String(e)}if(d)l.push(` silent renewal: ERROR — ${d}`);else if(u){let e=n(a),t=!!(c&&e?.token&&c!==e.token);l.push(` silent renewal: SUCCESS${t?` — token refreshed`:` (token unchanged)`}`),l.push(` after: ${C8(e)}`)}else l.push(` silent renewal: FAILED (onSilentRenew returned null)`),l.push(` → no window should have appeared. Open DevTools console and`),l.push(` look for "[oauth-service] Extension OAuth error" / "[adobe]" to see`),l.push(` the IMS/Chrome reason (e.g. login_required).`);return{stdout:l.join(`
|
|
3467
3467
|
`)+`
|
|
3468
3468
|
`,stderr:``,exitCode:+!u}}function C8(e){if(!e)return`no token`;if(e.expired)return`expired`;if(e.expiresAt){let t=e.expiresAt-Date.now();if(t>0){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4);return e>0?`valid, expires in ${e}h ${n}m`:`valid, expires in ${n}m`}}return`valid`}async function uce(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-BIKnTjZm.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-CTntqv0R.js`),i=await dce(e,t);if(!i.ok)return i.result;let a=n(i.value);if(!a.ok)return T8(`oauth-token: invalid intercept config: ${a.error}`);let o=await r();if(!o)return T8(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let s=await o(a.config);return s?{stdout:`${s}\n`,stderr:``,exitCode:0}:T8(`oauth-token: intercept timed out or was cancelled`)}function dce(e,t){let n=e.indexOf(`--from-file`);return n>=0?fce(e[n+1],t):pce(e)}async function fce(e,t){if(!e)return{ok:!1,result:T8(`oauth-token: --from-file requires a path`)};try{let n=t.fs.resolvePath(t.cwd,e),r=await t.fs.readFile(n),i=typeof r==`string`?r:new TextDecoder().decode(r);return{ok:!0,value:JSON.parse(i)}}catch(t){return{ok:!1,result:T8(`oauth-token: failed to read ${e}: ${t instanceof Error?t.message:String(t)}`)}}}function pce(e){let t=w8(e,`--authorize-url`),n=w8(e,`--redirect-pattern`);if(!t)return{ok:!1,result:T8(`oauth-token: --authorize-url is required`)};if(!n)return{ok:!1,result:T8(`oauth-token: --redirect-pattern is required`)};let r=mce(e);return r.ok?{ok:!0,value:{authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.value.length>0?{rewrite:r.value}:{}}}:r}function mce(e){let t=[];for(let n=0;n<e.length;n++){if(e[n]!==`--rewrite`)continue;let r=e[n+1];if(!r)return{ok:!1,result:T8(`oauth-token: --rewrite requires a value`)};let i=r.split(`=`);if(i.length<3)return{ok:!1,result:T8(`oauth-token: --rewrite "${r}" must be "<match>=<key>=<value>"`)};let[a,o,...s]=i;t.push({match:a,appendParams:{[o]:s.join(`=`)}})}return{ok:!0,value:t}}function w8(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function T8(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function hce(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
3469
3469
|
`,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}t.scopes&&n.push(`scopes: ${t.scopes}`),a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
@@ -3581,7 +3581,7 @@ Examples:
|
|
|
3581
3581
|
plugin list
|
|
3582
3582
|
plugin info my-plugin
|
|
3583
3583
|
plugin remove my-plugin
|
|
3584
|
-
`}function qce(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(Kce());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Yce(i,a,e);case`list`:case`ls`:return await $ce(i,e);case`info`:return await ele(i,e);case`validate`:return await tle(i,a,e);case`remove`:case`rm`:case`delete`:return await nle(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-
|
|
3584
|
+
`}function qce(e={}){return V(`plugin`,async(t,n)=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return V8(Kce());let r=t[0],i=t.slice(1),a=n?.cwd??`/`;try{switch(r){case`install`:case`add`:return await Yce(i,a,e);case`list`:case`ls`:return await $ce(i,e);case`info`:return await ele(i,e);case`validate`:return await tle(i,a,e);case`remove`:case`rm`:case`delete`:return await nle(i,e);default:return H8(`plugin: unknown subcommand "${r}" (try \`plugin --help\`)`)}}catch(e){return H8(`plugin ${r}: ${e instanceof Error?e.message:String(e)}`)}})}async function U8(e){if(e.fs)return e.fs;let{VirtualFS:t}=await import(`./fs-Dnva5HZ3.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DJXlpNui.js`).then(e=>e.n);return t.create({dbName:n})}async function W8(e,t,n){let r=rle(t,e);if(await n.exists(r))return{kind:`local`,root:r};let{parseGitHubRef:i}=await import(`./github-install-DpekDVQj.js`).then(e=>e.t),a=i(e);if(a){let e=`${a.owner}/${a.repo}${a.branch?`@${a.branch}`:``}${a.path?`/${a.path}`:``}`;return{kind:`github`,ref:{...a,display:e}}}return{kind:`error`,message:`${r} does not exist and "${e}" is not a GitHub reference (owner/repo[@branch] or https://github.com/owner/repo[/tree/branch[/dir]])`}}function Jce(e){let t=e.replace(/[^A-Za-z0-9._-]+/g,`-`);return/^\.+$/.test(t)?t.replace(/\./g,`_`):t}function G8(e){let t=[e.owner,e.repo,...e.path?[e.path]:[]];return`${B8}/${t.map(Jce).join(`--`)}`}async function K8(e,t,n,r){let{fetchRepoZip:i,stripZipPrefix:a,writeZipFilesToDir:o}=await import(`./github-zip-0POubY9i.js`).then(e=>e.i),s=await i(e.owner,e.repo,r,e.branch);if(s.status===`error`)return`failed to download ${e.display}: ${s.message}`;let c=a(s.files),l=e.path?e.path.replace(/^\/|\/$/g,``)+`/`:``;if(!c[`${l}plugin.json`])return`no plugin.json found at ${e.display} — not an Agent Plugins package`;try{await n.rm(t,{recursive:!0})}catch{}return await n.mkdir(t,{recursive:!0}),(await o(c,l,t,n,!1)).length===0?`no files found at ${e.display}`:null}async function q8(e,t){try{await e.rm(t,{recursive:!0})}catch{}}async function Yce(e,t,n){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin install <path|repo>
|
|
3585
3585
|
|
|
3586
3586
|
Loads the Agent Plugins package at <path>, or downloads it from a GitHub
|
|
3587
3587
|
reference (owner/repo, owner/repo@branch, or
|
|
@@ -3592,19 +3592,19 @@ mcp.json. On success the plugin is recorded in
|
|
|
3592
3592
|
/workspace/.plugins/plugins.json — its skills then surface through the
|
|
3593
3593
|
standard skills discovery, and each supported streamable-http MCP server
|
|
3594
3594
|
is registered in the MCP store as "<plugin>:<server>".
|
|
3595
|
-
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-B23_5sFw.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-
|
|
3595
|
+
`);let r=e.filter(e=>!e.startsWith(`--`));if(r.length<1)return H8(`plugin install: expected <path|repo>`);let i=await U8(n),a=await W8(r[0],t,i);if(a.kind===`error`)return H8(`plugin install: ${a.message}`);let o,s;if(a.kind===`github`){if(!n.fetch)return H8(`plugin install: GitHub installs are unavailable (no network fetch configured)`);o=G8(a.ref),s=a.ref.display;let e=await K8(a.ref,o,i,n.fetch);if(e)return H8(`plugin install: ${e}`)}else o=a.root;let{loadPluginFromDirectory:c}=await import(`./loader-B23_5sFw.js`),l=await c(i,o);if(!l.ok)return a.kind===`github`&&await q8(i,o),H8(`plugin install: plugin at ${s??o} was rejected:\n${J8(l.diagnostics)}`);let{plugin:u}=l,d=u.manifest.name,{getInstalledPlugin:f,setInstalledPlugin:p}=await import(`./store-DGOhX8_w.js`),m=await f(d,n.fs);if(m&&m.root!==o)return a.kind===`github`&&await q8(i,o),H8(`plugin install: a plugin named "${d}" is already installed from ${m.root} (remove it first)`);let h=await Qce(u,n),g=await Zce(d,m?.mcpServerNames,h.registered,n);return await p(d,{root:o,version:u.manifest.version,description:u.manifest.description,installedAt:new Date().toISOString(),mcpServerNames:h.registered,...s?{source:s}:{}},n.fs),V8(Xce(u,h,g,s??o,l.diagnostics))}function Xce(e,t,n,r,i){let a=e.manifest.name,o=t.registered,s=e.mcp.servers.filter(e=>e.status!==`supported`),c=[`Installed agent plugin "${a}"${e.manifest.version?` v${e.manifest.version}`:``} from ${r}`,` skills: ${e.skills.length}${e.skills.length>0?` (${e.skills.map(e=>e.name).join(`, `)})`:``}`,` mcp: ${o.length} registered${o.length>0?` (${o.join(`, `)})`:``}${s.length>0?`, ${s.length} skipped`:``}${n>0?`, ${n} removed from previous install`:``}`];return t.conflicts.length>0&&c.push(` warning: not bridged — MCP server name(s) already in use and not owned by this plugin: ${t.conflicts.join(`, `)} (remove them with \`mcp remove\` first)`),i.length>0&&c.push(`Diagnostics:`,J8(i)),c.join(`
|
|
3596
3596
|
`)+`
|
|
3597
|
-
`}async function Zce(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-
|
|
3598
|
-
`);let{listInstalledPlugins:n}=await import(`./store-
|
|
3597
|
+
`}async function Zce(e,t,n,r){let i=(t??[]).filter(e=>!n.includes(e));if(i.length===0)return 0;let{deleteServer:a,getServer:o}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),s=0;for(let t of i)(await o(t,r.fs))?.pluginOrigin===e&&await a(t,r.fs)&&(s+=1);return s}async function Qce(e,t){let n=e.mcp.servers.filter(e=>e.status===`supported`);if(n.length===0)return{registered:[],conflicts:[]};let{getServer:r,setServer:i}=await import(`./store-_EfBoYjW.js`).then(e=>e.r),{McpClient:a}=await import(`./client-DVC0x03n.js`).then(e=>e.n),o=[],s=[];for(let c of n){let n=c.config,l=`${e.manifest.name}:${c.name}`,u=await r(l,t.fs);if(u&&u.pluginOrigin!==e.manifest.name){s.push(l);continue}let d=[];try{let e=new a({url:n.url,headers:n.headers});await e.initialize(),d=await e.toolsList()}catch{}await i(l,{url:n.url,...n.headers?{headers:n.headers}:{},tools:d,addedAt:new Date().toISOString(),pluginOrigin:e.manifest.name},t.fs),o.push(l)}return{registered:o,conflicts:s}}async function $ce(e,t){if(e.includes(`--help`)||e.includes(`-h`))return V8(`usage: plugin list
|
|
3598
|
+
`);let{listInstalledPlugins:n}=await import(`./store-DGOhX8_w.js`),r=await n(t.fs),i=Object.keys(r).sort();if(i.length===0)return V8("No agent plugins installed. Use `plugin install <path>`.\n");let a=[[`NAME`,`VERSION`,`ROOT`,`MCP`]];for(let e of i){let t=r[e];a.push([e,t.version??`-`,t.root,String(t.mcpServerNames?.length??0)])}let o=a[0].map((e,t)=>Math.max(...a.map(e=>e[t].length)));return V8(a.map(e=>e.map((e,t)=>e.padEnd(o[t])).join(` `)).join(`
|
|
3599
3599
|
`)+`
|
|
3600
3600
|
`)}async function ele(e,t){if(e.length===0||WZ(e))return e.length===0?H8(`plugin info: expected <name>`):V8(`usage: plugin info <name>
|
|
3601
|
-
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-
|
|
3601
|
+
`);let n=e[0],{getInstalledPlugin:r}=await import(`./store-DGOhX8_w.js`),i=await r(n,t.fs);if(!i)return H8(`plugin info: no installed plugin named "${n}"`);let a=await U8(t),{loadPluginFromDirectory:o}=await import(`./loader-B23_5sFw.js`),s=await o(a,i.root);if(!s.ok)return H8(`plugin info: plugin at ${i.root} no longer loads:\n${J8(s.diagnostics)}`);let{plugin:c}=s,l=c.manifest,u=[`${l.name}${l.version?` v${l.version}`:``}`,...l.description?[` ${l.description}`]:[],` root: ${c.root}`,...l.license?[` license: ${l.license}`]:[],...l.homepage?[` home: ${l.homepage}`]:[],``,`Skills (${c.skills.length}):`,...c.skills.map(e=>` ${e.name} ${e.description}`),``,`MCP servers (${c.mcp.servers.length}):`,...c.mcp.servers.map(e=>e.status===`supported`?` ${e.name} ${e.config.type} ${e.config.url}`:` ${e.name} [skipped: ${e.reason}]`)];return s.diagnostics.length>0&&u.push(``,`Diagnostics:`,J8(s.diagnostics)),V8(u.join(`
|
|
3602
3602
|
`)+`
|
|
3603
3603
|
`)}async function tle(e,t,n){if(e.length===0||WZ(e))return e.length===0?H8(`plugin validate: expected <path|repo>`):V8(`usage: plugin validate <path|repo>
|
|
3604
3604
|
`);let r=await U8(n),i=await W8(e[0],t,r);if(i.kind===`error`)return H8(`plugin validate: ${i.message}`);let a,o=null;if(i.kind===`github`){if(!n.fetch)return H8(`plugin validate: GitHub sources are unavailable (no network fetch configured)`);o=`/tmp/.plugin-validate/${G8(i.ref).split(`/`).pop()}`;let e=await K8(i.ref,o,r,n.fetch);if(e)return H8(`plugin validate: ${e}`);a=o}else a=i.root;let{loadPluginFromDirectory:s}=await import(`./loader-B23_5sFw.js`),c;try{c=await s(r,a)}finally{o&&await q8(r,o)}if(!c.ok)return{stdout:``,stderr:`plugin validate: REJECTED\n${J8(c.diagnostics)}\n`,exitCode:1};let{plugin:l}=c,u=l.mcp.servers.filter(e=>e.status===`supported`).length,d=[`plugin validate: OK — "${l.manifest.name}"${l.manifest.version?` v${l.manifest.version}`:``}`,` skills: ${l.skills.length}`,` mcp servers: ${u} supported, ${l.mcp.servers.length-u} skipped (mcp.json ${l.mcp.status})`];return c.diagnostics.length>0&&d.push(`Diagnostics:`,J8(c.diagnostics)),V8(d.join(`
|
|
3605
3605
|
`)+`
|
|
3606
3606
|
`)}async function nle(e,t){if(e.length===0||WZ(e))return e.length===0?H8(`plugin remove: expected <name>`):V8(`usage: plugin remove <name>
|
|
3607
|
-
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-
|
|
3607
|
+
`);let n=e[0],{getInstalledPlugin:r,deleteInstalledPlugin:i}=await import(`./store-DGOhX8_w.js`),a=await r(n,t.fs);if(!a)return H8(`plugin remove: no installed plugin named "${n}"`);let o=0;if(a.mcpServerNames&&a.mcpServerNames.length>0){let{deleteServer:e,getServer:r}=await import(`./store-_EfBoYjW.js`).then(e=>e.r);for(let i of a.mcpServerNames)(await r(i,t.fs))?.pluginOrigin===n&&await e(i,t.fs)&&(o+=1)}await i(n,t.fs);let s=a.root.startsWith(`${B8}/`);return s&&await q8(await U8(t),a.root),V8([`Removed agent plugin "${n}"`,` registry: removed`,` mcp servers: ${o} removed`,s?` files: removed (${a.root})`:` files: left in place (${a.root})`].join(`
|
|
3608
3608
|
`)+`
|
|
3609
3609
|
`)}function rle(e,t){let n=t.startsWith(`/`)?t:`${e.replace(/\/$/,``)}/${t}`,r=[];for(let e of n.split(`/`))e!==``&&e!==`.`&&(e===`..`?r.pop():r.push(e));return`/${r.join(`/`)}`}function J8(e){return e.map(e=>` ${e.level===`error`?`error`:`warn `} [${e.component}] ${e.message}`).join(`
|
|
3610
3610
|
`)}const Y8=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],ile=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],ale={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function ole(e={}){return V(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return vle();let n=e.processManager??sle();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
@@ -3755,7 +3755,7 @@ Examples:
|
|
|
3755
3755
|
secret peek OPENAI_KEY
|
|
3756
3756
|
secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
|
|
3757
3757
|
secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
|
|
3758
|
-
`}function _5(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]||e[t+1].startsWith(`-`)?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const uue={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},due=new Set;function v5(e,t){if(e===t)return!0;try{return
|
|
3758
|
+
`}function _5(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]||e[t+1].startsWith(`-`)?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const uue={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},due=new Set;function v5(e,t){if(e===t)return!0;try{return Aee(e).test(t)}catch{return!1}}function fue(e,t){for(let n of e)if(v5(n,t))return!0;return!1}function y5(e){return{stdout:``,stderr:`${Zn(`secret`,e)}\n`,exitCode:1}}function pue(e){let t=Xe(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??cue(t),i=e.grants??due,a=e.broker,o=()=>(a??=N_(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(fue(i,n))return`ok`;let r=await o().requestApproval({kind:`secret`,detail:`${uue[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return r;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&v5(e,n)?e:n)}return`ok`},injectMaskedEnv:async t=>{if(e.setEnv&&wx(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function mue(e){let t=hG(e);if(t.length!==0)return t.endsWith(`\r
|
|
3759
3759
|
`)?t.slice(0,-2):t.endsWith(`
|
|
3760
3760
|
`)?t.slice(0,-1):t}async function hue(e,t,n,r){let i=await r.gate(`persist`,e);return i===`ok`?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):y5(i)}async function gue(e,t,n,r){if(await r.backend.getInfo(e)){let t=await r.gate(`value`,e);if(t!==`ok`)return y5(t)}return await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}" (domains: ${n.join(`, `)}) — in-memory only, not persisted.\n`,stderr:``,exitCode:0}}async function _ue(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
|
|
3761
3761
|
`,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=mue(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
|
|
@@ -3874,7 +3874,7 @@ Examples:
|
|
|
3874
3874
|
Start one with: slicc <join-url> follow sh -c
|
|
3875
3875
|
`;let n=[`exec targets:`];for(let e of t){let t=[e.runtimeId];e.runtime&&t.push(`(${e.runtime})`),n.push(` - ${t.join(` `)}`),e.motd&&n.push(` ${e.motd}`)}return`${n.join(`
|
|
3876
3876
|
`)}\n`}function Ede(e){if(e.stdin===void 0)return;let t=gG(e.stdin);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 d(n)}function Dde(e){let t=!1,n,r,i=0;for(;i<e.length;){let a=e[i];if(a===`--help`||a===`-h`)return{help:!0};if(a===`--list`||a===`-l`){t=!0,i+=1;continue}if(a===`--cwd`){let t=e[i+1];if(t===void 0)return{error:`ssh: --cwd requires a directory argument`};n=t,i+=2;continue}if(a===`--timeout`){let t=e[i+1],n=Number(t);if(t===void 0||!Number.isFinite(n)||n<=0)return{error:`ssh: --timeout requires a positive number of seconds`};r=n,i+=2;continue}if(a.startsWith(`-`)&&a!==`-`)return{error:`ssh: unknown flag: ${a}`};break}let a=e[i],o=e.slice(i+1).join(` `);return{list:t,cwd:n,timeoutSec:r,runtimeId:a,command:o}}function Ode(){return V(`ssh`,async(e,t)=>{let n=Dde(e);if(`help`in n)return wde();if(`error`in n)return N5(n.error);if(n.list||n.runtimeId===void 0)return{stdout:Tde(xY()),stderr:``,exitCode:0};if(!n.command)return N5(`ssh: missing command
|
|
3877
|
-
Usage: ssh <runtime-id> <command...>`);let r=i();if(!r)return N5(`ssh: not available in this environment (needs the standalone app)`);let a=`ssh-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=()=>{r.call(`tray-exec-signal`,{execToken:a}).catch(()=>{})};t.signal?.addEventListener(`abort`,o,{once:!0});try{let e=n.timeoutSec?n.timeoutSec*1e3:void 0,i=await r.call(`tray-exec`,{runtimeId:n.runtimeId,command:n.command,cwd:n.cwd,execToken:a,timeoutMs:e,stdin:Ede(t)},{timeoutMs:(e??864e5)+5e3});return i.error?{stdout:i.stdout,stderr:`${i.stderr}ssh: ${i.error}\n`,exitCode:i.exitCode||1}:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}catch(e){return N5(`ssh: ${e instanceof Error?e.message:String(e)}`)}finally{t.signal?.removeEventListener(`abort`,o)}})}function kde(e){return{stdout:``,stderr:`${
|
|
3877
|
+
Usage: ssh <runtime-id> <command...>`);let r=i();if(!r)return N5(`ssh: not available in this environment (needs the standalone app)`);let a=`ssh-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,o=()=>{r.call(`tray-exec-signal`,{execToken:a}).catch(()=>{})};t.signal?.addEventListener(`abort`,o,{once:!0});try{let e=n.timeoutSec?n.timeoutSec*1e3:void 0,i=await r.call(`tray-exec`,{runtimeId:n.runtimeId,command:n.command,cwd:n.cwd,execToken:a,timeoutMs:e,stdin:Ede(t)},{timeoutMs:(e??864e5)+5e3});return i.error?{stdout:i.stdout,stderr:`${i.stderr}ssh: ${i.error}\n`,exitCode:i.exitCode||1}:{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}catch(e){return N5(`ssh: ${e instanceof Error?e.message:String(e)}`)}finally{t.signal?.removeEventListener(`abort`,o)}})}function kde(e){return{stdout:``,stderr:`${Zn(`sudo`,e)}\n`,exitCode:1}}function Ade(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return V(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
|
|
3878
3878
|
`,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
|
|
3879
3879
|
|
|
3880
3880
|
Request human approval to run <command> with elevation. If approved, the
|
|
@@ -4821,13 +4821,13 @@ Subcommands:
|
|
|
4821
4821
|
`,exitCode:1}}catch{return{stdout:``,stderr:`theme apply: file is not valid JSON
|
|
4822
4822
|
`,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:c,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function Afe(e,t){if(e.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
|
|
4823
4823
|
`,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}}const J5=`unknown`,Y5=`usage: uname [-amnorsv]`,X5=[`s`,`n`,`r`,`v`,`m`,`o`];function jfe(){return{stdout:[Y5,` -s kernel name (SLICC) -n nodename (leader/follower/standalone)`,` -r release (SLICC version) -v build stamp`,` -m machine (realm platform) -o operating system (user agent)`,` -a all of the above, in uname order`,``].join(`
|
|
4824
|
-
`),stderr:``,exitCode:0}}function Mfe(){let{releasedAt:e,buildId:t}=
|
|
4824
|
+
`),stderr:``,exitCode:0}}function Mfe(){let{releasedAt:e,buildId:t}=Rn();return e?`${t} (${e})`:t}function Nfe(){let e=globalThis.navigator,t=e?.userAgentData?.platform||e?.platform;return typeof t==`string`&&t.length>0?t:J5}function Pfe(){let e=globalThis.navigator?.userAgent;return typeof e==`string`&&e.length>0?e:J5}function Ffe(e){switch(e){case`s`:return`SLICC`;case`n`:return _ee();case`r`:return Rn().version;case`v`:return Mfe();case`m`:return Nfe();case`o`:return Pfe()}}function Ife(e){return{stdout:``,stderr:`uname: ${e}\n${Y5}\n`,exitCode:1}}function Lfe(e){let t=new Set;for(let n of e){if(!n.startsWith(`-`)||n===`-`)return{error:`extra operand '${n}'`};if(n.startsWith(`--`))return{error:`unrecognized option '${n}'`};for(let e of n.slice(1)){if(e===`a`){for(let e of X5)t.add(e);continue}if(!X5.includes(e))return{error:`unrecognized option '-${e}'`};t.add(e)}}return t}function Rfe(){return V(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return jfe();let t=Lfe(e);return`error`in t?Ife(t.error):{stdout:`${(t.size>0?X5.filter(e=>t.has(e)):[`s`]).map(Ffe).join(` `)}\n`,stderr:``,exitCode:0}})}function zfe(){return V(`unlink`,async(e,t)=>{if(e.includes(`--help`))return{stdout:`Usage: unlink FILE
|
|
4825
4825
|
Remove FILE. Symbolic links are removed without following their target.
|
|
4826
4826
|
`,stderr:``,exitCode:0};if(e.length!==1||e[0].startsWith(`-`))return{stdout:``,stderr:e.length===0?`unlink: missing operand
|
|
4827
4827
|
`:`unlink: extra operand
|
|
4828
4828
|
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e[0]);try{let r=t.fs.lstat?await t.fs.lstat(n):await t.fs.stat(n);return r.isDirectory&&!r.isSymbolicLink?{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': Is a directory\n`,exitCode:1}:(await t.fs.rm(n,{recursive:!1,force:!1}),{stdout:``,stderr:``,exitCode:0})}catch(t){let n=t instanceof Error?t.message:String(t);return{stdout:``,stderr:`unlink: cannot unlink '${e[0]}': ${n}\n`,exitCode:1}}})}function Bfe(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
4829
4829
|
`,stderr:``,exitCode:0}}function Vfe(e){let t=`.`,n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`-d`){t=e[r+1]??``,r++;continue}if(i.startsWith(`-`))return{kind:`error`,result:{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1}};n.push(i)}return n.length<1?{kind:`error`,result:{stdout:``,stderr:`unzip: expected archive path
|
|
4830
|
-
`,exitCode:1}}:{kind:`ok`,archive:n[0],destination:t||`.`}}async function Hfe(e,t,n,r){let i=n.replace(/\\/g,`/`);if(!i||i.endsWith(`/`))return!1;let a=e.fs.resolvePath(t,i);if(!Fr(t,a))return{stdout:``,stderr:`unzip: blocked suspicious path ${n}\n`,exitCode:1};let o=Cr(a);return o!==`/`&&await e.fs.mkdir(o,{recursive:!0}),await e.fs.writeFile(a,r),!0}function Ufe(){return V(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Bfe();let n=Vfe(e);if(n.kind===`error`)return n.result;let r=t.fs.resolvePath(t.cwd,n.archive),i=t.fs.resolvePath(t.cwd,n.destination);await t.fs.mkdir(i,{recursive:!0});let a=await t.fs.readFileBuffer(r),o=
|
|
4830
|
+
`,exitCode:1}}:{kind:`ok`,archive:n[0],destination:t||`.`}}async function Hfe(e,t,n,r){let i=n.replace(/\\/g,`/`);if(!i||i.endsWith(`/`))return!1;let a=e.fs.resolvePath(t,i);if(!Fr(t,a))return{stdout:``,stderr:`unzip: blocked suspicious path ${n}\n`,exitCode:1};let o=Cr(a);return o!==`/`&&await e.fs.mkdir(o,{recursive:!0}),await e.fs.writeFile(a,r),!0}function Ufe(){return V(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Bfe();let n=Vfe(e);if(n.kind===`error`)return n.result;let r=t.fs.resolvePath(t.cwd,n.archive),i=t.fs.resolvePath(t.cwd,n.destination);await t.fs.mkdir(i,{recursive:!0});let a=await t.fs.readFileBuffer(r),o=Gee(a),s=0;for(let[e,n]of Object.entries(o)){let r=await Hfe(t,i,e,n);if(r===!0)s++;else if(r!==!1)return r}return{stdout:`extracted ${s} file(s) to ${i}\n`,stderr:``,exitCode:0}})}const Z5=`ai-ecoverse/slicc`,Q5=`usage: upgrade status | upgrade apply --from=<version> --to=<version>`,$5=`packages/vfs-root`,e7=3e4,Wfe=[`${$5}/workspace/skills/`,`${$5}/shared/sprinkles/`,`${$5}/shared/sounds/`,`${$5}/shared/MEMORY.md`,`${$5}/etc/`],Gfe=[`auto-applied`,`merged-clean`,`kept-local`,`needs-review`,`unchanged`,`added-new`];function Kfe(){return Object.fromEntries(Gfe.map(e=>[e,0]))}function t7(e,t,n,r){let i=Kfe();for(let e of n)i[e.classification]+=1;return`${JSON.stringify({ok:r.length===0&&i[`needs-review`]===0,from:e,to:t,results:n.map(({path:e,classification:t,sidecar:n})=>({path:e,status:t,...n?{sidecar:n}:{}})),summary:i,errors:r})}\n`}function qfe(e){if(e[0]!==`apply`)throw Error(Q5);let t=new Map;for(let n of e.slice(1)){let e=n.match(/^--(from|to)=(.+)$/);if(!e)throw Error(`unsupported argument: ${n}`);t.set(e[1],e[2])}let n=t.get(`from`)??``,r=t.get(`to`)??``,i=/^v?[0-9][0-9A-Za-z.+_-]*$/;if(!i.test(n)||!i.test(r))throw Error(`both --from and --to must be release versions`);return{from:n,to:r}}function n7(e){return e.startsWith(`v`)?e:`v${e}`}function Jfe(e){if(!Wfe.some(t=>e.startsWith(t)))return null;let t=e.slice(17);return!t||t.split(`/`).some(e=>e===`.`||e===`..`)?null:t}async function r7(e,t){let n,r;try{n=await Promise.race([e(t,{method:`GET`,headers:{Accept:`application/json`}}),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`request timed out after ${e7}ms`)),e7)})])}catch(e){let n=e instanceof Error?e.message:String(e);throw Error(`fetch failed for ${t}: ${n}`)}finally{r!==void 0&&clearTimeout(r)}if(n.status<200||n.status>=300)throw Error(`fetch failed for ${t}: HTTP ${n.status} ${n.statusText}`);return n}async function i7(e,t){let n=await r7(t,`https://api.github.com/repos/${Z5}/git/trees/${encodeURIComponent(e)}?recursive=1`),r=Ot(n.body);if(r.truncated)throw Error(`bundled file discovery was truncated for ${e}`);if(!Array.isArray(r.tree))throw Error(`invalid bundled file discovery response for ${e}`);let i=new Map;for(let e of r.tree){if(e.type!==`blob`||typeof e.path!=`string`)continue;let t=Jfe(e.path);t&&i.set(t,e.path)}return i}function a7(e,t){let n=t.split(`/`).map(encodeURIComponent).join(`/`);return`https://raw.githubusercontent.com/${Z5}/${encodeURIComponent(e)}/${n}`}function o7(e,t){return!e||!t||e.byteLength!==t.byteLength?!1:e.every((e,n)=>e===t[n])}function Yfe(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}async function s7(e,t){if(!await e.exists(t))return;let n=await e.readFile(t,{encoding:`binary`});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}async function c7(e,t,n,r,i){let a=`${t}.upgrade-${n7(n)}-to-${n7(r)}.conflict`;if(!i.has(a)&&!await e.exists(a))return i.add(a),a;for(let t=1;;t+=1){let n=`${a}.${t}`;if(!i.has(n)&&!await e.exists(n))return i.add(n),n}}async function Xfe(e,t,n,r,i,a,o){let s=await s7(e.fs,t);if(!a)return{path:t,classification:s?`kept-local`:`unchanged`};if(!i)return s?{path:t,classification:o7(s,a)?`unchanged`:`kept-local`}:{path:t,classification:`added-new`,content:a};if(o7(i,a)||o7(s,a))return{path:t,classification:`unchanged`};if(!s)return{path:t,classification:`kept-local`};if(o7(s,i))return{path:t,classification:`auto-applied`,content:a};let[c,l,u]=[s,i,a].map(Yfe);if(c!==null&&l!==null&&u!==null){let i=VO(c,l,u,{diff3:!0,labels:{current:`local:${t}`,base:`${n7(n)}:${t}`,other:`${n7(r)}:${t}`}}),a=new TextEncoder().encode(i.content);return i.conflicts===0?{path:t,classification:`merged-clean`,content:a}:{path:t,classification:`needs-review`,content:a,sidecar:await c7(e.fs,t,n,r,o)}}return{path:t,classification:`needs-review`,content:a,sidecar:await c7(e.fs,t,n,r,o)}}async function Zfe(e,t){t.content?await e.writeFile(t.path,t.content):await e.exists(t.path)&&await e.rm(t.path)}async function Qfe(e,t){let n=t.filter(e=>e.content!==void 0),r=await Promise.all(n.map(async t=>{let n=t.sidecar??t.path;return{path:n,content:await s7(e,n)}})),i=[];for(let t=0;t<n.length;t+=1){let a=n[t],o=r[t];try{await e.writeFile(o.path,a.content),i.push(o)}catch(t){let n=[];for(let t of[o,...i.slice().reverse()])try{await Zfe(e,t)}catch(e){n.push(`${t.path}: ${e instanceof Error?e.message:String(e)}`)}let r=t instanceof Error?t.message:String(t),a=n.length===0?`all writes rolled back`:`rollback failed (${n.join(`; `)})`;throw Error(`apply failed for ${o.path}: ${r}; ${a}`)}}}async function $fe(e,t,n){let r=n7(t),i=n7(n),[a,o]=await Promise.all([i7(r,e.fetch),i7(i,e.fetch)]),s=[...new Set([...a.keys(),...o.keys()])].sort(),c=await Promise.all(s.map(async t=>{let[n,s]=await Promise.all([a.has(t)?r7(e.fetch,a7(r,a.get(t))).then(e=>Dt(e.body)):void 0,o.has(t)?r7(e.fetch,a7(i,o.get(t))).then(e=>Dt(e.body)):void 0]);return{path:t,base:n,theirs:s}})),l=new Set(s),u=[];for(let{path:r,base:i,theirs:a}of c)u.push(await Xfe(e,r,t,n,i,a,l));return await Qfe(e.fs,u),u}async function epe(e){let{version:t,releasedAt:n,buildId:r}=Rn(),i=[],a=null,o=e.getLastSeen??Bn();if(!o)i.push(`last-seen version unavailable: no reader registered in this runtime`);else try{a=await o()}catch(e){i.push(`last-seen version unavailable: ${e instanceof Error?e.message:String(e)}`)}let s=a!==null&&a!==t;return`${JSON.stringify({ok:i.length===0,version:t,releasedAt:n,build:r,lastSeen:a,mergePending:s,...s?{apply:`upgrade apply --from=${a} --to=${t}`}:{},errors:i})}\n`}function tpe(e){return V(`upgrade`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`${Q5}\n`,stderr:``,exitCode:0};if(t[0]===`status`)return t.length>1?{stdout:t7(``,``,[],[`unsupported argument: ${t[1]}`]),stderr:``,exitCode:1}:{stdout:await epe(e),stderr:``,exitCode:0};let n=``,r=``;try{({from:n,to:r}=qfe(t));let i=await $fe(e,n,r),a=i.some(e=>e.classification===`needs-review`);return{stdout:t7(n,r,i,[]),stderr:``,exitCode:+!!a}}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:t7(n,r,[],[t]),stderr:``,exitCode:1}}})}const npe=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function rpe(e){return dO(e,npe)}function l7(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 ipe(e){let t={};return e.has(`--vid`)&&(t.vendorId=l7(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=l7(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=l7(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=l7(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=l7(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const ape=new Set([`standard`,`class`,`vendor`]),ope=new Set([`device`,`interface`,`endpoint`,`other`]);function u7(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!ape.has(t))throw Error(`invalid --request-type: '${t}'`);if(!ope.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:l7(e.get(`--request`)??`0`,`request`),value:l7(e.get(`--value`)??`0`,`value`),index:l7(e.get(`--index`)??`0`,`index`)}}function d7(e){let t=gG(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function spe(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function f7(e){return`0x${e.toString(16).padStart(4,`0`)}`}function p7(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${f7(e.vendorId)}:${f7(e.productId)}\t${t}${n}${r}`}function m7(e){return{stdout:e,stderr:``,exitCode:0}}function h7(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const cpe=`usb - access USB devices via WebUSB
|
|
4831
4831
|
|
|
4832
4832
|
Usage: usb <subcommand> [options]
|
|
4833
4833
|
|
|
@@ -4968,7 +4968,7 @@ Examples:
|
|
|
4968
4968
|
webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
|
|
4969
4969
|
webhook list
|
|
4970
4970
|
webhook delete abc123
|
|
4971
|
-
`,stderr:``,exitCode:0}}function U7(e){return e().session?.webhookUrl??null}function W7(e,t,n){return t?
|
|
4971
|
+
`,stderr:``,exitCode:0}}function U7(e){return e().session?.webhookUrl??null}function W7(e,t,n){return t?dn(t,e):n()?pn(self.location.href,e):`(URL unavailable — connect a leader tray)`}function G7(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function Xpe(e,t,n){let r=`default`,i,a,o=e.indexOf(`--name`);o!==-1&&e[o+1]&&(r=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(i=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(a=e[c+1]),a=tZ(a,n),!a)return{stdout:``,stderr:`webhook create: --scoop is required (name a scoop or a cone; an extra cone's shell supplies its own)
|
|
4972
4972
|
`,exitCode:1};if(!t.hasLocalNodeServer()&&i)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
|
|
4973
4973
|
`,exitCode:1};let l=$pe(t);if(l)return l;let u=await aZ();if(!u)return G7(`create`);let d=await u.createWebhook(r,a,i),f=eme(d.id,t),p=`Created webhook "${d.name}"\nID: ${d.id}\nURL: ${f}\n`;return d.scoop&&(p+=`Scoop: ${d.scoop}\n`),d.filter&&(p+=`Filter: ${d.filter}\n`),{stdout:p,stderr:``,exitCode:0}}async function Zpe(e){let t=await aZ();if(!t)return G7(`list`);let n=await t.listWebhooks();if(n.length===0)return{stdout:`No active webhooks
|
|
4974
4974
|
`,stderr:``,exitCode:0};let{trayUrlBase:r,urlResolutionError:i}=tme(e);return{stdout:nme(n.map(t=>({id:t.id,name:t.name,url:W7(t.id,r,e.hasLocalNodeServer),createdAt:t.createdAt,filter:t.filter,scoop:t.scoop})),r,i,e.hasLocalNodeServer),stderr:``,exitCode:0}}async function Qpe(e){let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
|
|
@@ -5209,8 +5209,8 @@ pass --wait to block and print the full result.
|
|
|
5209
5209
|
`,stderr:``,exitCode:0};let n;try{n=Hme(e)}catch(e){return t9(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await Wme(t,r,a)}catch{return t9(`${r}: No such file or directory`)}if(n.revert){let e=r9(o),r=n.plain?Rme(e):zme(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:r9(r),stderr:``,exitCode:0}}let{data:s,base:c}=Kme(n,o),l=Gme(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 i9(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=Nr(t,o),s=n?`${n}/${o}`:o;a+=await i9(e,i,s,r)}return a}function Jme(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
|
|
5210
5210
|
`,stderr:``,exitCode:0}}function Yme(){return V(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Jme();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
|
|
5211
5211
|
`,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(/^\.\//,``))||Lr(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await i9(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
|
|
5212
|
-
`,exitCode:1};let c=Gee(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function Xme(e={}){let t=[dae({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),AY(),Ode(),Xue(e.browserAPI,e.fs),Mce(e.browserAPI),Pae(e),Yme(),Ufe(),Qde(),Mde(),zde(),Ide(),tX(),qme(),M5(`sqlite3`),M5(`sqllite`),lfe(),wfe(),g$(),hY(),zse({buildProcessConfig:e.buildProcessConfig}),X8(`python3`,{buildProcessConfig:e.buildProcessConfig}),X8(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[S6(`ipk`,{fs:e.fs,fetch:e.fetch}),S6(`npm`,{fs:e.fs,fetch:e.fetch}),S6(`i`,{fs:e.fs,fetch:e.fetch}),U6(`ipx`,{fs:e.fs,fetch:e.fetch}),U6(`npx`,{fs:e.fs,fetch:e.fetch}),eQ(`di`,{fs:e.fs,fetch:e.fetch}),eQ(`uv`,{fs:e.fs,fetch:e.fetch}),tpe({fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[gae({fetch:e.fetch})]:[],i0(),rme(e.webhook),ume(),pZ(),Yoe({fs:e.fs,scriptCatalog:e.scriptCatalog}),qce({fs:e.fs,fetch:e.fetch}),D0(),gde(),L8(`pdftk`),L8(`pdf`),z8(`pdftoppm`),z8(`pdftocairo`),eZ(`convert`),eZ(`magick`),hme({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins,getScriptRegisteredNames:e.getScriptRegisteredNames}),Tfe(),Rfe(),zfe(),qoe(),HQ(),Zse(),Wse(),Woe(),Eue({setEnv:e.setEnv}),Rle({fs:e.fs}),tue(),QY(),$Y(),eX(`xclip`),eX(`xsel`),Xle(),V0(),qq(),Jq(),Pse(e.fs),Oee(),Hse(),pJ({getParentJid:e.getParentJid}),YQ(),ole({processManager:e.processManager}),woe({processManager:e.processManager}),Cse(),Hoe(),ype(),Mae(),Q$(),kpe({processManager:e.processManager}),l1(),GY({registry:e.cherryRuntimeRegistry}),bZ(),DZ({fs:e.fs}),OZ({fs:e.fs}),Ade(e.sudoCommand),Tme({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),dme(),ede()];return e.fs&&(Gce(),t.push(...H0.map(t=>cae(t,e.browserAPI,e.fs)))),t}const Zme=Reflect.get(Eee,`DefenseInDepthBox`);var Qme=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}virtualUsrStat(e){if(e===`/usr`||e===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(e.startsWith(`/usr/bin/`)){let t=e.slice(9);if(t.length>0&&!t.includes(`/`)&&this.getVirtualBinCommands().includes(t))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}return null}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=Zme?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=Pt(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=Pt(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=Pt(e);if(typeof t==`string`){let e=Et(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=Pt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new $t(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof $t&&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 $t&&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=Pt(e);return this.virtualUsrStat(t)?!0:this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=Pt(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.statSync(t);if(r)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)};let i=await this.vfs.stat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!!i.isSymlink,mode:i.type===`directory`?493:420,size:i.size,mtime:new Date(i.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=Pt(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.lstatSync(t);if(r)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)};let i=await this.vfs.lstat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:i.type===`symlink`,mode:i.type===`directory`?493:i.type===`symlink`?511:420,size:i.size,mtime:new Date(i.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(Pt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=Pt(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=Pt(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(Pt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=Pt(e),i=Pt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new $t(`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=Ft(e,r.name),i=Ft(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(Pt(e),Pt(t))})}resolvePath(e,t){return t.startsWith(`/`)?Pt(t):Pt(Ft(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,Pt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(Pt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(Pt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function a9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?a9(e.getUnderlyingFS?.()):null}async function $me(){await c(`github`)?.getValidAccessToken?.()}const ehe=r(`almost-bash-shell`),o9=`__SLICC_RUN_PID`;function s9(e){let t=e?.get(o9);if(t===void 0)return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function the(e){if(!(o9 in e))return{...e};let{[o9]:t,...n}=e;return n}var c9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;initialJshSync=null;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;progress;activeRunSignal;scriptRun=null;scriptRunsActive=0;registryNames=new Set;resolveJshProcessConfig=e=>this.buildJshProcessConfig(s9(e));static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}static buildInitialEnv(e,t){return{HOME:Nj,PATH:mr,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env}}buildSupplementalCommands(e,t){return Xme({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],getScriptRegisteredNames:()=>[...this.registeredJshCommands.keys(),...this.registeredWorkflowCommands],fs:e.fs,fetch:t,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,webhook:e.webhook,getParentJid:e.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:e.processManager,sudoCommand:e.sudo?{broker:e.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}})}constructor(t){this.options=t,this.vfsAdapter=new Qme(t.fs),this.progress=new MG({scrubLabel:t.scrubProgressLabel}),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r=e.buildInitialEnv(t,n);this.gitCommands=new Mj({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`,ensureFreshGithubToken:$me}),this.mountCommands=new jx({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=a9(i)??a9(a);this.scriptCatalog=t.scriptCatalog??new _r({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=p({progress:LG(this.progress)}),l=this.buildSupplementalCommands(t,c),u=[s,this.createMountCustomCommand(),ZK(t.fs),Bq(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...qn(),...Jn()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new Tee({fs:this.vfsAdapter,cwd:n,env:{},fetch:c,commands:f,customCommands:u,sleep:iK(this.progress,{isAborted:()=>this.activeRunSignal?.aborted??!1})}),this.allowedCommands!==null){let e=this.bash;for(let t of Jn())this.isCommandAllowed(t)||e.commands.delete(t)}{let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForDispatch(n));this.registryNames=new Set(e.commands.keys())}let m=u.map(e=>e.name),h=f??[...qn(),...Jn()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.startInitialJshSync()}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}applySessionOverrides(e){e.cwd!==void 0&&(this.cwd=e.cwd,this.lastEnv.PWD=e.cwd),e.env&&Object.assign(this.lastEnv,e.env)}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight===null?(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight):(this.jshSyncDirty=!0,this.jshSyncInflight)}async executeCommand(e,t,n,r=``){let i=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let i=await this.runCommand(e,t,n,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}finally{this.activeShellPid=i}}async executeScriptFile(e,t=[]){return TG(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`)}currentScanRoots(){return fr(this.lastEnv.PATH)}startInitialJshSync(){this.initialJshSync=this.initHomeAndProfile().then(()=>this.syncJshCommands()).catch(()=>void 0).finally(()=>{this.initialJshSync=null})}async initHomeAndProfile(){let e=this.options.fs;try{let t=this.options.env?.HOME??await Pj(e);this.lastEnv.HOME=t,this.options.env?.USER||(this.lastEnv.USER=Fj(t));let n=`${t.replace(/\/+$/,``)}/.profile`;if(!await e.exists(n).catch(()=>!1))return;let r=await this.bash.exec(`. "$HOME/.profile"`,{env:this.lastEnv,cwd:this.cwd});if(r.env){let{PWD:e,...t}=r.env;this.lastEnv={...t,PWD:this.lastEnv.PWD??this.cwd}}}catch(e){ehe.warn(`HOME/profile init failed; continuing with defaults`,e)}}async waitForInitialJshSync(e){let t=this.initialJshSync;if(t===null)return;if(!e){await t;return}if(e.aborted)return;let n;try{await new Promise(r=>{n=()=>r(),e.addEventListener(`abort`,n,{once:!0}),t.then(()=>r(),()=>r())})}finally{n&&e.removeEventListener(`abort`,n)}}async runCommand(e,t,n,r=``){let i=e.trim().split(/\s+/)[0]||`unknown`;Jee(i),await this.waitForInitialJshSync(t);let a={env:n===void 0?this.lastEnv:{...this.lastEnv,[o9]:String(n)},cwd:this.cwd,signal:t,...r===``?{}:{stdin:r,stdinKind:`bytes`}},o=this.lastEnv.PATH;this.activeRunSignal=t;let s=this.beginScriptRun(e),c;try{c=await this.bash.exec(e,a)}finally{this.activeRunSignal===t&&(this.activeRunSignal=void 0),this.endScriptRun(s)}if(await this.flushPendingCommandGrants(),c.env&&(this.lastEnv=the(c.env)),c.env&&this.lastEnv.PATH!==o&&await this.syncJshCommands().catch(()=>void 0),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(c.env?.PWD&&(this.cwd=c.env.PWD),c.exitCode===127){let t=await this.tryJshFallback(e,n);if(t)return this.syncJshCommands().catch(()=>void 0),t}return c}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForDispatch(e){let t=this.wrapCommandForSudo(e),n=e.name===`timeout`?cK(t,this.progress):uK(t,this.progress),r=()=>this.scriptRun?.stepDone();return{...n,async execute(e,t){try{return await n.execute(e,t)}finally{r()}}}}beginScriptRun(e){if(this.scriptRunsActive+=1,!this.progress.hasSink())return null;if(this.scriptRunsActive>1)return this.scriptRun?.end(),this.scriptRun=null,null;let t={totalSteps:null};try{t=$G(this.bash.transform(e).ast,this.registryNames)}catch{t={totalSteps:null}}return this.scriptRun=new tK(t,this.progress,eK(e)),this.scriptRun}endScriptRun(e){this.scriptRunsActive=Math.max(0,this.scriptRunsActive-1),e&&(e.end(),this.scriptRun===e&&(this.scriptRun=null))}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 fK(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=nr(e);if(!n)return;let r=`${Qn}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof $t&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
5213
|
-
`)?`${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(this.currentScanRoots()),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.wrapCommandForDispatch(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.wrapCommandForDispatch(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.options.jshDiscoveryFs??this.options.fs,r=e,i=async(e,i)=>{let a=i.exec??((e,t)=>this.bash.exec(e,{env:Object.fromEntries(i.env),cwd:t?.cwd??i.cwd,args:t?.args})),o=(await t.getJshCommands(this.currentScanRoots())).get(r);if(o){let t;try{let e=await n.readFile(o,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}return EG(t,[`node`,o,...e],{fs:i.fs,cwd:i.cwd,env:i.env,stdin:i.stdin,exec:a},this.buildJshProcessConfig(s9(i.env)))}let s=(await t.getWorkflowCommands()).get(r);if(s){let t=hr(s.path,e);return a(t[0],{args:t.slice(1),cwd:i.cwd})}return{stdout:``,stderr:`${r}: command no longer exists\n`,exitCode:127}};return{name:e,trusted:!0,async execute(e,t){try{return await i(e,t)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${r}: ${t}\n`,exitCode:1}}}}}createGitCustomCommand(){let e=this.gitCommands;return V(`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 V(`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(this.currentScanRoots()),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,t){let n=e.trim(),r=n.indexOf(` `),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1).trim():``,o=(await this.getFilteredJshCommands()).get(i);if(!o)return null;let s=a?jG(a):[],c=this.options.jshDiscoveryFs??this.options.fs,l;try{let e=await c.readFile(o,{encoding:`utf-8`});l=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127,env:this.lastEnv}}let u=[`node`,o,...s],d=await EG(l,u,{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(t));return{stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode,env:this.lastEnv}}buildJshProcessConfig(e){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>e??this.activeShellPid??this.options.getCurrentShellPid?.()}}};function nhe(e,t,n,r){return e?{...n,...r?{SLICC_LICK_TARGET:r}:{}}:{...n,HOME:`/scoops/${t}/home`,USER:t,PATH:[`/usr/bin`,`/scoops/${t}/workspace/skills`,`/scoops/${t}/workspace/bin`,...dr].join(`:`)}}function rhe(e,t,n){return e.display.role===`child`?t.folder:t.jid===n?void 0:t.folder}function ihe({sudoManager:e,unit:t,folder:n,onSudoRequest:r}){if(!e)return null;let i=e,{policy:a}=t,o=a.approvalAuthority===`user`,s=r,c=o||!s?i.getBroker():{requestApproval:e=>s(e)},l=o?()=>i.getPolicy():()=>i.getPolicyForScoop(n),u=a.sudoDefaultDisposition,d=i.getShellConfig(),f=a.persistCommandGrants?d.persistCommandGrant:async()=>{};return{broker:c,getPolicy:l,defaultDisposition:u,shellConfig:{...d,broker:c,getPolicy:l,defaultDisposition:u,persistCommandGrant:f}}}const ahe=r(`scoop-context`);async function ohe(e){let{scoop:t,unit:n,fs:r,skillsFs:i}=e,a=n.workspace.root,o=e.getBrowserAPI();n.policy.filesystem.kind===`full-workspace`&&await ib(r,Ah);let s=i??r,c=await Dx(),l=ihe({sudoManager:e.sudoManager,unit:n,folder:t.folder,onSudoRequest:e.onSudoRequest}),u=l?
|
|
5212
|
+
`,exitCode:1};let c=Wee(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function Xme(e={}){let t=[dae({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),AY(),Ode(),Xue(e.browserAPI,e.fs),Mce(e.browserAPI),Pae(e),Yme(),Ufe(),Qde(),Mde(),zde(),Ide(),tX(),qme(),M5(`sqlite3`),M5(`sqllite`),lfe(),wfe(),g$(),hY(),zse({buildProcessConfig:e.buildProcessConfig}),X8(`python3`,{buildProcessConfig:e.buildProcessConfig}),X8(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[S6(`ipk`,{fs:e.fs,fetch:e.fetch}),S6(`npm`,{fs:e.fs,fetch:e.fetch}),S6(`i`,{fs:e.fs,fetch:e.fetch}),U6(`ipx`,{fs:e.fs,fetch:e.fetch}),U6(`npx`,{fs:e.fs,fetch:e.fetch}),eQ(`di`,{fs:e.fs,fetch:e.fetch}),eQ(`uv`,{fs:e.fs,fetch:e.fetch}),tpe({fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[gae({fetch:e.fetch})]:[],i0(),rme(e.webhook),ume(),pZ(),Yoe({fs:e.fs,scriptCatalog:e.scriptCatalog}),qce({fs:e.fs,fetch:e.fetch}),D0(),gde(),L8(`pdftk`),L8(`pdf`),z8(`pdftoppm`),z8(`pdftocairo`),eZ(`convert`),eZ(`magick`),hme({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins,getScriptRegisteredNames:e.getScriptRegisteredNames}),Tfe(),Rfe(),zfe(),qoe(),HQ(),Zse(),Wse(),Woe(),Eue({setEnv:e.setEnv}),Rle({fs:e.fs}),tue(),QY(),$Y(),eX(`xclip`),eX(`xsel`),Xle(),V0(),qq(),Jq(),Pse(e.fs),Dee(),Hse(),pJ({getParentJid:e.getParentJid}),YQ(),ole({processManager:e.processManager}),woe({processManager:e.processManager}),Cse(),Hoe(),ype(),Mae(),Q$(),kpe({processManager:e.processManager}),l1(),GY({registry:e.cherryRuntimeRegistry}),bZ(),DZ({fs:e.fs}),OZ({fs:e.fs}),Ade(e.sudoCommand),Tme({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),dme(),ede()];return e.fs&&(Gce(),t.push(...H0.map(t=>cae(t,e.browserAPI,e.fs)))),t}const Zme=Reflect.get(Tee,`DefenseInDepthBox`);var Qme=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}virtualUsrStat(e){if(e===`/usr`||e===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(e.startsWith(`/usr/bin/`)){let t=e.slice(9);if(t.length>0&&!t.includes(`/`)&&this.getVirtualBinCommands().includes(t))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}return null}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=Zme?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=Pt(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=Pt(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=Pt(e);if(typeof t==`string`){let e=Et(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=Pt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new $t(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof $t&&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 $t&&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=Pt(e);return this.virtualUsrStat(t)?!0:this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=Pt(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.statSync(t);if(r)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)};let i=await this.vfs.stat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:!!i.isSymlink,mode:i.type===`directory`?493:420,size:i.size,mtime:new Date(i.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=Pt(e),n=this.virtualUsrStat(t);if(n)return n;let r=this.vfs.lstatSync(t);if(r)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)};let i=await this.vfs.lstat(t);return{isFile:i.type===`file`,isDirectory:i.type===`directory`,isSymbolicLink:i.type===`symlink`,mode:i.type===`directory`?493:i.type===`symlink`?511:420,size:i.size,mtime:new Date(i.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(Pt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=Pt(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=Pt(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(Pt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=Pt(e),i=Pt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new $t(`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=Ft(e,r.name),i=Ft(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(Pt(e),Pt(t))})}resolvePath(e,t){return t.startsWith(`/`)?Pt(t):Pt(Ft(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,Pt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(Pt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(Pt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function a9(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?a9(e.getUnderlyingFS?.()):null}async function $me(){await c(`github`)?.getValidAccessToken?.()}const ehe=r(`almost-bash-shell`),o9=`__SLICC_RUN_PID`;function s9(e){let t=e?.get(o9);if(t===void 0)return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function the(e){if(!(o9 in e))return{...e};let{[o9]:t,...n}=e;return n}var c9=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;initialJshSync=null;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;progress;activeRunSignal;scriptRun=null;scriptRunsActive=0;registryNames=new Set;resolveJshProcessConfig=e=>this.buildJshProcessConfig(s9(e));static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}static buildInitialEnv(e,t){return{HOME:Nj,PATH:mr,USER:`user`,SHELL:`/bin/bash`,PWD:t,...e.env}}buildSupplementalCommands(e,t){return Xme({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],getScriptRegisteredNames:()=>[...this.registeredJshCommands.keys(),...this.registeredWorkflowCommands],fs:e.fs,fetch:t,scriptCatalog:this.scriptCatalog,browserAPI:e.browserAPI,webhook:e.webhook,getParentJid:e.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:e.processManager,sudoCommand:e.sudo?{broker:e.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}})}constructor(t){this.options=t,this.vfsAdapter=new Qme(t.fs),this.progress=new MG({scrubLabel:t.scrubProgressLabel}),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r=e.buildInitialEnv(t,n);this.gitCommands=new Mj({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`,ensureFreshGithubToken:$me}),this.mountCommands=new jx({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=a9(i)??a9(a);this.scriptCatalog=t.scriptCatalog??new _r({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=p({progress:LG(this.progress)}),l=this.buildSupplementalCommands(t,c),u=[s,this.createMountCustomCommand(),ZK(t.fs),Bq(t.fs,c,t.browserAPI),...l].filter(e=>this.isCommandAllowed(e.name)),d=[...Jn(),...Yn()],f=this.allowedCommands?d.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new wee({fs:this.vfsAdapter,cwd:n,env:{},fetch:c,commands:f,customCommands:u,sleep:iK(this.progress,{isAborted:()=>this.activeRunSignal?.aborted??!1})}),this.allowedCommands!==null){let e=this.bash;for(let t of Yn())this.isCommandAllowed(t)||e.commands.delete(t)}{let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForDispatch(n));this.registryNames=new Set(e.commands.keys())}let m=u.map(e=>e.name),h=f??[...Jn(),...Yn()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.startInitialJshSync()}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}applySessionOverrides(e){e.cwd!==void 0&&(this.cwd=e.cwd,this.lastEnv.PWD=e.cwd),e.env&&Object.assign(this.lastEnv,e.env)}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight===null?(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight):(this.jshSyncDirty=!0,this.jshSyncInflight)}async executeCommand(e,t,n,r=``){let i=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let i=await this.runCommand(e,t,n,r);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}}finally{this.activeShellPid=i}}async executeScriptFile(e,t=[]){return TG(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`)}currentScanRoots(){return fr(this.lastEnv.PATH)}startInitialJshSync(){this.initialJshSync=this.initHomeAndProfile().then(()=>this.syncJshCommands()).catch(()=>void 0).finally(()=>{this.initialJshSync=null})}async initHomeAndProfile(){let e=this.options.fs;try{let t=this.options.env?.HOME??await Pj(e);this.lastEnv.HOME=t,this.options.env?.USER||(this.lastEnv.USER=Fj(t));let n=`${t.replace(/\/+$/,``)}/.profile`;if(!await e.exists(n).catch(()=>!1))return;let r=await this.bash.exec(`. "$HOME/.profile"`,{env:this.lastEnv,cwd:this.cwd});if(r.env){let{PWD:e,...t}=r.env;this.lastEnv={...t,PWD:this.lastEnv.PWD??this.cwd}}}catch(e){ehe.warn(`HOME/profile init failed; continuing with defaults`,e)}}async waitForInitialJshSync(e){let t=this.initialJshSync;if(t===null)return;if(!e){await t;return}if(e.aborted)return;let n;try{await new Promise(r=>{n=()=>r(),e.addEventListener(`abort`,n,{once:!0}),t.then(()=>r(),()=>r())})}finally{n&&e.removeEventListener(`abort`,n)}}async runCommand(e,t,n,r=``){let i=e.trim().split(/\s+/)[0]||`unknown`;qee(i),await this.waitForInitialJshSync(t);let a={env:n===void 0?this.lastEnv:{...this.lastEnv,[o9]:String(n)},cwd:this.cwd,signal:t,...r===``?{}:{stdin:r,stdinKind:`bytes`}},o=this.lastEnv.PATH;this.activeRunSignal=t;let s=this.beginScriptRun(e),c;try{c=await this.bash.exec(e,a)}finally{this.activeRunSignal===t&&(this.activeRunSignal=void 0),this.endScriptRun(s)}if(await this.flushPendingCommandGrants(),c.env&&(this.lastEnv=the(c.env)),c.env&&this.lastEnv.PATH!==o&&await this.syncJshCommands().catch(()=>void 0),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(c.env?.PWD&&(this.cwd=c.env.PWD),c.exitCode===127){let t=await this.tryJshFallback(e,n);if(t)return this.syncJshCommands().catch(()=>void 0),t}return c}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForDispatch(e){let t=this.wrapCommandForSudo(e),n=e.name===`timeout`?cK(t,this.progress):uK(t,this.progress),r=()=>this.scriptRun?.stepDone();return{...n,async execute(e,t){try{return await n.execute(e,t)}finally{r()}}}}beginScriptRun(e){if(this.scriptRunsActive+=1,!this.progress.hasSink())return null;if(this.scriptRunsActive>1)return this.scriptRun?.end(),this.scriptRun=null,null;let t={totalSteps:null};try{t=$G(this.bash.transform(e).ast,this.registryNames)}catch{t={totalSteps:null}}return this.scriptRun=new tK(t,this.progress,eK(e)),this.scriptRun}endScriptRun(e){this.scriptRunsActive=Math.max(0,this.scriptRunsActive-1),e&&(e.end(),this.scriptRun===e&&(this.scriptRun=null))}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 fK(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=rr(e);if(!n)return;let r=`${$n}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch(e){if(!(e instanceof $t&&e.code===`ENOENT`))throw e}let o=a&&!a.endsWith(`
|
|
5213
|
+
`)?`${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(this.currentScanRoots()),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.wrapCommandForDispatch(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.wrapCommandForDispatch(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.options.jshDiscoveryFs??this.options.fs,r=e,i=async(e,i)=>{let a=i.exec??((e,t)=>this.bash.exec(e,{env:Object.fromEntries(i.env),cwd:t?.cwd??i.cwd,args:t?.args})),o=(await t.getJshCommands(this.currentScanRoots())).get(r);if(o){let t;try{let e=await n.readFile(o,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127}}return EG(t,[`node`,o,...e],{fs:i.fs,cwd:i.cwd,env:i.env,stdin:i.stdin,exec:a},this.buildJshProcessConfig(s9(i.env)))}let s=(await t.getWorkflowCommands()).get(r);if(s){let t=hr(s.path,e);return a(t[0],{args:t.slice(1),cwd:i.cwd})}return{stdout:``,stderr:`${r}: command no longer exists\n`,exitCode:127}};return{name:e,trusted:!0,async execute(e,t){try{return await i(e,t)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${r}: ${t}\n`,exitCode:1}}}}}createGitCustomCommand(){let e=this.gitCommands;return V(`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 V(`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(this.currentScanRoots()),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,t){let n=e.trim(),r=n.indexOf(` `),i=r>=0?n.slice(0,r):n,a=r>=0?n.slice(r+1).trim():``,o=(await this.getFilteredJshCommands()).get(i);if(!o)return null;let s=a?jG(a):[],c=this.options.jshDiscoveryFs??this.options.fs,l;try{let e=await c.readFile(o,{encoding:`utf-8`});l=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${o}'\n`,exitCode:127,env:this.lastEnv}}let u=[`node`,o,...s],d=await EG(l,u,{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(t));return{stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode,env:this.lastEnv}}buildJshProcessConfig(e){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>e??this.activeShellPid??this.options.getCurrentShellPid?.()}}};function nhe(e,t,n,r){return e?{...n,...r?{SLICC_LICK_TARGET:r}:{}}:{...n,HOME:`/scoops/${t}/home`,USER:t,PATH:[`/usr/bin`,`/scoops/${t}/workspace/skills`,`/scoops/${t}/workspace/bin`,...dr].join(`:`)}}function rhe(e,t,n){return e.display.role===`child`?t.folder:t.jid===n?void 0:t.folder}function ihe({sudoManager:e,unit:t,folder:n,onSudoRequest:r}){if(!e)return null;let i=e,{policy:a}=t,o=a.approvalAuthority===`user`,s=r,c=o||!s?i.getBroker():{requestApproval:e=>s(e)},l=o?()=>i.getPolicy():()=>i.getPolicyForScoop(n),u=a.sudoDefaultDisposition,d=i.getShellConfig(),f=a.persistCommandGrants?d.persistCommandGrant:async()=>{};return{broker:c,getPolicy:l,defaultDisposition:u,shellConfig:{...d,broker:c,getPolicy:l,defaultDisposition:u,persistCommandGrant:f}}}const ahe=r(`scoop-context`);async function ohe(e){let{scoop:t,unit:n,fs:r,skillsFs:i}=e,a=n.workspace.root,o=e.getBrowserAPI();n.policy.filesystem.kind===`full-workspace`&&await ib(r,Ah);let s=i??r,c=await Dx(),l=ihe({sudoManager:e.sudoManager,unit:n,folder:t.folder,onSudoRequest:e.onSudoRequest}),u=l?Nee(r,{broker:l.broker,getPolicy:l.getPolicy,defaultDisposition:l.defaultDisposition}):r,d=nhe(n.policy.filesystem.kind===`full-workspace`,t.folder,c,e.lickTarget),f=new c9({fs:u,cwd:a,env:Object.keys(d).length>0?d:void 0,browserAPI:o,webhook:{hasLocalNodeServer:pt,getLeaderStatus:un},jshDiscoveryFs:i?s:void 0,allowedCommands:t.config?.allowedCommands,getParentJid:()=>t.jid,isScoop:()=>n.display.role===`child`,sudo:l?.shellConfig,scrubProgressLabel:mt(),processManager:e.processManager??void 0,processOwner:e.processOwner,getCurrentShellPid:e.getTurnPid});return ahe.info(`AlmostBashShell initialized`,{folder:t.folder}),{shell:f,gatedFs:u,skills:await eb(s,Ah)}}const l9=51200;function u9(e){if(e.length===0)return[];let t=e.split(`
|
|
5214
5214
|
`);return e.endsWith(`
|
|
5215
5215
|
`)&&t.pop(),t}function d9(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}function she(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=u9(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};if(Buffer.byteLength(a[0],`utf-8`)>r)return{content:``,truncated:!0,truncatedBy:`bytes`,totalLines:o,totalBytes:i,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`;for(let e=0;e<a.length&&e<n;e++){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(e>0);if(c+n>r){l=`bytes`;break}s.push(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let u=s.join(`
|
|
5216
5216
|
`),d=Buffer.byteLength(u,`utf-8`);return{content:u,truncated:!0,truncatedBy:l,totalLines:o,totalBytes:i,outputLines:s.length,outputBytes:d,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r}}function f9(e,t={}){let n=t.maxLines??2e3,r=t.maxBytes??51200,i=Buffer.byteLength(e,`utf-8`),a=u9(e),o=a.length;if(o<=n&&i<=r)return{content:e,truncated:!1,truncatedBy:null,totalLines:o,totalBytes:i,outputLines:o,outputBytes:i,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:n,maxBytes:r};let s=[],c=0,l=`lines`,u=!1;for(let e=a.length-1;e>=0&&s.length<n;e--){let t=a[e],n=Buffer.byteLength(t,`utf-8`)+ +(s.length>0);if(c+n>r){if(l=`bytes`,s.length===0){let e=che(t,r);s.unshift(e),c=Buffer.byteLength(e,`utf-8`),u=!0}break}s.unshift(t),c+=n}s.length>=n&&c<=r&&(l=`lines`);let d=s.join(`
|
|
@@ -5220,8 +5220,8 @@ pass --wait to block and print the full result.
|
|
|
5220
5220
|
`)}async function Bhe(e,t){let n=Rhe(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return S9.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:zhe(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Vhe(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return T9(n,t.getScoops);if(i.jid===t.scoop.jid)return{content:`Cannot feed yourself.`,isError:!0};if(i.parentJid===null)return{content:`Cannot feed a cone (root unit).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),S9.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 Hhe(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>Ihe(t,e.getScoopTabState)).join(`
|
|
5221
5221
|
`)}`}}function Uhe({name:e,folder:t,model:n,modelProviderId:r,visiblePaths:i,writablePaths:a,allowedCommands:o,thinkingLevel:s,backgroundAfterSeconds:c,parentJid:l,defaultVisibleRoots:u}){return{name:e,folder:t,trigger:`@${t}`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},...n&&r?{modelProviderId:r}:{},visiblePaths:i??u,writablePaths:a??[`/scoops/${t}/`,`/shared/`],...o?{allowedCommands:o}:{},...s?{thinkingLevel:s}:{},...c===void 0?{}:{backgroundAfterSeconds:c}},configSchemaVersion:3,parentJid:l}}async function Whe(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return S9.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 Ghe(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c,background_after:l}=e,u=Nhe(c);if(!u.ok)return{content:u.content,isError:u.isError};let d=Phe(l);if(!d.ok)return{content:d.content,isError:!0};let f=Fhe(r,t.resolveModelSelection);if(!f.ok)return{content:f.content,isError:f.isError};let p=Mhe(n);try{let e=Uhe({name:n,folder:p,model:f.modelId,modelProviderId:f.providerId,visiblePaths:a,writablePaths:o,allowedCommands:s,thinkingLevel:u.level,backgroundAfterSeconds:d.seconds,parentJid:t.scoop.jid,defaultVisibleRoots:Ph(jh(t.scoop))}),r=await t.onScoopScoop(e);return S9.info(`Scoop created`,{name:n,folder:p}),i&&t.onFeedScoop?Whe(r,i,n,p,t.onFeedScoop):{content:`Scoop "${n}" created as "${p}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function Khe(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return T9(n,t.getScoops);if(r.jid===t.scoop.jid)return{content:`Cannot drop yourself.`,isError:!0};if(r.parentJid===null)return{content:`Cannot drop a cone (root unit).`,isError:!0};try{return await t.onDropScoop(r.jid),S9.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 E9(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function D9(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function qhe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return E9();let{resolved:r,unknown:i}=C9(n,t.getScoops);return r.length===0?D9(i):(t.onMuteScoops(r.map(e=>e.jid)),S9.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function Jhe(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 Yhe(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return E9();let{resolved:r,unknown:i}=C9(n,t.getScoops);if(r.length===0)return D9(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);S9.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(...Jhe(s,o)),{content:c.join(`
|
|
5222
5222
|
`)}}function Xhe(e,t){return!Array.isArray(e)||e.length===0?E9():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 Zhe(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 Qhe(e,t){let{scoop_names:n,timeout_ms:r}=e,i=Xhe(n,r);if(i)return i;let{resolved:a,unknown:o}=C9(n,t.getScoops);if(a.length===0)return D9(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 S9.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:Zhe(u,o,d,r)}}function $he(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 ege(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?(S9.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:$he(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 tge(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?(S9.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 nge(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(`
|
|
5223
|
-
`)}`}}async function rge(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),S9.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 ige(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=>Lhe(t,e)}}function age(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:[...w9],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=>Bhe(t,e)}}function oge(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=>Vhe(t,e)}}function sge(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>Hhe(e)}}function cge(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: YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...Hh],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`}},required:[`name`]},execute:t=>Ghe(t,e)}}function lge(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=>Khe(t,e)}}function uge(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=>qhe(t,e)}}function dge(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=>Yhe(t,e)}}function fge(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=>Qhe(t,e)}}function pge(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=>ege(t,e)}}function mge(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>tge(t,e)}}function hge(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:()=>nge(e)}}function gge(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=>rge(t,e)}}function _ge(e){let t=[],n=oh(e.scoop);return rh(e.scoop)||(t.push(ige(e)),e.onSudoRequest&&t.push(age(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(oge(e)),t.push(sge(e)),e.onScoopScoop&&t.push(cge(e)),e.onDropScoop&&t.push(lge(e)),e.onMuteScoops&&t.push(uge(e)),e.onUnmuteScoops&&t.push(dge(e)),e.onScheduleScoopWait&&t.push(fge(e)),e.onSudoResolve&&(t.push(pge(e)),t.push(mge(e))),e.onListSudoRequests&&t.push(hge(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(gge(e))),t}const vge=r(`scoop-context`);async function yge(e){let{scoop:t,unit:n,callbacks:r}=e,i=_ge({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:L,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=[...Ohe(e.gatedFs),She(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:mt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){vge.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);a.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let o={scrubToolResult:mt()};return e.processManager?Ue(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o):Ue(a,void 0,o)}const O9=r(`scoop-context`);async function bge(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e;O9.info(`Filesystem ready`,{folder:t.folder}),await Sx(r,t,n);let{shell:a,gatedFs:o,skills:s}=await ohe({scoop:t,unit:n,fs:r,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(a);let c=await yge({scoop:t,unit:n,callbacks:i,shell:a,fs:r,gatedFs:o,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:l,globalMemory:u}=await nx(r,n,()=>i.getGlobalMemory());if(!ix(t))return O9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let d=ox(t,n),f=lx(t,n,u,l,s),p=await e.sessions.restore(),{streamWithSessionId:m,compactFn:h,getCompactionApiKey:g}=await Cx(d,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>ix(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:e=>i.onCompactionStateChange?.(e)});if(e.isDisposed())return{kind:`abandoned`};let _=Ch(t);return{kind:`ready`,agent:bx({model:d,tools:c,systemPrompt:f,messages:p,thinkingLevel:dx(fx()??_.level,d),getApiKey:()=>ix(t)??void 0,transformContext:h,streamFn:m,captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:h,getCompactionApiKey:g,effortOverride:_.effortOverride,toolCount:c.length}}const k9=r(`scoop-context`);var xge=class{deps;timer=null;createdAt=0;constructor(e){this.deps=e}get sessionId(){return this.deps.sessionId}get store(){return this.deps.store}async restore(){let e=this.deps.store;if(!e)return[];try{let t=await e.load(this.deps.sessionId);if(t){let e=ree(t.messages);return this.createdAt=t.createdAt,k9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:e.length,droppedOrphans:t.messages.length-e.length}),e}}catch(e){k9.error(`Failed to restore agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`)}return[]}persistNow(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[],n=this.deps.store;!n||t.length===0||n.save({id:this.deps.sessionId,messages:t,config:{},createdAt:this.createdAt||Date.now(),updatedAt:Date.now()}).catch(e=>{k9.error(`Failed to save agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}schedule(){this.deps.isDisposed()||!this.deps.store||this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function Sge(e,t){if(!e)return null;let{text:n}=t,r=n.length>200?`${n.slice(0,197)}…`:n;return e.spawn({kind:`scoop-turn`,argv:[`prompt`,r],cwd:t.cwd,owner:t.owner,adoptAbort:t.abortController})}function Cge(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function A9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const j9=r(`scoop-context`);var wge=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;j9.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(j9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:Ub(r)}),!!(t<3&&(await Wb(M9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return Hb(e)?(j9.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return pa(e)?(j9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),ga(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!Ub(e)||t>=3)return!1;let r=M9(t);return j9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await Wb(r,n)&&!this.deps.isDisposed()}fail(e,t){ir(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function M9(e){return 1e3*2**(e-1)}function Tge(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){j9.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const N9=r(`scoop-context`);var Ege=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;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;turnRunner;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>this.callbacks.onToolStart?.(e,t,n),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:()=>this.sessions.schedule(),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.unit=Fh(e),this.owner={kind:vh(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessions=new xge({store:r??null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new yx({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new Zb({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new $b({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new vx({getAgent:()=>this.agent,isDisposed:()=>this.disposed,getTurnSignal:()=>this.promptAbortController?.signal,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),isImageRecoveryActive:()=>this.imageRecovery.isActive,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onExhausted:e=>this.reportExhaustedOverflow(e),setStatus:e=>this.setStatus(e),scoopName:e.name,folder:e.folder}),this.turnRunner=new wge({isDisposed:()=>this.disposed,overflow:this.overflow,beginAttempt:()=>{this.didStreamDeltas=!1,this.promptStreamErrorMessage=null},getStreamError:()=>this.promptStreamErrorMessage,setStatus:e=>this.setStatus(e),onError:e=>this.callbacks.onError(e),onFatalError:t.onFatalError?e=>this.callbacks.onFatalError?.(e):void 0,isInteractive:this.unit.completion.mode===`interactive`,scoopName:e.name,folder:e.folder})}ownLickTarget(){return rhe(this.unit,this.scoop,uh(this.callbacks.getScoops())[0]?.jid)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);let e=await bge({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getLickTarget:()=>this.ownLickTarget(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},spawnBashJob:e=>this.bashJobs.spawn(e)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),N9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);N9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(cx(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),Cge(this.processManager,t,{lastError:n,aborted:r.aborted}),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async prompt(e,t=[],n){if(!await this.ensureAgentReady()||Tge(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder}))return;let r=this.agent;this.promptAbortController?.abort();let i=new AbortController;this.promptAbortController=i;let a=i.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=Sge(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:i});this.currentTurnProcess=o,this.runBounds.arm();let s=null;try{if(s=await this.turnRunner.run(r,e,t,a),s&&!this.disposed&&!a.aborted){this.turnRunner.reportExhausted(s);return}!this.disposed&&!a.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(i,o,s,a)}}stop(){A9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return sx(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=mx(this.agent,this.scoop))}async reloadSkills(){this.agent&&await gx(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?fx()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,hx(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.runBounds.disarm(),A9(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){this.disposed||qb(e,this.eventSink,t)}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||Gb(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const P9=r(`scoop-lifecycle-manager`);var Dge=class{deps;units=new Map;constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new Bb(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??uh(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return lh(t.values(),e)??uh(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){P9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof Kn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context)if(n.tab?.status===`error`)P9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{P9.debug(`Context already exists`,{jid:e});return}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Fh(t).policy.filesystem,o=a.kind===`full-workspace`?r:new Kn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new Ege(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{P9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),P9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),P9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return P9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(P9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){P9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){P9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),P9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();fh(e),this.inheritModel(e),await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),P9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&rr(`spawn`,e.folder)}catch(n){P9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){P9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{P9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(xh(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?bh(t):void 0)??gb();n&&wh(e,n)}async unregister(e){let t=this.deps.getScoops(),n=t.get(e);if(n&&n.parentJid===null&&uh(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{P9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{P9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&P9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),P9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){P9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;wh(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return wh(n,r),this.getContext(e)?.updateModel(),P9.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return!0}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();P9.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{P9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),P9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Th(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){P9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Fh(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),rr(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:jh(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:o.canResolveApprovals?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(P9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),rr(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Fh(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){P9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{P9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const F9=r(`scoop-message-router`);var Oge=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if(F9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){F9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);rr(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),F9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){F9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){F9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(F9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){F9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{F9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);F9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;if(n.reported||r<3e5)return;n.reported=!0;let i=`Lick queue remained deferred while scoop was busy for ${3e5/1e3}s`;F9.warn(`Busy lick queue may be starved`,{jid:e,error:i}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r})}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){F9.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){F9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){F9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(F9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){F9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){F9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){F9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${Qm(e.content,e.attachments)}`).join(`
|
|
5224
|
-
`),l=s.flatMap(e=>$m(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=gn(kn(bn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);F9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{F9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{F9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),F9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{F9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),F9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const I9=r(`orchestrator`);var kge=class{scoops=new Map;workUnits=new xre(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new lb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Lb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Fb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new kb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new xb({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>wn(e),saveMessage:e=>_n(e)});lickRegistry=new fb({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Oge({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>_n(e),deleteMessage:e=>yn(e),clearMessagesForScoop:e=>Dn(e),clearAllMessages:()=>Tn(),getMessagesSince:(e,t,n)=>Cn(e,t,n),setState:(e,t)=>hn(e,t)},isExternalLickChannel:wg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Dge({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=>mn(e),deleteScoop:e=>En(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>See(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(e){await Mn(),this.sharedFs=await _b(()=>Gn.create({dbName:`slicc-fs`}),e),this.sessionStore=new nh,this.fsWatcher=new wee,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new H_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new d_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new hb(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await An(),n=Object.values(t).find(e=>dh(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),fh(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Sn(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new yb({onTaskRun:async(e,t)=>{I9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),I9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);I9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Dee(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=W_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=dh(e)?null:t??null;try{await mn(e)}catch(t){I9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!xh(e));if(e.length===0)return;let t=gb(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?bh(n):void 0)??t;if(r){wh(e,r);try{await mn(e)}catch(t){I9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Mh.root}/`,r=Ph(Nh(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setScoopExistenceResolver(e=>this.getScoops().some(t=>bee(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return uh(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Gn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ib(this.sharedFs).catch(e=>{I9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new H_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new d_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new hb(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),I9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return wn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CLzdz05B.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(kee)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&I9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,I9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new bg,t=this.sharedFs;return new my({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:My(),snapshotStore:{read:e=>Ty(t,e),write:(e,n)=>wy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.90.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function Age(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function jge(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=(e,n)=>Ige(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=Age(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,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(c,d),Pge(t,n);let f=i(a.ctx,c),p=Fge(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>L9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${R9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(R9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},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=u,s.preview=i===`done`?Nge(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,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:a,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 Mge(e){let t=jge(e);return globalThis[J7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Nge(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Pge(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 Fge(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 Ige(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Lge(n,t,a?.args??[],r):e===`agent`?Rge(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Lge(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>z9&&i.logs.splice(0,i.logs.length-z9),r()}return{stdout:``,stderr:``,exitCode:0}}async function Rge(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}var zge=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=V9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new $t(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new $t(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new $t(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new $t(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return Gge(t);let n=this.pm.get(e);switch(t){case`status`:return Bge(n);case`cmdline`:return Vge(n);case`cwd`:return Hge(n);case`stat`:return Uge(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Bge(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Wge(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(`
|
|
5223
|
+
`)}`}}async function rge(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),S9.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 ige(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=>Lhe(t,e)}}function age(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:[...w9],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=>Bhe(t,e)}}function oge(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=>Vhe(t,e)}}function sge(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>Hhe(e)}}function cge(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: YOUR OWN workspace plus the shared skills tree — ["/workspace/"] for the primary cone, ["/cones/<folder>/workspace/", "/workspace/skills/"] for any other. Prefer omitting it over naming "/workspace/" explicitly, which would point the scoop at a different cone's files. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes — note that /tmp stays readable and writable regardless, as shared scratch space every scoop gets (so nothing secret belongs there). Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...Hh],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`},background_after:{type:`number`,description:`Seconds this scoop's bash tool waits for a command before detaching it to the background and continuing (default 600). Lower it for a scoop that must never stall on a slow command — nobody can cancel a scoop's turn, and its detached commands report back via a Background Command lick. Use 0 to detach every command immediately.`}},required:[`name`]},execute:t=>Ghe(t,e)}}function lge(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=>Khe(t,e)}}function uge(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=>qhe(t,e)}}function dge(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=>Yhe(t,e)}}function fge(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=>Qhe(t,e)}}function pge(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=>ege(t,e)}}function mge(e){return{name:`lick_dismiss`,description:`Dismiss a pending actionable lick by its lick_id. For scoop sudo escalation this denies the sensitive action. For llms.txt discovery this silently appends the advertising host to /etc/llmstxtignore.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in a sudo-request or llms.txt discovery notification).`}},required:[`lick_id`]},execute:t=>tge(t,e)}}function hge(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:()=>nge(e)}}function gge(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=>rge(t,e)}}function _ge(e){let t=[],n=oh(e.scoop);return rh(e.scoop)||(t.push(ige(e)),e.onSudoRequest&&t.push(age(e))),n.canManageChildren&&(e.onFeedScoop&&t.push(oge(e)),t.push(sge(e)),e.onScoopScoop&&t.push(cge(e)),e.onDropScoop&&t.push(lge(e)),e.onMuteScoops&&t.push(uge(e)),e.onUnmuteScoops&&t.push(dge(e)),e.onScheduleScoopWait&&t.push(fge(e)),e.onSudoResolve&&(t.push(pge(e)),t.push(mge(e))),e.onListSudoRequests&&t.push(hge(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(gge(e))),t}const vge=r(`scoop-context`);async function yge(e){let{scoop:t,unit:n,callbacks:r}=e,i=_ge({scoop:t,onSendMessage:r.onSendMessage,getScoops:r.getScoops,getScoopTabState:r.getScoopTabState,onFeedScoop:r.onFeedScoop,onScoopScoop:r.onScoopScoop,resolveModelSelection:L,onDropScoop:r.onDropScoop,onMuteScoops:r.onMuteScoops,onUnmuteScoops:r.onUnmuteScoops,onScheduleScoopWait:r.onScheduleScoopWait,onSetGlobalMemory:r.setGlobalMemory,getGlobalMemory:r.getGlobalMemory,onSudoRequest:r.onSudoRequest,onSudoResolve:r.onSudoResolve,onListSudoRequests:r.onListSudoRequests}),a=[...Ohe(e.gatedFs),She(e.shell,e.fs,n.workspace.scratch,{defaultBackgroundAfterSeconds:t.config?.backgroundAfterSeconds,targetScoop:e.lickTarget,jobHost:{spawn:t=>e.spawnBashJob(t)},scrubOutput:mt(),fireLick:e=>{let n=globalThis.__slicc_lick_handler;if(!n){vge.warn(`No lick handler for background bash completion`,{folder:t.folder});return}n(e)}}),...i];if(t.config?.structuredOutputSchema){let{createStructuredOutputTool:n}=await import(`./structured-output-tool-BDaIhclx.js`);a.push(n(t.config.structuredOutputSchema,e.onStructuredOutput))}let o={scrubToolResult:mt()};return e.processManager?Ue(a,{processManager:e.processManager,owner:e.processOwner,getParentPid:e.getTurnPid},o):Ue(a,void 0,o)}const O9=r(`scoop-context`);async function bge(e){let{scoop:t,unit:n,fs:r,callbacks:i}=e;O9.info(`Filesystem ready`,{folder:t.folder}),await Sx(r,t,n);let{shell:a,gatedFs:o,skills:s}=await ohe({scoop:t,unit:n,fs:r,skillsFs:e.skillsFs,getBrowserAPI:i.getBrowserAPI,sudoManager:e.sudoManager,onSudoRequest:i.onSudoRequest,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget()});e.onShellReady(a);let c=await yge({scoop:t,unit:n,callbacks:i,shell:a,fs:r,gatedFs:o,processManager:e.processManager,processOwner:e.processOwner,getTurnPid:e.getTurnPid,lickTarget:e.getLickTarget(),onStructuredOutput:e.onStructuredOutput,spawnBashJob:e.spawnBashJob}),{scoopMemory:l,globalMemory:u}=await nx(r,n,()=>i.getGlobalMemory());if(!ix(t))return O9.info(`ScoopContext init deferred — no API key yet`,{folder:t.folder}),{kind:`deferred`};let d=ox(t,n),f=lx(t,n,u,l,s),p=await e.sessions.restore(),{streamWithSessionId:m,compactFn:h,getCompactionApiKey:g}=await Cx(d,{scoop:t,unit:n,coneJid:e.coneJid,getModelApiKey:()=>ix(t),getEffortOverride:e.getEffortOverride,appendConeMemory:i.appendConeMemory,onCompactionStateChange:e=>i.onCompactionStateChange?.(e)});if(e.isDisposed())return{kind:`abandoned`};let _=Ch(t);return{kind:`ready`,agent:bx({model:d,tools:c,systemPrompt:f,messages:p,thinkingLevel:dx(fx()??_.level,d),getApiKey:()=>ix(t)??void 0,transformContext:h,streamFn:m,captureStructuredOutput:t.config?.structuredOutputSchema?e.onStructuredOutput:void 0}),compactFn:h,getCompactionApiKey:g,effortOverride:_.effortOverride,toolCount:c.length}}const k9=r(`scoop-context`);var xge=class{deps;timer=null;createdAt=0;constructor(e){this.deps=e}get sessionId(){return this.deps.sessionId}get store(){return this.deps.store}async restore(){let e=this.deps.store;if(!e)return[];try{let t=await e.load(this.deps.sessionId);if(t){let e=ree(t.messages);return this.createdAt=t.createdAt,k9.info(`Restored agent session`,{folder:this.deps.folder,messageCount:e.length,droppedOrphans:t.messages.length-e.length}),e}}catch(e){k9.error(`Failed to restore agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)}),this.deps.onRestoreError(`Conversation history could not be restored. Starting fresh.`)}return[]}persistNow(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t=this.deps.getMessages()??e??[],n=this.deps.store;!n||t.length===0||n.save({id:this.deps.sessionId,messages:t,config:{},createdAt:this.createdAt||Date.now(),updatedAt:Date.now()}).catch(e=>{k9.error(`Failed to save agent session`,{folder:this.deps.folder,error:e instanceof Error?e.message:String(e)})})}schedule(){this.deps.isDisposed()||!this.deps.store||this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.deps.isDisposed()||this.persistNow()},1e3))}};function Sge(e,t){if(!e)return null;let{text:n}=t,r=n.length>200?`${n.slice(0,197)}…`:n;return e.spawn({kind:`scoop-turn`,argv:[`prompt`,r],cwd:t.cwd,owner:t.owner,adoptAbort:t.abortController})}function Cge(e,t,n){!t||!e||(n.lastError&&!n.aborted?e.exit(t.pid,1):e.exit(t.pid,n.aborted?null:0))}function A9(e,t,n,r){t&&e?e.signal(t.pid,n):r?.abort()}const j9=r(`scoop-context`);var wge=class{deps;constructor(e){this.deps=e}async run(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.deps.isDisposed()||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n,r);if(!o||this.deps.isDisposed()||r.aborted||(i=o,await this.handleAttemptError(o,a,r)))return null}return i}reportExhausted(e){let t=e.message;j9.error(`Agent error after retries exhausted`,{folder:this.deps.folder,error:t,maxRetries:3}),this.fail(`Scoop "${this.deps.scoopName}" failed after 3 attempts: ${t}`,t)}async tryAgentPrompt(e,t,n,r){this.deps.beginAttempt();try{if(await e.prompt(t,n),this.deps.isDisposed()||r.aborted)return null;let i=this.deps.overflow.pendingRecovery;if(i!==null&&(await i,this.deps.overflow.clearPendingRecovery(i),this.deps.isDisposed()||r.aborted))return null;let a=this.deps.getStreamError();return a?Error(a):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handleAttemptError(e,t,n){let r=e.message;return this.handleStaleAssetError(r)||this.handleNonRetryableError(r)?!0:!await this.handleRetryableError(r,t,n)&&(j9.error(`Agent error`,{folder:this.deps.folder,error:r,attempt:t,isRetryable:Ub(r)}),!!(t<3&&(await Wb(M9(t),n)||this.deps.isDisposed())))}handleNonRetryableError(e){return Hb(e)?(j9.error(`Non-retryable agent error`,{folder:this.deps.folder,error:e}),this.fail(`Scoop "${this.deps.scoopName}" failed with unrecoverable error: ${e}`,e),!0):!1}handleStaleAssetError(e){return pa(e)?(j9.error(`Stale-asset import failure; requesting page reload`,{folder:this.deps.folder,error:e}),ga(this.deps.isInteractive),this.fail(`Scoop "${this.deps.scoopName}" hit a stale build after a deploy; reloading to recover.`,e),!0):!1}async handleRetryableError(e,t,n){if(!Ub(e)||t>=3)return!1;let r=M9(t);return j9.warn(`Retryable agent error, will retry`,{folder:this.deps.folder,error:e,attempt:t,maxRetries:3,delayMs:r}),!await Wb(r,n)&&!this.deps.isDisposed()}fail(e,t){ar(`llm`,t),this.deps.setStatus(`error`),this.deps.onFatalError?this.deps.onFatalError(e):this.deps.onError(t)}};function M9(e){return 1e3*2**(e-1)}function Tge(e,t,n,r){let i=e.state?.isStreaming??!1;if(r.isProcessing||i){j9.info(`Queueing prompt via ${r.steer?`steer`:`followUp`} while processing`,{folder:r.folder,isProcessing:r.isProcessing,agentIsStreaming:i});let a={role:`user`,content:[{type:`text`,text:t},...n],timestamp:Date.now()};return r.steer?e.steer(a):e.followUp(a),!0}return!1}const N9=r(`scoop-context`);var Ege=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;compactFn=null;getCompactionApiKey=null;coneJid;unit;owner;skillsFs=null;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;sessions;runBounds;bashJobs;imageRecovery;overflow;turnRunner;eventSink={textDelta:e=>{this.didStreamDeltas=!0,this.callbacks.onResponse(e,!0)},toolStart:(e,t,n)=>this.callbacks.onToolStart?.(e,t,n),toolUI:(e,t,n)=>this.callbacks.onToolUI?.(e,t,n),toolUIDone:e=>this.callbacks.onToolUIDone?.(e),toolProgress:(e,t,n)=>this.callbacks.onToolProgress?.(e,t,n),toolResult:(e,t,n,r)=>this.callbacks.onToolEnd?.(e,t,n,r),checkpoint:()=>this.sessions.schedule(),assistantMessageEnd:e=>this.handleAssistantMessageEnd(e),turnStart:()=>this.runBounds.enforceOnTurnStart(),turnCompleted:()=>this.runBounds.recordCompletedTurn(),responseDone:()=>this.callbacks.onResponseDone(),agentEnd:(e,t)=>this.handleAgentEndEvent(e,t)};constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.unit=Fh(e),this.owner={kind:vh(e),scoopJid:e.jid},this.callbacks=t,this.fs=n,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessions=new xge({store:r??null,sessionId:e.jid,folder:e.folder,getMessages:()=>this.agent?.state?.messages,isDisposed:()=>this.disposed,onRestoreError:e=>this.callbacks.onError(e)}),this.runBounds=new yx({getConfig:()=>this.scoop.config,isDisposed:()=>this.disposed,onTripped:()=>{this.setStatus(`error`),this.stop()}}),this.bashJobs=new Zb({processManager:this.processManager,cwd:this.unit.workspace.root,owner:this.owner,getTurnPid:()=>this.currentTurnProcess?.pid,folder:e.folder}),this.imageRecovery=new $b({getAgent:()=>this.agent,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onError:e=>this.callbacks.onError(e),folder:e.folder}),this.overflow=new vx({getAgent:()=>this.agent,isDisposed:()=>this.disposed,getTurnSignal:()=>this.promptAbortController?.signal,getCompactFn:()=>this.compactFn,getCompactionApiKey:()=>this.getCompactionApiKey?.(),isImageRecoveryActive:()=>this.imageRecovery.isActive,onResponse:(e,t)=>this.callbacks.onResponse(e,t),onExhausted:e=>this.reportExhaustedOverflow(e),setStatus:e=>this.setStatus(e),scoopName:e.name,folder:e.folder}),this.turnRunner=new wge({isDisposed:()=>this.disposed,overflow:this.overflow,beginAttempt:()=>{this.didStreamDeltas=!1,this.promptStreamErrorMessage=null},getStreamError:()=>this.promptStreamErrorMessage,setStatus:e=>this.setStatus(e),onError:e=>this.callbacks.onError(e),onFatalError:t.onFatalError?e=>this.callbacks.onFatalError?.(e):void 0,isInteractive:this.unit.completion.mode===`interactive`,scoopName:e.name,folder:e.folder})}ownLickTarget(){return rhe(this.unit,this.scoop,uh(this.callbacks.getScoops())[0]?.jid)}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}get isBusy(){return this.isProcessing||(this.agent?.state?.isStreaming??!1)}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);let e=await bge({scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,callbacks:this.callbacks,sessions:this.sessions,sudoManager:this.sudoManager,processManager:this.processManager,processOwner:this.owner,coneJid:this.coneJid,getTurnPid:()=>this.currentTurnProcess?.pid,getLickTarget:()=>this.ownLickTarget(),getEffortOverride:()=>this.activeEffortOverride,isDisposed:()=>this.disposed,onShellReady:e=>{this.shell=e},onStructuredOutput:e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0},spawnBashJob:e=>this.bashJobs.spawn(e)});if(e.kind===`abandoned`)return;if(e.kind===`deferred`){this.setStatus(`ready`);return}this.compactFn=e.compactFn,this.getCompactionApiKey=e.getCompactionApiKey,this.activeEffortOverride=e.effortOverride,this.agent=e.agent,this.unsubscribe=this.agent.subscribe((e,t)=>this.handleAgentEvent(e,t)),this.setStatus(`ready`),N9.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:e.toolCount})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);N9.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){return this.agent||(await this.init(),this.agent)?!0:(this.callbacks.onError(cx(this.scoop)),!1)}cleanupPromptState(e,t,n,r){this.runBounds.disarm();let i=this.runBounds.takeExceededNote();i!==null&&this.callbacks.onError(`agent run terminated: ${i}`),(n||r.aborted)&&this.sessions.persistNow(),this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),Cge(this.processManager,t,{lastError:n,aborted:r.aborted}),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async prompt(e,t=[],n){if(!await this.ensureAgentReady()||Tge(this.agent,e,t,{steer:n?.steer??!1,isProcessing:this.isProcessing,folder:this.scoop.folder}))return;let r=this.agent;this.promptAbortController?.abort();let i=new AbortController;this.promptAbortController=i;let a=i.signal;this.isProcessing=!0,this.setStatus(`processing`),this.overflow.resetForRun();let o=Sge(this.processManager,{text:e,cwd:this.unit.workspace.root,owner:this.owner,abortController:i});this.currentTurnProcess=o,this.runBounds.arm();let s=null;try{if(s=await this.turnRunner.run(r,e,t,a),s&&!this.disposed&&!a.aborted){this.turnRunner.reportExhausted(s);return}!this.disposed&&!a.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(i,o,s,a)}}stop(){A9(this.processManager,this.currentTurnProcess,`SIGINT`,this.promptAbortController),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.status!==`error`&&this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){return sx(this.agent?.state?.messages??[],this.scoop)}getSessionId(){return this.sessions.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){this.agent&&(this.activeEffortOverride=mx(this.agent,this.scoop))}async reloadSkills(){this.agent&&await gx(this.agent,{scoop:this.scoop,unit:this.unit,fs:this.fs,skillsFs:this.skillsFs,getGlobalMemory:()=>this.callbacks.getGlobalMemory()})}setThinkingLevel(e,t){return this.agent?fx()?this.agent.state.thinkingLevel:(this.activeEffortOverride=t,hx(this.agent,e)):`off`}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.sessions.persistNow(),this.disposed=!0,this.runBounds.disarm(),A9(this.processManager,this.currentTurnProcess,`SIGTERM`,this.promptAbortController),this.bashJobs.reapAll(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.compactFn=null,this.getCompactionApiKey=null,this.agent=null,this.shell=null,this.fs=null}handleAgentEvent(e,t){this.disposed||qb(e,this.eventSink,t)}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleAssistantMessageEnd(e){e.errorMessage||this.overflow.markAssistantSucceeded();let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}handleAgentEndEvent(e,t){this.disposed||t?.aborted||Gb(e,{imageRecovery:this.imageRecovery,overflow:this.overflow,isProcessing:()=>this.isProcessing,didStreamDeltas:()=>this.didStreamDeltas,latchStreamError:e=>{this.promptStreamErrorMessage=e},onError:e=>this.callbacks.onError(e),persist:e=>this.sessions.persistNow(e)},t)}reportExhaustedOverflow(e){this.unit.completion.mode===`interactive`?this.callbacks.onError(e):this.callbacks.onFatalError?this.callbacks.onFatalError(e):this.callbacks.onError(e)}};const P9=r(`scoop-lifecycle-manager`);var Dge=class{deps;units=new Map;constructor(e){this.deps=e}getUnit(e){return this.units.get(e)}ensureUnit(e){let t=this.units.get(e);return(!t||t.isClosed)&&(t=new Bb(e,{getScoop:e=>this.deps.getScoops().get(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,[],i),clearIdleTimer:e=>this.deps.idleTimers.clear(e),forgetCompletion:(e,t)=>this.deps.completionService.forgetScoop(e,t),unregister:e=>this.unregister(e)}),this.units.set(e,t)),t}getContexts(){let e=new Map;for(let[t,n]of this.units)n.context&&e.set(t,n.context);return e}getContext(e){return this.units.get(e)?.context??void 0}syncReadGrants(e){for(let t of this.deps.getScoops().values()){if(e!==void 0&&t.folder!==e)continue;let n=this.getContext(t.jid)?.getFS();this.applyPolicyReadGrants(t,n)}}getTab(e){return this.units.get(e)?.tab??void 0}observe(e,t){return this.ensureUnit(e).observe(t)}displayJidFor(e){let t=this.deps.approverFor(e)?.jid;return t&&t!==e?t:void 0}dispatch(e,t,...n){this.units.get(e)?.dispatch(t,...n)}parentOf(e){let t=this.deps.getScoops();return(e.parentJid===null?void 0:t.get(e.parentJid))??uh(t.values())[0]}rootOf(e){let t=this.deps.getScoops();return lh(t.values(),e)??uh(t.values())[0]}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){P9.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}applyPolicyReadGrants(e,t){if(!(t instanceof qn))return;let n=this.deps.getSudoManager()?.getPolicyForScoop(e.folder);n&&t.setReadGrants(n.read.filter(e=>e.nopasswd).map(e=>e.pattern))}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);let n=this.ensureUnit(e);if(n.context)if(n.tab?.status===`error`)P9.info(`Re-creating context after error`,{jid:e}),n.disposeContext();else{P9.debug(`Context already exists`,{jid:e});return}let r=this.deps.getSharedFs();if(!r)throw Error(`Shared filesystem not initialized`);let i=`scoop-${t.folder}-${Date.now()}`,a=Fh(t).policy.filesystem,o=a.kind===`full-workspace`?r:new qn(r,[...a.writablePaths],[...a.visiblePaths],`sudo-delegated`);a.kind===`restricted`&&(await this.ensureSudoersLoaded(t),this.applyPolicyReadGrants(t,o));let s=this.buildContextCallbacks(e,t),c=this.rootOf(t)?.jid,l=new Ege(t,s,o,this.deps.getSessionStore()??void 0,r??void 0,c,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());n.attachContext(l,i),await l.init(),n.tab?.status===`initializing`&&n.transition(`ready`)&&(this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`),Promise.resolve().then(()=>this.deps.messageRouter.flushOnIdle(e)).catch(t=>{P9.warn(`Initial idle queue probe failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}));let u=this.deps.getScoops().get(e);u&&u.parentJid!==null&&this.deps.idleTimers.start(e),P9.info(`Scoop context created`,{jid:e,contextId:i})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.units.get(e);t&&(t.teardown(),this.units.delete(e),P9.info(`Scoop context destroyed`,{jid:e}))}getTabsMap(){let e=new Map;for(let[t,n]of this.units)n.tab&&e.set(t,n.tab);return e}markTabError(e,t){let n=this.ensureUnit(e);n.transition(`error`,{contextId:n.tab?.contextId??`scoop-error-${e}`,error:t})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let e of this.units.values())e.detachContext()}async destroyAllTabs(){for(let e of Array.from(this.units.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.getTab(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return P9.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[],a){let o=this.getContext(e);o||=(await this.createTab(e),this.getContext(e));let s=this.units.get(e);if(s?.tab?.status===`initializing`){if(P9.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){P9.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}o=this.getContext(e)}if(!o||!s){P9.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),s.tab&&s.transition(`processing`)&&(this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),P9.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await o.prompt(t,i,a)}async register(e){let t=this.deps.getScoops();fh(e),this.inheritModel(e),await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),P9.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.parentJid!==null&&ir(`spawn`,e.folder)}catch(n){P9.error(`Scoop init failed`,{jid:e.jid,name:e.name,error:n instanceof Error?n.message:String(n)});try{this.destroyTab(e.jid)}catch(t){P9.warn(`Failed to destroy scoop runtime during init rollback`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}throw t.delete(e.jid),this.deps.messageRouter.forgetScoop(e.jid),await this.deps.db.deleteScoop(e.jid).catch(t=>{P9.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}inheritModel(e){if(xh(e))return;let t=e.parentJid?this.deps.getScoops().get(e.parentJid):void 0,n=(t?bh(t):void 0)??gb();n&&wh(e,n)}async unregister(e){let t=this.deps.getScoops(),n=t.get(e);if(n&&n.parentJid===null&&uh(t.values()).length<=1)throw Error(`Cannot drop the last cone`);let r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{P9.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{P9.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&P9.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),P9.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){P9.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}async setModel(e,t){let n=this.deps.getScoops().get(e);if(!n)return!1;let r=n.model;wh(n,t),this.getContext(e)?.updateModel();try{await this.deps.db.saveScoop(n)}catch(t){return wh(n,r),this.getContext(e)?.updateModel(),P9.warn(`Failed to persist unit model; rolled back`,{jid:e,error:t instanceof Error?t.message:String(t)}),!1}return!0}refreshModels(){let e=this.getContexts();for(let t of e.values())t.updateModel();P9.info(`Models re-resolved on all active contexts`,{contextCount:e.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.getContexts()){let r=this.getTab(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{P9.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),P9.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.getContext(e),a=i?i.setThinkingLevel(t,n):null;Th(r,t===void 0?void 0:{level:t,effortOverride:n});try{await this.deps.db.saveScoop(r)}catch(t){P9.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops(),{policy:o,completion:s}=Fh(t),c=s.mode!==`interactive`;return{onResponse:(t,i)=>{a().has(e)&&(n.onResponse(e,t,i),this.dispatch(e,`onResponse`,t,i),c&&(i?r.appendResponseChunk(e,t):r.setResponseFull(e,t)))},onResponseDone:()=>{a().has(e)&&(this.units.get(e)?.touch(),n.onResponseDone(e))},onError:r=>{a().has(e)&&(this.units.get(e)?.transition(`error`,{error:r}),ir(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`))},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:t=>{a().has(e)&&(this.units.get(e)?.transition(t),n.onStatusChange(e,t),this.dispatch(e,`onStatusChange`,t),t===`ready`&&this.deps.messageRouter.flushOnIdle(e),t===`ready`&&c&&r.notifyCompletion(e))},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r,i)=>{n.onToolStart?.(e,t,r,i)},onToolEnd:(t,r,i,a)=>{n.onToolEnd?.(e,t,r,i,a)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i,this.displayJidFor(e))},onToolUIDone:t=>{n.onToolUIDone?.(e,t,this.displayJidFor(e))},onToolProgress:(t,r,i)=>{n.onToolProgress?.(e,t,r,i)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:o.canManageChildren?e=>this.getTab(e):void 0,onFeedScoop:o.canManageChildren?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:o.canCreateChildren?async e=>{let n={...e,jid:`scoop_${e.folder}_${Date.now()}`,parentJid:t.jid};return await i.registerScoop(n),n}:void 0,onDropScoop:o.canManageChildren?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:o.canManageChildren?e=>i.muteScoops(e):void 0,onUnmuteScoops:o.canManageChildren?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:o.canManageChildren?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:o.canWriteSharedMemory?e=>i.setGlobalMemory(e):void 0,appendConeMemory:o.canWriteSharedMemory?(e,n)=>i.appendConeMemory(e,{...n,memoryPath:jh(t).memoryPath}):void 0,onSudoRequest:o.approvalAuthority===`user`?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:o.canResolveApprovals?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:o.canResolveApprovals?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);if(P9.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),ir(`error`,r.folder,t),this.units.get(e)?.transition(`error`,{error:t}),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),Fh(r).completion.mode===`interactive`)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let i=this.parentOf(r);if(!i)return;let a={id:`scoop-error-${e}-${Date.now()}`,chatJid:i.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(i.jid,a)}catch(e){P9.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(a).catch(e=>{P9.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const F9=r(`scoop-message-router`);var Oge=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;debounceStates=new Map;processing=new Map;busyDeferrals=new Map;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.cancelDebounce(e),this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e),this.clearBusyDeferral(e)}async handleMessage(e){if(F9.info(`handleMessage`,{id:e.id,chatJid:e.chatJid,sender:e.senderName,channel:e.channel,contentPreview:e.content.slice(0,80)}),this.deps.isExternalLickChannel(e.channel))try{this.deps.notifyIncomingMessage(e.chatJid,e)}catch(t){F9.warn(`onIncomingMessage for external lick channel threw`,{channel:e.channel,error:t instanceof Error?t.message:String(t)})}await this.deps.db.saveMessage(e),await this.routeToScoop(e)}async delegateToScoop(e,t,n){let r=this.deps.getScoops().get(e);if(!r)throw Error(`Scoop not found: ${e}`);ir(`feed`,r.folder);let i={id:`delegate-${Date.now()}-${Math.random().toString(36).slice(2)}`,chatJid:e,senderId:`cone`,senderName:n,content:t,timestamp:new Date().toISOString(),fromAssistant:!0,channel:`delegation`};await this.deps.db.saveMessage(i),this.deps.notifyIncomingMessage(e,i),F9.info(`Delegating to scoop`,{scoopJid:e,scoopName:r.name,promptLength:t.length}),this.deps.sendPrompt(e,t,`cone`,n).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Delegation failed`,{scoopJid:e,error:n}),this.deps.onError(e,`Delegation failed: ${n}`)})}async routeToScoop(e){let t=this.deps.getScoops().get(e.chatJid);if(!t){F9.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}if(!this.passesTriggerGate(t,e)){F9.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let n=this.messageQueues.get(e.chatJid)??[];n.push(e),this.messageQueues.set(e.chatJid,n);let r=this.deps.getTabs().get(e.chatJid);if(F9.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:r?.status??`no-tab`,queueLength:n.length}),r?.status===`error`){F9.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),r=this.deps.getTabs().get(e.chatJid)}catch{F9.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}if(r?.status===`ready`||r?.status===`processing`){if(this.deps.isExternalLickChannel(e.channel)){await this.scheduleScoopQueue(e.chatJid,e.id);return}await this.flushScoopQueue(e.chatJid)}}passesTriggerGate(e,t){let n=t.channel===`webhook`||t.channel===`cron`||t.channel===`fswatch`||t.channel===`sprinkle`||t.channel===`bash`;return!e||e.parentJid===null||!e.requiresTrigger||!e.trigger||n||t.content.includes(e.trigger)}scheduleScoopQueue(e,t){let n=this.debounceStates.get(e)??{startedAt:Date.now(),waiters:[]};n.timer!==void 0&&clearTimeout(n.timer);let r=new Promise((e,r)=>{n.waiters.push({messageId:t,resolve:e,reject:r})}),i=Math.max(0,3e3-(Date.now()-n.startedAt));return n.timer=setTimeout(()=>{n.timer=void 0,this.flushScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);F9.error(`Debounced message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},Math.min(1e3,i)),this.debounceStates.set(e,n),r}async flushScoopQueue(e){let t=this.takeDebounce(e);if(t&&this.processing.has(e)&&this.shouldDeferQueuedLicks(e)){for(let e of t.waiters)e.resolve();this.recordBusyDeferral(e,this.messageQueues.get(e)?.length??0);return}try{await this.processScoopQueue(e);for(let e of t?.waiters??[])e.resolve()}catch(e){for(let n of t?.waiters??[])n.reject(e);throw e}}async flushOnIdle(e){if(this.messageQueues.has(e))try{await this.flushScoopQueue(e)}catch(t){let n=t instanceof Error?t.message:String(t);F9.error(`Idle message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)}}shouldDeferQueuedLicks(e){let t=this.messageQueues.get(e);return t!==void 0&&t.length>0&&t.every(e=>this.deps.isExternalLickChannel(e.channel))}recordBusyDeferral(e,t){let n=this.busyDeferrals.get(e)??{startedAt:Date.now(),reported:!1,count:t??0};t!==void 0&&(n.count=t),this.busyDeferrals.set(e,n);let r=Date.now()-n.startedAt;if(n.reported||r<3e5)return;n.reported=!0;let i=`Lick queue remained deferred while scoop was busy for ${3e5/1e3}s`;F9.warn(`Busy lick queue may be starved`,{jid:e,error:i}),this.emitLickBackpressure(e,{count:n.count,waitingMs:r})}clearBusyDeferral(e){let t=this.busyDeferrals.get(e);this.busyDeferrals.delete(e),t?.reported&&this.emitLickBackpressure(e,{count:0,waitingMs:Date.now()-t.startedAt})}emitLickBackpressure(e,t){try{this.deps.onLickBackpressure?.(e,t)}catch(t){F9.warn(`Lick backpressure callback failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}}takeDebounce(e){let t=this.debounceStates.get(e);return t?.timer!==void 0&&clearTimeout(t.timer),this.debounceStates.delete(e),t}cancelDebounce(e){let t=this.takeDebounce(e);for(let e of t?.waiters??[])e.resolve()}cancelDebounces(){for(let e of this.debounceStates.keys())this.cancelDebounce(e)}cancelDebounceWaiter(e,t){let n=this.debounceStates.get(e);if(!n)return;let r=[];for(let e of n.waiters)e.messageId===t?e.resolve():r.push(e);n.waiters=r,r.length===0&&this.cancelDebounce(e)}async processScoopQueue(e){let t=this.processing.get(e);if(t){t.rerun=!0,await t.done.catch(()=>{});return}let n={rerun:!1,done:Promise.resolve()};return this.processing.set(e,n),n.done=this.drainScoopQueue(e,n),n.done}async drainScoopQueue(e,t){let n=!1,r;try{do{t.rerun=!1;try{await this.runScoopQueue(e)}catch(e){n||(n=!0,r=e)}}while(t.rerun)}finally{this.processing.delete(e)}if(n)throw r}async runScoopQueue(e){let t=this.messageQueues.get(e);if(!t){F9.debug(`processScoopQueue: queue not registered`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`&&n?.status!==`processing`){F9.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i),s=o.filter(e=>this.passesTriggerGate(r,e));if(F9.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,eligibleMessageCount:s.length,queueLength:t.length}),o.length===0){F9.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);return}if(s.length===0){F9.debug(`processScoopQueue: no messages passed trigger gate, clearing queue`,{jid:e}),this.messageQueues.set(e,[]),this.clearBusyDeferral(e);let t=_n(An(xn(a),o));this.lastAgentTimestamp.set(e,t),await this.deps.db.setState(`lastAgentTs_${e}`,t);return}if(s.every(e=>this.deps.isExternalLickChannel(e.channel))&&this.deps.getContexts().get(e)?.isBusy){F9.debug(`processScoopQueue: deferring lick batch while scoop is busy`,{jid:e,messageCount:s.length}),this.recordBusyDeferral(e,s.length);return}this.clearBusyDeferral(e);let c=s.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${Qm(e.content,e.attachments)}`).join(`
|
|
5224
|
+
`),l=s.flatMap(e=>$m(e.attachments));this.messageQueues.set(e,[]);let u=s[s.length-1],d=_n(An(xn(a),o));this.lastAgentTimestamp.set(e,d),await this.deps.db.setState(`lastAgentTs_${e}`,d);let f=s.some(e=>e.steer);await this.deps.sendPrompt(e,c,u.senderId,u.senderName,l,{steer:f})}startMessageLoop(){this.pollInterval||=setInterval(()=>{let e=this.deps.getTabs();for(let t of this.deps.getScoops().keys()){let n=e.get(t);this.recordBusyDeferralIfPresent(t);let r=(this.messageQueues.get(t)?.length??0)>0;n?.status===`ready`&&r&&!this.debounceStates.has(t)&&this.processScoopQueue(t).catch(e=>{let n=e instanceof Error?e.message:String(e);F9.error(`Message queue processing failed`,{jid:t,error:n}),this.deps.onError(t,`Queue processing failed: ${n}`)})}},2e3)}recordBusyDeferralIfPresent(e){this.busyDeferrals.has(e)&&this.recordBusyDeferral(e)}stopMessageLoop(){this.cancelDebounces(),this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(this.cancelDebounce(e),t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{F9.warn(`Failed to clear agent session for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})})}}await this.deps.db.clearMessagesForScoop(e).catch(t=>{F9.warn(`Failed to clear persisted channel history for scoop`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.lastAgentTimestamp.delete(e),this.messageQueues.set(e,[]),this.clearBusyDeferral(e),F9.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){this.cancelDebounces(),await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{F9.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.busyDeferrals.keys())this.clearBusyDeferral(e);for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),F9.info(`All messages cleared`)}async clearQueuedMessages(e){this.cancelDebounce(e);let t=this.messageQueues.get(e)??[],n=this.deps.getScoops().get(e)?.assistantLabel??e,r=this.lastAgentTimestamp.get(e)??``,i=await this.deps.db.getMessagesSince(e,r,n),a=new Set([...t,...i].map(e=>e.id));for(let e of a)await this.deps.db.deleteMessage(e);this.messageQueues.set(e,[]),this.clearBusyDeferral(e)}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let r=n.findIndex(e=>e.id===t);r!==-1&&n.splice(r,1),n.length===0&&this.clearBusyDeferral(e)}this.cancelDebounceWaiter(e,t),await this.deps.db.deleteMessage(t)}};const I9=r(`orchestrator`);var kge=class{scoops=new Map;workUnits=new xre(this);container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new lb({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;llmsTxtIgnorePolicy=null;modelPolicyFile=null;lifecycle;idleTimers=new Lb({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),findParent:e=>this.parentOrDefaultRoot(e),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Fb({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new kb({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findParent:e=>this.parentOrDefaultRoot(e),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;unregisterExportService=null;approvalRouter=new xb({getScoops:()=>this.scoops,findApprover:e=>this.parentOrDefaultRoot(e),getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>Tn(e),saveMessage:e=>vn(e)});lickRegistry=new fb({getConeShell:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},getConeFs:()=>{let e=this.defaultRoot();return e?this.lifecycle.getContext(e.jid)?.getFS()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new Oge({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i??[],a),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),onLickBackpressure:(e,t)=>this.callbacks.onLickBackpressure?.(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>vn(e),deleteMessage:e=>bn(e),clearMessagesForScoop:e=>On(e),clearAllMessages:()=>En(),getMessagesSince:(e,t,n)=>wn(e,t,n),setState:(e,t)=>gn(e,t)},isExternalLickChannel:wg});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new Dge({getScoops:()=>this.scoops,approverFor:e=>this.ownerRootOrDefault(e),getSharedFs:()=>this.sharedFs,getSessionStore:()=>this.sessionStore,getProcessManager:()=>this.processManager,getSudoManager:()=>this.sudoManager,callbacks:this.callbacks,idleTimers:this.idleTimers,completionService:this.completionService,db:{saveScoop:e=>hn(e),deleteScoop:e=>Dn(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>xee(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e),flushOnIdle:e=>this.messageRouter.flushOnIdle(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(e){await Nn(),this.sharedFs=await _b(()=>Kn.create({dbName:`slicc-fs`}),e),this.sessionStore=new nh,this.fsWatcher=new Cee,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new H_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy=new d_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile=new hb(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init();let t=await jn(),n=Object.values(t).find(e=>dh(e))?.jid;for(let e of Object.values(t)){await this.backfillParent(e,n),fh(e),this.migrateScoopConfig(e,Object.values(t)),this.scoops.set(e.jid,e),this.messageRouter.ensureQueue(e.jid);let r=await Cn(`lastAgentTs_${e.jid}`);r&&this.messageRouter.setLastAgentTimestamp(e.jid,r)}await this.backfillModels(),await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new yb({onTaskRun:async(e,t)=>{I9.info(`Running scheduled task`,{taskId:e.id,scoop:t.name}),await this.sendPrompt(t.jid,`[SCHEDULED TASK]\n\n${e.prompt}`,`scheduler`,`Scheduled Task`)},getScoop:e=>{for(let t of this.scoops.values())if(t.folder===e)return t}}),this.scheduler.start(),I9.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let t of this.scoops.values())try{await this.createScoopTab(t.jid)}catch(e){let n=e instanceof Error?e.message:String(e);I9.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:t.jid,folder:t.folder,root:t.parentJid===null,error:n}),t.parentJid!==null&&this.lifecycle.markTabError(t.jid,n)}finally{e?.(`scoop-restored:${t.jid}`)}Eee(e=>this.getSessionCostsForCommand(e)),this.unregisterExportService=W_(this.buildWorkerExportService()),this.messageRouter.startMessageLoop()}async backfillParent(e,t){if(e.parentJid===void 0){e.parentJid=dh(e)?null:t??null;try{await hn(e)}catch(t){I9.warn(`Failed to persist backfilled parentJid; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}async backfillModels(){let e=[...this.scoops.values()].filter(e=>!xh(e));if(e.length===0)return;let t=gb(),n=[...e].sort((e,t)=>Number(e.parentJid!==null)-Number(t.parentJid!==null));for(let e of n){let n=e.parentJid?this.scoops.get(e.parentJid):void 0,r=(n?bh(n):void 0)??t;if(r){wh(e,r);try{await hn(e)}catch(t){I9.warn(`Failed to persist backfilled model; will retry next boot`,{jid:e.jid,error:t instanceof Error?t.message:String(t)})}}}}migrateScoopConfig(e,t){if(e.parentJid===null)return;let n=e.configSchemaVersion??0;if(!(n>=3)){if(n<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),n<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),n<3){let n=`${Mh.root}/`,r=Ph(Nh(t,e)),i=e.config?.visiblePaths,a=i?.length===1&&i[0]===n;r[0]!==n&&a&&(e.config={...e.config,visiblePaths:r})}e.configSchemaVersion=3}}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/home/user`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),e.setScoopExistenceResolver(e=>this.getScoops().some(t=>yee(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}registerDiscoveryLick(e){return this.lickRegistry.registerDiscovery(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}getScoopTabState(e){return this.lifecycle.getTab(e)}defaultRoot(){return uh(this.scoops.values())[0]}parentOrDefaultRoot(e){let t=e===void 0?void 0:this.scoops.get(e);return(t?.parentJid?this.scoops.get(t.parentJid):void 0)??this.defaultRoot()}ownerRootOrDefault(e){let t=e===void 0?void 0:this.scoops.get(e);return lh(this.scoops.values(),t)??this.defaultRoot()}getWorkUnits(){return this.workUnits}getLiveUnit(e){return this.lifecycle.getUnit(e)}ensureLiveUnit(e){return this.lifecycle.ensureUnit(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await Kn.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await ib(this.sharedFs).catch(e=>{I9.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new H_({fs:this.sharedFs,watcher:this.fsWatcher,onPolicyReload:e=>this.lifecycle.syncReadGrants(e)}),await this.sudoManager.init(),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=new d_(this.sharedFs,this.fsWatcher),await this.llmsTxtIgnorePolicy.init(),this.modelPolicyFile?.dispose(),this.modelPolicyFile=new hb(this.sharedFs,this.fsWatcher),await this.modelPolicyFile.init(),this.lickManager?.setDiscoveryIgnore?.(e=>this.llmsTxtIgnorePolicy?.ignores(e)??!1),this.costTracker.reset(),I9.info(`Filesystem reset and defaults re-seeded`)}clearScoopMessages(e){return this.messageRouter.clearScoopMessages(e,this.lifecycle.getContext(e))}clearAllMessages(){return this.messageRouter.clearAllMessages()}handleMessage(e){return this.messageRouter.handleMessage(e)}delegateToScoop(e,t,n){return this.messageRouter.delegateToScoop(e,t,n)}createScoopTab(e){return this.lifecycle.createTab(e)}async destroyScoopTab(e){this.lifecycle.destroyTab(e)}isProcessing(e){return this.lifecycle.getTab(e)?.status===`processing`}getScoopContext(e){return this.lifecycle.getContext(e)}clearQueuedMessages(e){return this.messageRouter.clearQueuedMessages(e)}deleteQueuedMessage(e,t){return this.messageRouter.deleteQueuedMessage(e,t)}async getMessagesForScoop(e){return Tn(e)}sendPrompt(e,t,n,r,i=[],a){return this.lifecycle.sendPrompt(e,t,n,r,i,a)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}setScoopModel(e,t){return this.lifecycle.setModel(e,t)}refreshModels(){this.lifecycle.refreshModels()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(e){return this.costTracker.getSessionCosts(e)}async getSessionCostsForCommand(e){let t=this.getSessionCosts({includeDropped:e===`all`});if(e===`live`||!this.sharedFs)return t;let{readSessionsIndex:n}=await import(`./frozen-archive-format-CLzdz05B.js`).then(e=>e.t),r=await n(this.sharedFs);return[...t,...r.map(Oee)]}getModelCosts(e){return this.costTracker.getModelCosts(e)}getBurnRate(e){return this.costTracker.getBurnRate(e)}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&I9.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.lickManager?.setDiscoveryIgnore?.(null),this.llmsTxtIgnorePolicy?.dispose(),this.llmsTxtIgnorePolicy=null,this.modelPolicyFile?.dispose(),this.modelPolicyFile=null,this.sudoManager?.dispose(),this.sudoManager=null,this.unregisterExportService?.(),this.unregisterExportService=null,I9.info(`Orchestrator shutdown`)}buildWorkerExportService(){let e=new bg,t=this.sharedFs;return new my({collection:{listScoops:()=>this.getScoops(),isProcessing:e=>this.isProcessing(e),getAgentMessages:e=>this.getScoopContext(e)?.getAgentMessages()??null,loadPersistedSessions:()=>this.sessionStore?.loadAll()??Promise.resolve([]),loadUiChatSessions:async()=>{let t=await e.list();return(await Promise.all(t.map(t=>e.load(t)))).filter(e=>e!==null)},wait:e=>new Promise(t=>setTimeout(t,e))},knownSecrets:My(),snapshotStore:{read:e=>Ty(t,e),write:(e,n)=>wy(t,e,n)},vfs:t,getActiveSessionInfo:()=>{let e=this.defaultRoot();return{id:e?.jid??`session-${Date.now()}`,title:e?.name??`Active Session`}},version:`6.91.0`})}};const L9=r(`workflow-run-manager`),R9=`/shared/workflow-runs`,z9=1e3;function Age(e,t){if(t===void 0)return{origin:`terminal`};let n=e.getStartingRoot(t);return n?{origin:`cone`,lickTarget:n.lickTarget}:{origin:`scoop`}}function jge(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=(e,n)=>Ige(e,n,t,()=>r(n));async function a(a){let c=a.runId??e.makeRunId(),l=a.sentinel,u=Age(e,a.parentJid),d={id:c,name:a.name,source:a.source,origin:u.origin,lickTarget:u.lickTarget,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(c,d),Pge(t,n);let f=i(a.ctx,c),p=Fge(e.processManager,d,c,()=>r(c));return e.runRealm(a.code,[`workflow`,a.filename,c],f).then(e=>o(c,l,e)).catch(e=>s(c,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>L9.warn(`workflow run lifecycle error`,e)),{runId:c}}async function o(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?c(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?c(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):c(t,`done`,i,null)}function s(e,t){return c(e,`error`,null,t)}async function c(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${R9}/${n}.json`,u=new Date().toISOString();try{await e.sharedFs.mkdir(R9,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:u},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=u,s.preview=i===`done`?Nge(a):o??``,r(n),l(s)}function l(t){t.origin===`cone`&&e.fireLick({type:`workflow`,targetScoop:t.lickTarget,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:a,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 Mge(e){let t=jge(e);return globalThis[J7]=t,L9.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function Nge(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function Pge(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 Fge(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 Ige(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?Lge(n,t,a?.args??[],r):e===`agent`?Rge(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function Lge(e,t,n,r){let i=e.get(t);if(i&&i.status===`running`){let[e,t=``]=n;e===`phase`?(i.currentPhase=t,i.logs.push(t)):e===`log`&&i.logs.push(t),i.logs.length>z9&&i.logs.splice(0,i.logs.length-z9),r()}return{stdout:``,stderr:``,exitCode:0}}async function Rge(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}var zge=class{kind=`proc`;source=void 0;profile=void 0;mountId;pm;closed=!1;constructor(e,t={}){this.pm=e,this.mountId=t.mountId??`proc-${Date.now().toString(36)}`}async readDir(e){this.assertOpen(e);let t=V9(e);if(t.length===0){let e=this.pm.list(),t=e.map(e=>({name:String(e.pid),kind:`directory`}));return e.some(e=>e.pid===1)||t.push({name:`1`,kind:`directory`}),t.sort((e,t)=>Number(e.name)-Number(t.name))}if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return B9.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new $t(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=V9(e);if(t.length!==2)throw new $t(`EISDIR`,`is a directory`,e);let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=V9(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=H9(t[0]);if(n===null||!this.pidExists(n))throw new $t(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!B9.includes(r))throw new $t(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new $t(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new $t(`EACCES`,`read-only filesystem`,e)}async refresh(){return{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:`/proc`,extra:`kernel processes (read-only)`}}async close(){this.closed=!0}assertOpen(e){if(this.closed)throw new $t(`EBADF`,`mount closed`,e)}pidExists(e){return e===1||this.pm.get(e)!==null}fileSize(e,t){return this.renderProcFile(e,t).length}fileMtime(e){if(e===1)return 0;let t=this.pm.get(e);return t?t.finishedAt??t.startedAt:0}renderProcFile(e,t){if(e===1)return Gge(t);let n=this.pm.get(e);switch(t){case`status`:return Bge(n);case`cmdline`:return Vge(n);case`cwd`:return Hge(n);case`stat`:return Uge(n)}}};const B9=[`status`,`cmdline`,`cwd`,`stat`];function V9(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function H9(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function Bge(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${U9(e.status)} (${e.status})`,`Owner:\t${Wge(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(`
|
|
5225
5225
|
`)+`
|
|
5226
5226
|
`}function Vge(e){return e.argv.join(`\0`)+`\0`}function Hge(e){return e.cwd+`
|
|
5227
5227
|
`}function Uge(e){return[e.pid,`(${e.kind})`,U9(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
@@ -5229,5 +5229,5 @@ pass --wait to block and print the full result.
|
|
|
5229
5229
|
`)+`
|
|
5230
5230
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
5231
5231
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
5232
|
-
`}}function Kge(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(eV(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(!YB(n.token))return;let a=i.get(n.id);if(a){r({type:tV,id:n.id}),a.result&&r({type:nV,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:tV,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:nV,id:n.id,...e})};(oV(n)?lV(n):$B(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function W9(){return globalThis}function qge(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Jge(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function Yge(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Xge(e,t)}function Xge(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=e.targetScoop?Ca(r,e.targetScoop):uh(r)[0];if(!i){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Kre(i)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:i.folder});return}e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let a=Rg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=qge(e),s=Jge(e),c=e.type,l={id:`${c}-${s}-${Date.now()}`,chatJid:i.jid,senderId:c,senderName:`${c}:${o}`,content:a.content,timestamp:e.timestamp,fromAssistant:!1,channel:c,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l).catch(e=>{n.warn(`Lick message routing failed`,{channel:c,eventName:o,error:String(e)})})}async function Zge(e,t,n,r,i){let a=new vr,o=new kge(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,SG(wG()),W9().__slicc_browser=t,await n.bind(o,t);let s=
|
|
5233
|
-
`,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 n_e(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CnkYvHKI.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 r_e(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 Vre(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})},i_e(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function i_e(e){let t=p();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>Hre()}}function a_e(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-DjDqX7zc.js`).then(e=>e.n),{mountConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-CdyPAwVL.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function o_e(){Rn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-BmshpeMo.js`);return e()})}function s_e(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-BmshpeMo.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 c_e(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-BM2oq7W2.js`),{ScriptCatalog:r}=await import(`./script-catalog-Bt94D0RP.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function l_e(){return pt()}async function u_e(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);o_e();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Zge(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?sg(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new zge(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Qge(l,e,o);s(`lick-manager-ready`),f&&e_e({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await t_e({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;l_e()&&(g=await n_e(p,o,e.localLickWsUrl??null));let _=r_e(n,p,o);f&&a_e(f,p,o),a||await $ge(l),s(`cone-bootstrapped`),f&&s_e(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await c_e(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Kge({nonce:e.syncFsChannelNonce}).dispose);let x=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){x||(x=!0,await d_e({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,syncFsResponderDispose:b,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:o}))}}}async function d_e(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)}f_e({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function f_e(e){let t=W9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,SG(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[J7]}const G9=`x-bypass-llm-proxy`;function p_e(e,t,n){return t?(r,i)=>{if(!m_e(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 m_e(e,t,n){if(g_e(e,t))return!0;let r=n?.()??null;return r?h_e(e,r,t):!1}function h_e(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 g_e(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 __e(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 v_e=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(!y_e(e)||e.source!==`panel`)return;let t=e.payload;b_e(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=_G(l(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,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 y_e(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 b_e(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 x_e=class extends c9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function S_e(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new v_e({transport:t,processManager:i,createShell:(a,o)=>new x_e(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??pt,getLeaderStatus:e.webhook?.getLeaderStatus??ln},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function C_e(e){let t=new w_e(e);return t.start(),{stop:()=>t.dispose()}}var w_e=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(!T_e(e)||e.source!==`panel`)return;let t=e.payload;if(E_e(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(D_e(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new $t(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new $t(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(O_e(e.type),e.requestId,new $t(`EACCES`,`vfs-rpc-host has no writable backend wired`),k_e(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new $t(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new $t(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new $t(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function T_e(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function E_e(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 D_e(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 O_e(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 k_e(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof $t?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function A_e(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=p_e(e.bind(globalThis),t,j_e)}function j_e(){let e=lee();if(!e)return null;try{return new URL(e).origin}catch{return null}}function M_e(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 N_e=__e(e=>I_e(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&N_e.handle(e.data)});function P_e(e){let t=va(e.pageBuildId,`6.90.0-mt767keb`);return()=>{t&&qee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.90.0-mt767keb`)}}function F_e(e){A_e(),uee(e.localApiBaseUrl??null),oee(e.bridgeToken??null),fG(e.syncFsBridgeEnabled??!1),cee(e.extensionDelegateId??null),M_e(e.localStorageSeed??{}),e.flagFloat&&oa(e.flagFloat)}async function I_e(e){ha(e.instanceId);let t=P_e(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{F_e(e),Yee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=xa(e.kernelPort),a=new n_(r),o=n_.createCallbacks(a),c=new Sa(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new nte(c);Y9=await u_e({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(ate(i));let m=await R_e({host:Y9,transport:r,browser:l,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){L_e(e.kernelPort,t)}}function L_e(e,t){_a(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function R_e(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=S_e({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=C_e({transport:e.transport,client:t,writableClient:t,logger:console}),i=await z_e(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function z_e(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CKwQ54O1.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-Co-pb0x0.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|
|
5232
|
+
`}}function Kge(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(eV(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(!YB(n.token))return;let a=i.get(n.id);if(a){r({type:tV,id:n.id}),a.result&&r({type:nV,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:tV,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),605e3),r({type:nV,id:n.id,...e})};(oV(n)?lV(n):$B(n)).then(s).catch(e=>s({ok:!1,errno:`EIO`,message:e instanceof Error?e.message:String(e)}))};return n.addEventListener(`message`,a),{dispose:()=>{n.removeEventListener(`message`,a);for(let e of i.values())e.timer&&clearTimeout(e.timer);i.clear(),t&&n.close?.()}}}function W9(){return globalThis}function qge(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`bash`:return e.bashJobId??`bash`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Jge(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`bash`:return`bash-${e.bashJobId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function Yge(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}Xge(e,t)}function Xge(e,{orchestrator:t,log:n}){let r=t.getScoops(),i=e.targetScoop?Ca(r,e.targetScoop):uh(r)[0];if(!i){n.warn(`Lick target scoop not found`,e.targetScoop);return}if(e.type===`discovery`&&!Kre(i)){n.debug?.(`dropping discovery lick for non-browsing scoop`,{scoop:i.folder});return}e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`?e.lickId=t.registerUpgradeLick(e):e.type===`discovery`&&(e.lickId=t.registerDiscoveryLick(e)??void 0);let a=Rg(e);if(a===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let o=qge(e),s=Jge(e),c=e.type,l={id:`${c}-${s}-${Date.now()}`,chatJid:i.jid,senderId:c,senderName:`${c}:${o}`,content:a.content,timestamp:e.timestamp,fromAssistant:!1,channel:c,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l).catch(e=>{n.warn(`Lick message routing failed`,{channel:c,eventName:o,error:String(e)})})}async function Zge(e,t,n,r,i){let a=new vr,o=new kge(e,{...r,getBrowserAPI:()=>t});o.setProcessManager(a),W9().__slicc_pm=a,SG(wG()),W9().__slicc_browser=t,await n.bind(o,t);let s=fn(()=>n.emitTrayRuntimeStatus()),c=kre(()=>n.emitTrayRuntimeStatus());return await o.init(i),await n.seedBuffersFromAgentState(),{processManager:a,orchestrator:o,unsubLeader:s,unsubFollower:c,sharedFs:o.getSharedFS()}}async function Qge(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Be2VSQE-.js`).then(e=>e.t);r(t=>e.getSessionCostsForCommand(t));let{getLickManager:i}=await import(`./lick-manager-DFmMezV-.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??Yge,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function $ge(e){uh(e.getScoops()).length>0||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,parentJid:null,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function e_e(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;Mge({sharedFs:i,getStartingRoot:e=>{let n=uh(t.getScoops()),r=n.find(t=>t.jid===e);return r?{jid:r.jid,lickTarget:r.jid===n[0]?.jid?void 0:r.folder}:null},fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>EG(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>Y7().slice(10,22),splitResult:(e,t)=>X7(e,t)})}async function t_e(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-CKHqIv8e.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
|
|
5233
|
+
`,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 n_e(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-CnkYvHKI.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 r_e(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 Vre(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})},i_e(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function i_e(e){let t=p();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,discoverySource:`live-navigation`,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>Hre()}}function a_e(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-DrF_Ifaz.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-BsWQfSkJ.js`).then(e=>e.n),{mountConfiguredHostMounts:a,withoutHostMountedTargets:o}=await import(`./auto-mount-table-CdyPAwVL.js`),s=await a(e,n),c=o(await r(),s);if(c.length===0)return;let{needsRecovery:l}=await i(c,e,n);if(l.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:l}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function o_e(){zn(async()=>{let{getLastSeenVersion:e}=await import(`./upgrade-detection-CW8nHgbA.js`);return e()})}function s_e(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-CW8nHgbA.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 c_e(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-BM2oq7W2.js`),{ScriptCatalog:r}=await import(`./script-catalog-Bt94D0RP.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function l_e(){return pt()}async function u_e(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,s=t=>e.onBootProgress?.(t);o_e();let{processManager:c,orchestrator:l,unsubLeader:u,unsubFollower:d,sharedFs:f}=await Zge(t,n,r,i,e.onBootProgress);if(s(`orchestrator-ready`),f?sg(l,f,l.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),f)try{await f.mountInternal(`/proc`,new zge(c))}catch(e){o.warn(`Failed to mount /proc`,e)}let p=await Qge(l,e,o);s(`lick-manager-ready`),f&&e_e({orchestrator:l,processManager:c,lickManager:p,sharedFs:f}),W9().__slicc_lickManager=p;let{wsBridge:m,wsRegistry:h}=await t_e({browser:n,lickManager:p,orchestrator:l,sharedFs:f,log:o});W9().__slicc_wsSubscribers=h;let g=null;l_e()&&(g=await n_e(p,o,e.localLickWsUrl??null));let _=r_e(n,p,o);f&&a_e(f,p,o),a||await $ge(l),s(`cone-bootstrapped`),f&&s_e(p,o);let v=null,y=null;f&&({bshWatchdogStop:v,scriptCatalogDispose:y}=await c_e(f,n,o));let b=null;f&&e.syncFsChannelNonce&&(b=Kge({nonce:e.syncFsChannelNonce}).dispose);let x=!1;return{orchestrator:l,browser:n,bridge:r,lickManager:p,sharedFs:f??null,processManager:c,async dispose(){x||(x=!0,await d_e({unsubLeader:u,unsubFollower:d,bshWatchdogStop:v,scriptCatalogDispose:y,lickWsBridgeStop:g,navigationWatcherStop:_,syncFsResponderDispose:b,sharedFs:f,wsRegistry:h,wsBridge:m,processManager:c,lickManager:p,browser:n,log:o}))}}}async function d_e(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)}f_e({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function f_e(e){let t=W9();t.__slicc_pm===e.processManager&&(delete t.__slicc_pm,SG(null)),t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[J7]}const G9=`x-bypass-llm-proxy`;function p_e(e,t,n){return t?(r,i)=>{if(!m_e(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 m_e(e,t,n){if(g_e(e,t))return!0;let r=n?.()??null;return r?h_e(e,r,t):!1}function h_e(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 g_e(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 __e(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 v_e=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(!y_e(e)||e.source!==`panel`)return;let t=e.payload;b_e(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n,t.shell.applySessionOverrides?.({cwd:e.cwd,env:e.env});let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=``;if(e.stdin)try{i=_G(l(e.stdin))}catch{this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec with invalid stdin (expected base64)`,e.sid);return}let a=await t.shell.executeCommand(e.command,n.signal,r?.pid,i);await this.emitExecSuccess(e,a,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 y_e(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 b_e(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 x_e=class extends c9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function S_e(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new v_e({transport:t,processManager:i,createShell:(a,o)=>new x_e(a,t,{fs:n,cwd:o.cwd,env:o.env,browserAPI:r,webhook:{hasLocalNodeServer:e.webhook?.hasLocalNodeServer??pt,getLeaderStatus:e.webhook?.getLeaderStatus??un},processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function C_e(e){let t=new w_e(e);return t.start(),{stop:()=>t.dispose()}}var w_e=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(!T_e(e)||e.source!==`panel`)return;let t=e.payload;if(E_e(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(D_e(t)){this.handleWriteRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] write handler unexpectedly threw`,e)});return}})}dispose(){this.unsubscribe?.(),this.unsubscribe=null}async handleRequest(e){switch(e.type){case`vfs-read-dir`:return this.handleReadDir(e);case`vfs-read-file`:return this.handleReadFile(e);case`vfs-stat`:return this.handleStat(e)}}async handleReadDir(e){try{let t=await this.client.readDir(e.path),n={type:`vfs-read-dir-result`,requestId:e.requestId,ok:!0,entries:t};this.transport.send(n)}catch(t){this.emitError(`vfs-read-dir-result`,e.requestId,t,e.path)}}async handleReadFile(e){let t=e.encoding??`utf-8`;try{let n=await this.client.readFile(e.path,{encoding:t});if(t===`binary`){if(!(n instanceof Uint8Array)){this.emitError(`vfs-read-file-result`,e.requestId,new $t(`EIO`,`readFile(binary) did not return Uint8Array`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`binary`,data:n},r=n.buffer,i=typeof ArrayBuffer<`u`&&r instanceof ArrayBuffer?[r]:void 0;this.transport.send(t,i)}else{if(typeof n!=`string`){this.emitError(`vfs-read-file-result`,e.requestId,new $t(`EIO`,`readFile(utf-8) did not return string`),e.path);return}let t={type:`vfs-read-file-result`,requestId:e.requestId,ok:!0,encoding:`utf-8`,data:n};this.transport.send(t)}}catch(t){this.emitError(`vfs-read-file-result`,e.requestId,t,e.path)}}async handleStat(e){try{let t=await this.client.stat(e.path),n={type:`vfs-stat-result`,requestId:e.requestId,ok:!0,stats:t};this.transport.send(n)}catch(t){this.emitError(`vfs-stat-result`,e.requestId,t,e.path)}}async handleWriteRequest(e){if(!this.writableClient){this.emitWriteError(O_e(e.type),e.requestId,new $t(`EACCES`,`vfs-rpc-host has no writable backend wired`),k_e(e));return}switch(e.type){case`vfs-write-file`:return this.handleWriteFile(e,this.writableClient);case`vfs-mkdir`:return this.handleMkdir(e,this.writableClient);case`vfs-rm`:return this.handleRm(e,this.writableClient);case`vfs-flush`:return this.handleFlush(e,this.writableClient);case`vfs-list-mount-points`:return this.handleListMountPoints(e,this.writableClient)}}async handleWriteFile(e,t){try{if(e.encoding===`binary`){if(!(e.data instanceof Uint8Array)){this.emitWriteError(`vfs-write-file-result`,e.requestId,new $t(`EIO`,`vfs-write-file(binary) data is not Uint8Array`),e.path);return}}else if(typeof e.data!=`string`){this.emitWriteError(`vfs-write-file-result`,e.requestId,new $t(`EIO`,`vfs-write-file(utf-8) data is not string`),e.path);return}let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.writeFile(e.path,e.data,n);let r={type:`vfs-write-file-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-write-file-result`,e.requestId,t,e.path)}}async handleMkdir(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.mkdir(e.path,n);let r={type:`vfs-mkdir-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-mkdir-result`,e.requestId,t,e.path)}}async handleRm(e,t){try{let n=e.recursive===void 0?void 0:{recursive:e.recursive};await t.rm(e.path,n);let r={type:`vfs-rm-result`,requestId:e.requestId,ok:!0};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-rm-result`,e.requestId,t,e.path)}}async handleFlush(e,t){try{await t.flush();let n={type:`vfs-flush-result`,requestId:e.requestId,ok:!0};this.transport.send(n)}catch(t){this.emitWriteError(`vfs-flush-result`,e.requestId,t,``)}}async handleListMountPoints(e,t){if(!t.listMountPoints){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,new $t(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function T_e(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function E_e(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 D_e(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 O_e(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 k_e(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof $t?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function A_e(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=p_e(e.bind(globalThis),t,j_e)}function j_e(){let e=lee();if(!e)return null;try{return new URL(e).origin}catch{return null}}function M_e(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 N_e=__e(e=>I_e(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&N_e.handle(e.data)});function P_e(e){let t=va(e.pageBuildId,`6.91.0-mt77ppme`);return()=>{t&&Kee(`mixed-build-graph`,`page ${e.pageBuildId} worker 6.91.0-mt77ppme`)}}function F_e(e){A_e(),uee(e.localApiBaseUrl??null),oee(e.bridgeToken??null),fG(e.syncFsBridgeEnabled??!1),cee(e.extensionDelegateId??null),M_e(e.localStorageSeed??{}),e.flagFloat&&oa(e.flagFloat)}async function I_e(e){ha(e.instanceId);let t=P_e(e),n=t=>{e.kernelPort.postMessage({type:`kernel-worker-boot-progress`,stage:t})};try{F_e(e),Jee().then(t).catch(()=>{}),await s(),n(`providers-registered`);let r=xa(e.kernelPort),a=new n_(r),o=n_.createCallbacks(a),c=new Sa(e.cdpPort);await c.connect(),n(`cdp-connected`);let l=new tte(c);Y9=await u_e({container:{},browser:l,bridge:a,callbacks:o,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null,onBootProgress:n});let{createSprinkleManagerProxyOverChannel:u}=await import(`./sprinkle-bridge-channel-CftxYQ9D.js`),d=u({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=d;let f=Y9.sharedFs?.getWatcher();if(f){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)f.watch(r,e=>e.endsWith(`.shtml`),e=>{for(let t of e){let e=t.path.split(`/`).pop()?.replace(/\.shtml$/,``);e&&n.add(e)}t||=setTimeout(()=>{t=null;for(let e of n)d.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:p}=await import(`./panel-rpc-BPwAqRch.js`).then(e=>e.i);$9=p({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,l.setTrayTargetProvider(ite(i));let m=await R_e({host:Y9,transport:r,browser:l,instanceId:e.instanceId});m&&(X9=m.stopTerminalHost,Z9=m.stopVfsRpcHost,Q9=m.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(t){L_e(e.kernelPort,t)}}function L_e(e,t){_a(t);try{let n=t instanceof Error?t.message:String(t),r=t?.code;e.postMessage({type:`kernel-worker-boot-error`,message:n,...typeof r==`string`?{code:r}:{},...t instanceof Error&&t.stack?{stack:t.stack}:{}})}catch{}throw t}async function R_e(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=S_e({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=C_e({transport:e.transport,client:t,writableClient:t,logger:console}),i=await z_e(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function z_e(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-DequteUl.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-CKwQ54O1.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-Co-pb0x0.js`).then(e=>e.n),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});
|