sliccy 5.60.0 → 5.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/assets/{account-store-dvAfa3y8.js → account-store-Bkt-sHjk.js} +1 -1
- package/dist/ui/assets/{account-store-BddNCTSm.js → account-store-DK2Sc2Br.js} +1 -1
- package/dist/ui/assets/{adobe-DC5UT0ZJ.js → adobe-CKLRjAln.js} +1 -1
- package/dist/ui/assets/{adobe-C0iTCwW2.js → adobe-D3LfvR1c.js} +1 -1
- package/dist/ui/assets/{apps-ztx90XZQ.js → apps-Bf1H6-85.js} +1 -1
- package/dist/ui/assets/{azure-openai-BKnOwPkT.js → azure-openai-CqSF2b4l.js} +1 -1
- package/dist/ui/assets/{azure-openai-Y9U14npX.js → azure-openai-LwRRPkRI.js} +1 -1
- package/dist/ui/assets/{cerebras-D_u7JsxU.js → cerebras-CEBK7ldR.js} +1 -1
- package/dist/ui/assets/{cerebras-ZAPHCT6L.js → cerebras-DoDBOChk.js} +1 -1
- package/dist/ui/assets/{connect-surface-YVJhSwyb.js → connect-surface-DADZwDbi.js} +1 -1
- package/dist/ui/assets/{fs-BVM9dzPP.js → fs-BZ8jCbhy.js} +1 -1
- package/dist/ui/assets/{fs-CMpdIYZs.js → fs-Cfytz2TS.js} +2 -2
- package/dist/ui/assets/{github-ndbvNRbv.js → github-BYsKWPeV.js} +1 -1
- package/dist/ui/assets/{github-CmX1lUH3.js → github-DdPXKMLe.js} +2 -2
- package/dist/ui/assets/{github-copilot-C9loxoyp.js → github-copilot-AYSHehC3.js} +1 -1
- package/dist/ui/assets/{github-copilot-JdvDIR67.js → github-copilot-aVD8W5Uc.js} +1 -1
- package/dist/ui/assets/js-realm-worker-vnTP6x9C.js +48 -0
- package/dist/ui/assets/{kernel-worker-DMnEeTNU.js → kernel-worker-Dv6ugtws.js} +416 -416
- package/dist/ui/assets/{lick-ws-bridge-SPFIXhG2.js → lick-ws-bridge-DsRRwfVk.js} +1 -1
- package/dist/ui/assets/{local-llm-DS8tu43V.js → local-llm-Ja3mfEao.js} +1 -1
- package/dist/ui/assets/{local-llm-B5vPCdpH.js → local-llm-kMFFJCDT.js} +1 -1
- package/dist/ui/assets/{main-D8Y-cnmF.js → main-jD3wsTHm.js} +3 -3
- package/dist/ui/assets/{mount-C4XESP9i.js → mount-B1o0Tu6r.js} +1 -1
- package/dist/ui/assets/{mount-Hr9QXuwp.js → mount-Co7VoiG3.js} +2 -2
- package/dist/ui/assets/{mount-recovery-BHHDw9yC.js → mount-recovery-Cwl9npdz.js} +1 -1
- package/dist/ui/assets/{new-session-u-78FCPG.js → new-session-DvI8DpbC.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-DHKASsxn.js → oauth-bootstrap-LUBU0zw1.js} +2 -2
- package/dist/ui/assets/{openai-codex-Djc_-qM9.js → openai-codex-CH1oMijR.js} +1 -1
- package/dist/ui/assets/{openai-codex-gi-RyKX_.js → openai-codex-Dc2-mj0x.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-CTZqBsvr.js → panel-rpc-handlers-BGkBk9Rn.js} +2 -2
- package/dist/ui/assets/{provider-POdkeNpc.js → provider-P5X9hREk.js} +1 -1
- package/dist/ui/assets/{provider-DeZ3vGbS.js → provider-YWxytFh6.js} +2 -2
- package/dist/ui/assets/{provider-settings-BraIAAA7.js → provider-settings-DyFcREdE.js} +1 -1
- package/dist/ui/assets/{provider-settings-3FoUN196.js → provider-settings-R1mQ9-PX.js} +1 -1
- package/dist/ui/assets/provider-store-access-DhwBcPZJ.js +1 -0
- package/dist/ui/assets/{provider-store-access-B_pR-9Xx.js → provider-store-access-GUSmwQsv.js} +2 -2
- package/dist/ui/assets/{providers-B26DtTJa.js → providers-BXwvtxEC.js} +1 -1
- package/dist/ui/assets/{providers-CvODsjGm.js → providers-C-C_QZBA.js} +2 -2
- package/dist/ui/assets/{quick-llm-DzhE1JW0.js → quick-llm-CyIluLr1.js} +1 -1
- package/dist/ui/assets/{session-freezer-CUzeQ9yz.js → session-freezer-DHt0Igru.js} +2 -2
- package/dist/ui/assets/{setup-sudo-cXyK0NGW.js → setup-sudo-C7mksJ74.js} +2 -2
- package/dist/ui/assets/{skills-otSlGBFl.js → skills-B5bs2JnW.js} +1 -1
- package/dist/ui/assets/{store-BfzctFJC.js → store-fjjsfL92.js} +1 -1
- package/dist/ui/assets/{sudo-LN3PJp6v.js → sudo-B5hEP8ex.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-DIIyklC5.js → upgrade-detection-B6AiyIwx.js} +1 -1
- package/dist/ui/assets/{wc-extension-oy0LEz26.js → wc-extension-kt7jA5Vw.js} +2 -2
- package/dist/ui/assets/{wc-follower-DcQtc8YB.js → wc-follower-BFZP3SRo.js} +3 -3
- package/dist/ui/assets/wc-live-BPDbUJ7I.js +8 -0
- package/dist/ui/assets/{wc-nav-BqxVwvjV.js → wc-nav-B0oFpZdj.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-D9lPUOm-.js → wc-onboarding-BtEZZu63.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-C0wfdFBG.js → wc-placeholder-BqQKxg_e.js} +2 -2
- package/dist/ui/assets/{wc-settings-qEE2zwaO.js → wc-settings-B5BrTsqJ.js} +2 -2
- package/dist/ui/assets/{wc-shell-BHZzK20y.js → wc-shell-D1rFLiLn.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-DlE9uQTj.js → wc-sprinkles-CtVb4mz3.js} +2 -2
- package/dist/ui/assets/{wc-tray-BdFq9TlZ.js → wc-tray-2PpRgp9c.js} +2 -2
- package/dist/ui/assets/{xai-grok-Bx0idvJc.js → xai-grok-CbKylYRb.js} +1 -1
- package/dist/ui/assets/{xai-grok-CemZ8tZD.js → xai-grok-olZUR6su.js} +1 -1
- package/dist/ui/index.html +5 -5
- package/dist/ui/llm-proxy-sw.js +1 -1
- package/dist/ui/packages/webapp/index.html +5 -5
- package/package.json +1 -1
- package/dist/ui/assets/js-realm-worker-B4uCLm52.js +0 -48
- package/dist/ui/assets/provider-store-access-BkJ_SWbe.js +0 -1
- package/dist/ui/assets/wc-live-D7BaYtR7.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./logger-LESFN7Hj.js";import{c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h}from"./proxied-fetch-sbHa3Tte.js";import{r as g,t as _}from"./src-Dk1QVJRd.js";import{D as v,E as y,F as b,I as x,L as S,M as C,N as w,P as T,R as E,T as D,_ as O,h as k,i as A,j,o as M,v as N}from"./account-store-
|
|
1
|
+
import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{t as n}from"./logger-LESFN7Hj.js";import{c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,s as p,t as m,u as h}from"./proxied-fetch-sbHa3Tte.js";import{r as g,t as _}from"./src-Dk1QVJRd.js";import{D as v,E as y,F as b,I as x,L as S,M as C,N as w,P as T,R as E,T as D,_ as O,h as k,i as A,j,o as M,v as N}from"./account-store-DK2Sc2Br.js";import{a as P,i as ee,n as te,r as ne}from"./transcript-limits-D0M7bLr9.js";import{n as re,o as ie,s as ae}from"./tool-ui-t6ocn6AG.js";import{a as oe,i as se,n as F,o as I,r as ce,t as le}from"./backend-local-J_dSen8g.js";import{t as ue}from"./runtime-env-byAg9ij-.js";import{t as L}from"./types-idfTVsM8.js";import{n as de,t as fe}from"./mime-types-D7IV6i7k.js";import{a as pe,i as me,n as R,r as z}from"./mount-B1o0Tu6r.js";import{o as he}from"./mount-table-store-CTrzlrNn.js";import{n as ge,r as B,t as _e}from"./fetch-body-DDu_AU5I.js";import{t as V}from"./remote-cache-D59F5FOx.js";import{r as ve,t as H}from"./mount-recovery-Cwl9npdz.js";import{S as U,a as ye,b as be,g as xe,h as Se,i as W,l as Ce,m as we,n as Te,o as Ee,p as De,t as Oe,u as ke,v as Ae,w as je,x as Me}from"./db-DjAqlQ2I.js";import{a as Ne,i as Pe,n as Fe,r as Ie}from"./tray-runtime-config-DlPGhxQs.js";import{a as Le,i as Re,n as ze,o as Be,r as Ve}from"./runtime-mode-M-qJL9jF.js";import{n as He,r as Ue,t as We}from"./panel-rpc-CjFVE0nK.js";import{a as Ge}from"./providers-BXwvtxEC.js";import{a as Ke,c as qe,d as Je,i as Ye,l as Xe,n as Ze,o as Qe,s as $e,t as et,u as tt}from"./lick-manager-Ct3WOtut.js";import{i as nt,n as rt,t as it}from"./path-utils-DU6QhF_k.js";import{u as at}from"./transform-messages-CVIV-EgO.js";import{l as ot,m as st}from"./bedrock-camp-CvxD6hHk.js";import{t as ct}from"./__vite-browser-external-SwrSgYTf.js";import{a as lt,n as ut,r as dt}from"./fs-BZ8jCbhy.js";import{a as ft,c as pt,i as G,n as mt,o as ht,r as gt,s as _t}from"./cost-command-Cpg2Em0Q.js";import{a as vt,c as yt,d as bt,f as xt,i as St,l as Ct,m as wt,n as Tt,o as Et,p as Dt,r as Ot,s as kt,u as At}from"./skills-B5bs2JnW.js";import{n as jt,t as Mt}from"./llm-session-id-ZObKEXzb.js";import{a as Nt,c as Pt,d as Ft,f as It,i as Lt,l as Rt,n as zt,o as Bt,r as Vt,s as Ht,t as Ut,u as Wt}from"./installer-D7LGGQGy.js";import{n as Gt,t as Kt}from"./safe-buffer-C0pSmFaz.js";import{t as qt}from"./global-db-DvmmimLY.js";import{a as Jt,i as Yt,r as Xt,t as Zt}from"./git-config-Lj0BT7Oc.js";import{t as Qt}from"./process-manager-B5dz0PkO.js";import{D as $t,O as en,S as tn,_ as nn,a as rn,b as an,c as on,d as sn,f as cn,g as ln,h as un,i as dn,l as fn,m as pn,n as mn,o as hn,p as gn,r as _n,s as vn,t as yn,u as bn,v as xn,x as Sn,y as Cn}from"./shared-X5SFnyK-.js";import{i as wn,r as Tn,t as En}from"./magick-wasm-B-rybRPb.js";import{a as Dn,i as On,r as kn,t as An}from"./script-catalog-BYXhqRAc.js";import{t as jn}from"./local-llm-kMFFJCDT.js";import{t as Mn}from"./client-CpLUc-P8.js";const Nn=`__slicc_binary__`;function Pn(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Nn]===`b64`&&typeof t.data==`string`}function Fn(e){if(e instanceof Uint8Array)return{[Nn]:`b64`,data:c(e)};if(Array.isArray(e))return e.map(Fn);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Fn(r);return t}return e}function In(e){if(Pn(e))return d(e.data);if(Array.isArray(e))return e.map(In);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=In(r);return t}return e}const Ln=n(`panel-transport`);function Rn(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function zn(){return{onMessage:e=>{let t=(t,n,r)=>(Rn(t)&&e(In(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Fn(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)||Ln.error(`Offscreen → panel transport send failed`,{error:t})})}}}const Bn=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`,`discovery`]);function Vn(e){return e!=null&&Bn.has(e)}const Hn={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`,cron:`Cron Event`,"sudo-request":`Scoop Access Request`,preview:`Preview`,discovery:`Discovery Event`};function Un(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`sudo-request`:return e.sudoScoopName;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function Wn(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=H(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=Zn(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 Gn(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.`:`
|
|
2
2
|
|
|
3
3
|
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 Kn(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 qn(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function Jn(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 Yn(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(`
|
|
4
4
|
`)}}function Xn(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}.\nThis is informational — there is no card action. You MAY fetch it (e.g. \`curl ${r}\`) and act on it if it's relevant to the current task; otherwise ignore it.`}}function Zn(e,t){let n=Un(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 Qn(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return Zn(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 $n(e,t){let n=Zn(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 er(e){let t=Hn[e.type];return e.type===`session-reload`?Wn(e,t):e.type===`upgrade`?Gn(e,t):e.type===`cherry`?Kn(e,t):e.type===`preview`?qn(e,t):e.type===`workflow`?Jn(e,t):e.type===`sudo-request`?Yn(e,t):e.type===`navigate`?$n(e,t):e.type===`webhook`?Qn(e,t):e.type===`discovery`?Xn(e,t):Zn(e,t)}let tr={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function nr(){return{...tr}}function rr(){let e=nr();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.followerTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const ir=new Set;function ar(e){return ir.add(e),()=>{ir.delete(e)}}const or=`sessions`;function sr(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(or)||e.createObjectStore(or,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var cr=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await sr();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(or,`readwrite`);i.objectStore(or).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(or,`readonly`).objectStore(or).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(or,`readonly`).objectStore(or).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(or,`readwrite`);i.objectStore(or).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)}};const lr=n(`offscreen-bridge`);function ur(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 dr=class{orchestrator=null;browserAPI=null;messageBuffers=new Map;currentMessageId=new Map;scoopStatuses=new Map;sessionStore=null;followerSync=null;followerActive=!1;_transport;transportUnsubscribe=null;activeScoopJid=null;agentEventListeners=new Set;fanOutMessageId=new Map;constructor(e){this._transport=e??null}get transport(){return this._transport||=zn(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new cr;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.currentMessageId.get(t);if(n){let r=e.getBuffer(t).find(e=>e.id===n);r&&(r.isStreaming=!1),e.currentMessageId.delete(t)}e.persistScoop(t),e.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`})},onSendMessage:(t,n)=>{let r=e.getBuffer(t),i=`msg-${fr()}`;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.scoopStatuses.set(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})},onToolStart:(t,n,r)=>{P.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{P.has(n)||e.bufferToolEnd(t,n,r,i)},onToolUI:(t,n,r,i)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui`,toolName:n,requestId:r,html:i})},onToolUIDone:(t,n)=>{e.emit({type:`agent-event`,scoopJid:t,eventType:`tool_ui_done`,requestId:n})},onIncomingMessage:(t,n)=>e.bufferIncomingMessage(t,n),onMessageUpdate:(t,n)=>e.applyMessageUpdate(t,n),onScoopUnregistered:t=>e.evictScoopState(t)}}bufferToolStart(e,t,n){let r=te(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:fr(),name:t,input:r}),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_start`,toolName:t,toolInput:r})}bufferToolEnd(e,t,n,r){let i=this.currentMessageId.get(e);if(i){let a=this.getBuffer(e).find(e=>e.id===i);if(a?.toolCalls){let e=[...a.toolCalls].reverse().find(e=>e.name===t&&e.result===void 0);e&&(e.result=ne(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:ee(n),isError:r})}bufferIncomingMessage(e,t){let n={id:t.id,role:`user`,content:t.channel===`delegation`?`**[Instructions from sliccy]**\n\n${t.content}`:t.content,attachments:t.attachments,timestamp:new Date(t.timestamp).getTime(),source:t.channel===`delegation`?`delegation`:void 0,channel:t.channel,lickId:t.lickId,lickState:t.lickState};this.getBuffer(e).push(n),this.persistScoop(e),this.notifyPanelIncomingMessage(e,t)}evictScoopState(e){this.messageBuffers.delete(e.jid),this.currentMessageId.delete(e.jid),this.fanOutMessageId.delete(e.jid),this.scoopStatuses.delete(e.jid),!e.isCone&&this.sessionStore&&this.sessionStore.delete(`session-${e.folder}`).catch(t=>{console.warn(`[offscreen-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){let t=e.config&&(e.config.modelId!==void 0||e.config.thinkingLevel!==void 0)?{...e.config.modelId===void 0?{}:{modelId:e.config.modelId},...e.config.thinkingLevel===void 0?{}:{thinkingLevel:e.config.thinkingLevel}}:void 0;return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,assistantLabel:e.assistantLabel,status:this.scoopStatuses.get(e.jid)??`ready`,...t?{config:t}:{}}}buildStateSnapshot(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[],t=e.find(e=>e.isCone);return{type:`state-snapshot`,scoops:e,activeScoopJid:this.getActiveScoopJid()??t?.jid??null,trayRuntimeStatus:this.buildTrayRuntimeStatus()}}emitTrayRuntimeStatus(){let e=this.buildTrayRuntimeStatus(),t={type:`tray-runtime-status`,leader:e.leader,follower:e.follower};this.emit(t)}buildTrayRuntimeStatus(){let e=Le(),t=nr();return{leader:{state:e.state,session:e.session,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}}}setFollowerSync(e){this.followerSync=e}setFollowerActive(e){this.followerActive=e}setActiveScoopJid(e){this.activeScoopJid=e}getActiveScoopJid(){return this.activeScoopJid}onAgentEvent(e){return this.agentEventListeners.add(e),()=>{this.agentEventListeners.delete(e)}}fanOutAgentEvent(e){let{scoopJid:t,eventType:n}=e,r=[],i=()=>{let e=this.fanOutMessageId.get(t);return e||(e=`scoop-${t}-${fr()}`,this.fanOutMessageId.set(t,e),r.push({type:`message_start`,messageId:e})),e};switch(n){case`text_delta`:{let t=i();r.push({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=i();r.push({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_result`,messageId:n,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=i();r.push({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let n=this.fanOutMessageId.get(t);if(!n)return;r.push({type:`tool_ui_done`,messageId:n,requestId:e.requestId??``});break}case`response_done`:{let e=this.fanOutMessageId.get(t);if(!e)return;r.push({type:`content_done`,messageId:e}),this.fanOutMessageId.delete(t);break}case`turn_end`:this.fanOutMessageId.delete(t);break}for(let e of r)for(let n of this.agentEventListeners)try{n(t,e)}catch(e){lr.error(`onAgentEvent listener threw`,{error:e instanceof Error?e.message:String(e)})}}getMessagesForJid(e){return this.getBuffer(e)}async routeSprinkleLick(e,t,n,r){if(!this.orchestrator)return;let i=ur(t);i&&this.orchestrator.resolveNavigateHandoffByHuman(i.lickId,i.accepted);let a=this.orchestrator.getScoops(),o=n?a.find(e=>e.name===n||e.folder===n||e.folder===`${n}-scoop`):void 0;if(o||=a.find(e=>e.isCone),!o)return;let s=`sprinkle-${e}-${Date.now()}`,c=er({type:`sprinkle`,sprinkleName:e,timestamp:new Date().toISOString(),body:t,originLabel:r})?.content??`[Sprinkle Event: ${e}]\n\`\`\`json\n${JSON.stringify(t,null,2)}\n\`\`\``,l={id:s,chatJid:o.jid,senderId:`sprinkle`,senderName:`sprinkle:${e}`,content:c,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`sprinkle`};this.getBuffer(o.jid).push({id:s,role:`user`,content:c,timestamp:Date.now(),source:`lick`,channel:`sprinkle`}),this.persistScoop(o.jid),await this.orchestrator.handleMessage(l)}applyFollowerSnapshot(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(e=>e.isCone);if(!t)return;let n=e.map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),isStreaming:e.isStreaming}));if(this.messageBuffers.set(t.jid,n),this.currentMessageId.delete(t.jid),this.fanOutMessageId.delete(t.jid),this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.saveMessages(n,e).catch(e=>{lr.error(`applyFollowerSnapshot persist failed`,{error:e instanceof Error?e.message:String(e)})})}this.emit({type:`scoop-messages-replaced`,scoopJid:t.jid,messages:n})}getConeJid(){return this.orchestrator?.getScoops().find(e=>e.isCone)?.jid??null}emitFollowerAgentEvent(e){let t=this.getConeJid();if(t)switch(e.type){case`content_delta`:this.emit({type:`agent-event`,scoopJid:t,eventType:`text_delta`,text:e.text});break;case`content_done`:this.emit({type:`agent-event`,scoopJid:t,eventType:`response_done`});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});break}}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.scoopStatuses.set(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-QyCEPmi8.js`);return r(n,{source:e.isCone?`cone`:e.name??e.folder}).map(e=>({id:e.id,role:e.role,content:e.content,attachments:e.attachments,timestamp:e.timestamp,source:e.source,channel:e.channel,toolCalls:e.toolCalls?.map(e=>({id:e.id,name:e.name,input:e.input,result:e.result,isError:e.isError})),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.fanOutMessageId.delete(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.fanOutMessageId.delete(e),this.persistScoop(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:r});return}if(this.sessionStore){let n=t.isCone?`session-cone`:`session-${t.folder}`;try{let t=(await this.sessionStore.load(n))?.messages??[];t.length>0&&(this.messageBuffers.set(e,t),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.emit({type:`scoop-messages-replaced`,scoopJid:e,messages:t}))}catch(e){lr.error(`sessionStore load failed`,{sessionId:n,error:e instanceof Error?e.message:String(e)})}}}async handleConeCreate(e){if(!this.orchestrator)return;let t={jid:`cone_${Date.now()}`,name:e,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()};await this.orchestrator.registerScoop(t),this.emit({type:`scoop-created`,scoop:this.toScoopSnapshot(t)})}handleRequestSessionStats(e){let t=0,n=[],r=[],i=[];try{let e=this.orchestrator?.getSessionCosts()??[];t=e.reduce((e,t)=>e+t.usage.cost.total,0),n=this.orchestrator?.getContextFills()??[],r=(this.orchestrator?.getModelCosts()??[]).map(e=>({model:e.model,cost:e.cost,turns:e.turns,tokens:e.input+e.output+e.cacheRead+e.cacheWrite})),i=e.map(e=>({name:e.name,model:e.model,cost:e.usage.cost.total,type:e.type}))}catch{}this.emit({type:`session-stats`,requestId:e,totalCost:t,fills:n,models:r,scoops:i})}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:pr(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-QyCEPmi8.js`),i=a.getAgentMessages();if(i.length>0){let a=n(i,{source:r.isCone?`cone`:r.name??r.folder});this.emit({type:`scoop-transcript`,requestId:e,scoopJid:t,transcript:pr(a)});return}}n()}async handleRequestScoopChatMessages(e,t){let n=()=>{this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:[]})};if(!this.orchestrator){n();return}let r=this.orchestrator.getScoops().find(e=>e.jid===t);if(!r){n();return}let i=this.messageBuffers.get(t);if(i&&i.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:i});return}let a=await this.buildBufferFromAgentMessages(r);if(a&&a.length>0){this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:a});return}if(this.sessionStore){let n=r.isCone?`session-cone`:`session-${r.folder}`;try{let r=(await this.sessionStore.load(n))?.messages??[];this.emit({type:`scoop-chat-messages`,requestId:e,scoopJid:t,messages:r});return}catch{}}n()}persistScoop(e){this.persistScoopAwait(e)}async persistScoopAwait(e){if(!this.sessionStore||!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(!t)return;let n=t.isCone?`session-cone`:`session-${t.folder}`,r=this.messageBuffers.get(e);if(!(!r||r.length===0))try{await this.sessionStore.saveMessages(n,r)}catch(e){lr.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}-${fr()}`,this.currentMessageId.set(e,n);let r=(this.orchestrator?.getScoops()??[]).find(t=>t.jid===e),i=r?.isCone?`cone`:r?.name??`unknown`,a={id:n,role:`assistant`,content:``,timestamp:Date.now(),toolCalls:[],isStreaming:!0,source:i};return t.push(a),a}setupMessageListener(){return this.transport.onMessage(e=>{if(e.source===`panel`){if(e.payload?.type===`sprinkle-op-response`){import(`./sprinkle-proxy-B4nH2NxC.js`).then(({handleSprinkleOpResponse:t})=>{t(e.payload)});return}this.handlePanelMessage(e.payload).catch(t=>{console.error(`[offscreen-bridge] handlePanelMessage error:`,t);let n=e.payload.scoopJid;n&&this.emit({type:`error`,scoopJid:n,error:t instanceof Error?t.message:String(t)})})}})}async handlePanelMessage(e){if(this.orchestrator)switch(e.type){case`user-message`:await this.handleUserMessage(e);break;case`cone-create`:await this.handleConeCreate(e.name);break;case`scoop-feed`:await this.orchestrator.delegateToScoop(e.scoopJid,e.prompt,`sliccy`);break;case`scoop-drop`:await this.handleScoopDrop(e.scoopJid);break;case`abort`:this.orchestrator.stopScoop(e.scoopJid),this.orchestrator.clearQueuedMessages(e.scoopJid).catch(e=>{console.warn(`[offscreen-bridge] Failed to clear queued messages on abort:`,e)});break;case`delete-queued-message`:this.handleDeleteQueuedMessage(e.scoopJid,e.messageId);break;case`set-model`:this.orchestrator.updateModel();break;case`request-state`:this.emit(this.buildStateSnapshot());break;case`request-scoop-messages`:await this.handleRequestScoopMessages(e.scoopJid);break;case`request-scoop-transcript`:await this.handleRequestScoopTranscript(e.requestId,e.scoopJid);break;case`request-scoop-chat-messages`:await this.handleRequestScoopChatMessages(e.requestId,e.scoopJid);break;case`request-session-stats`:this.handleRequestSessionStats(e.requestId);break;case`clear-chat`:await this.handleClearChat(e.requestId);break;case`clear-filesystem`:await this.orchestrator.resetFilesystem().catch(e=>console.error(`[offscreen-bridge] clear-filesystem failed:`,e));break;case`refresh-model`:this.orchestrator.updateModel();break;case`set-thinking-level`:{let t=e;try{await this.orchestrator.setScoopThinkingLevel(t.scoopJid,t.level,t.effortOverride)}catch(e){console.error(`[offscreen-bridge] set-thinking-level failed:`,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(`[offscreen-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());break}}handleDeleteQueuedMessage(e,t){if(!this.orchestrator)return;this.orchestrator.deleteQueuedMessage(e,t).catch(e=>{console.warn(`[offscreen-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){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`};await this.orchestrator?.handleMessage(t),this.orchestrator?.createScoopTab(e.scoopJid)}async handleScoopDrop(e){if(!this.orchestrator)return;let t=this.orchestrator.getScoops().find(t=>t.jid===e);if(await this.orchestrator.unregisterScoop(e),this.messageBuffers.delete(e),this.currentMessageId.delete(e),this.fanOutMessageId.delete(e),this.scoopStatuses.delete(e),t&&this.sessionStore){let e=t.isCone?`session-cone`:`session-${t.folder}`;this.sessionStore.delete(e).catch(t=>{console.warn(`[offscreen-bridge] Failed to delete session on scoop drop:`,e,t)})}this.emitScoopList()}async handleClearChat(e){let t=this.orchestrator?.getScoops().find(e=>e.isCone)?.jid;t&&await this.orchestrator?.clearScoopMessages(t),this.sessionStore&&await this.sessionStore.delete(`session-cone`),t&&(this.messageBuffers.delete(t),this.currentMessageId.delete(t),this.fanOutMessageId.delete(t)),this.emit({type:`clear-chat-ack`,requestId:e})}async handleSprinkleLickMsg(e){if(this.followerActive){this.followerSync?this.followerSync.sendSprinkleLick(e.sprinkleName,e.body,e.targetScoop):console.warn(`[offscreen-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=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-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=globalThis.__slicc_lickManager;if(!t){console.warn(`[offscreen-bridge] inject-forwarded-lick dropped: worker LickManager unavailable`,{type:e.type});return}t.emitEvent(e)}async handlePanelCdpCommand(e){let{id:t,method:n,params:r,sessionId:i}=e;if(!this.browserAPI){console.warn(`[offscreen-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`){ae.markMounted(t);return}try{await ae.handleAction(t,{action:n,data:r})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`[offscreen-bridge] Tool UI action failed`,{requestId:t,action:n,error:r}),ae.cancel(t,`Action failed: ${r}`)}}applyLocalStorageOp(e,t){try{let e=globalThis.localStorage;e&&t(e)}catch(t){console.warn(`[offscreen-bridge] ${e} failed:`,t)}}emitScoopList(){let e=this.orchestrator?.getScoops().map(e=>this.toScoopSnapshot(e))??[];this.emit({type:`scoop-list`,scoops:e})}emit(e){this.transport.send(e),e.type===`agent-event`&&this.fanOutAgentEvent(e)}};function fr(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function pr(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
@@ -4851,12 +4851,12 @@ except BaseException:
|
|
|
4851
4851
|
`)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const QS={reset:`\x1B[0m`,green:`\x1B[32m`,red:`\x1B[31m`,yellow:`\x1B[33m`,gray:`\x1B[90m`,bold:`\x1B[1m`,cyan:`\x1B[36m`,dim:`\x1B[2m`};function $S(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${QS.reset}`:String(n);return{enabled:t,green:n(QS.green),red:n(QS.red),yellow:n(QS.yellow),gray:n(QS.gray),bold:n(QS.bold),cyan:n(QS.cyan),dim:n(QS.dim)}}const eC={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function tC(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*eC[i])}function nC(e){return e<10?`0${e}`:String(e)}const rC={parseDuration:tC,ago(e,t=new Date){return new Date(t.getTime()-tC(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-tC(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+tC(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-tC(e));return`${n.getFullYear()}/${nC(n.getMonth()+1)}/${nC(n.getDate())}`}},iC=/\u001b\[[0-9;]*m/g;function aC(e){return e.replace(iC,``)}function oC(e){return aC(e).length}function sC(e,t){let n=String(e??``);return t<=0?``:oC(n)<=t?n:t<=1?n.slice(0,t):`${aC(n).slice(0,t-1)}…`}function cC(e,t){let n=String(e??``),r=oC(n);return r===t?n:r>t?sC(n,t):n+` `.repeat(t-r)}function lC(e,t){if(!e.length)return``;let n=Math.max(...e.map(e=>e.length)),r=[];for(let i=0;i<n;i++)if(t&&t[i]!==void 0)r[i]=t[i];else{let t=0;for(let n of e){let e=i<n.length?String(n[i]??``):``;t=Math.max(t,oC(e))}r[i]=t}return e.map(e=>r.map((t,n)=>cC(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
|
|
4852
4852
|
`)}function uC(e){return e instanceof Date?e:new Date(e)}function dC(e,t=`short`){let n=uC(e);if(Number.isNaN(n.getTime()))return String(e);if(t===`iso`)return n.toISOString();if(t===`locale`)return new Intl.DateTimeFormat(void 0,{dateStyle:`medium`}).format(n);if(t===`human`){let e=Date.now()-n.getTime(),t=Math.abs(e);if(t<6e4)return e>=0?`just now`:`in a moment`;let r=(t,n)=>e>=0?`${t} ${n}${t===1?``:`s`} ago`:`in ${t} ${n}${t===1?``:`s`}`;return t<36e5?r(Math.round(t/6e4),`minute`):t<864e5?r(Math.round(t/36e5),`hour`):t<26298e5?r(Math.round(t/864e5),`day`):t<315576e5?r(Math.round(t/26298e5),`month`):r(Math.round(t/315576e5),`year`)}return`${n.getFullYear()}-${nC(n.getMonth()+1)}-${nC(n.getDate())}`}const fC={trunc:sC,col:cC,table:lC,date:dC},pC=async(e,t,n)=>{let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=[],s=async()=>{for(;;){let e=a++;if(e>=t.length)return;i[e]=await n(t[e],e)}};for(let e=0;e<Math.min(r,t.length);e++)o.push(s());return await Promise.all(o),i};function mC(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 hC(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=mC(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function gC(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:hC(t)}function _C(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 vC(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 yC(e){let t=vC(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function bC(...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=mC(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function xC(e,t){let n=bC(e),r=bC(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 SC(e){let t=e.charCodeAt(0)===47?`/`:``,n=vC(e),r=yC(e),i=r?n.slice(0,n.length-r.length):n,a=_C(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function CC(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 wC={sep:`/`,delimiter:`:`,basename:vC,dirname:_C,extname:yC,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:gC,normalize:hC,resolve:bC,relative:xC,parse:SC,format:CC},TC=65536,EC={md5:my.md5,sha1:hy.sha1,sha256:gy.sha256};function DC(e,t){let n=globalThis.Buffer;if(!n)throw Error(`crypto.createHash: Buffer is unavailable in this environment`);return t?n.from(e,t):n.from(e)}function OC(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(DC(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function kC(e){let t=String(e).toLowerCase().replace(`-`,``),n=EC[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(OC(e,t)),a},digest(e){i=!0;let t=DC(r.array());return e?t.toString(e):t}};return a}function AC(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function jC(e){return AC().getRandomValues(e)}function MC(e){for(let t=0;t<e.length;t+=TC){let n=Math.min(t+TC,e.length);jC(e.subarray(t,n))}}function NC(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const PC=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function FC(){let e=AC();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=jC(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${PC[t[0]]}${PC[t[1]]}${PC[t[2]]}${PC[t[3]]}-${PC[t[4]]}${PC[t[5]]}-${PC[t[6]]}${PC[t[7]]}-${PC[t[8]]}${PC[t[9]]}-${PC[t[10]]}${PC[t[11]]}${PC[t[12]]}${PC[t[13]]}${PC[t[14]]}${PC[t[15]]}`}const IC={randomFillSync(e,t=0,n){let r=NC(e),i=t,a=n===void 0?r.length:i+n;return MC(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return MC(NC(n)),n},randomUUID:FC,getRandomValues(e){return jC(e)},createHash:kC,get webcrypto(){return AC()},get subtle(){return AC().subtle}};var LC=class extends Error{actual;expected;operator;generatedMessage;code;constructor(e={}){let t=!e.message;super(e.message||`${RC(e.actual)} ${e.operator||`!=`} ${RC(e.expected)}`),this.name=`AssertionError`,this.actual=e.actual,this.expected=e.expected,this.operator=e.operator||``,this.generatedMessage=t,this.code=`ERR_ASSERTION`}};function RC(e){if(typeof e==`string`)return JSON.stringify(e);if(e==null)return String(e);if(typeof e==`object`)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function zC(e,t){return e instanceof Error?e:typeof e==`string`?new LC({message:e}):t()}function BC(e,t,n,r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!HC(e[i],t[i],n,r))return!1;return!0}function VC(e,t,n,r){let i=Object.keys(e);if(i.length!==Object.keys(t).length)return!1;for(let a of i){if(!Object.prototype.hasOwnProperty.call(t,a))return!1;let i=e[a],o=t[a];if(!HC(i,o,n,r))return!1}return!0}function HC(e,t,n,r){if((n?Object.is(e,t):e===t)||!n&&e==t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;let i=e,a=t;return n&&Object.getPrototypeOf(i)!==Object.getPrototypeOf(a)?!1:r.get(i)===a?!0:(r.set(i,a),Array.isArray(e)===Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)?BC(e,t,n,r):VC(i,a,n,r):!1)}function UC(e,t){try{if(e instanceof t)return!0}catch{}try{return!!t(e)}catch{return!1}}function WC(e,t){for(let[n,r]of Object.entries(t)){let t=e[n];if(r instanceof RegExp){if(typeof t!=`string`||!r.test(t))return!1}else if(t!==r)return!1}return!0}function GC(e,t){if(t===void 0)return!0;if(t instanceof RegExp){let n=e instanceof Error?e.message:String(e);return t.test(n)}return typeof t==`function`?UC(e,t):t&&typeof t==`object`?!e||typeof e!=`object`?!1:WC(e,t):!1}function KC(e){let t=(e,t)=>{if(!e)throw zC(t,()=>new LC({message:`The expression evaluated to a falsy value`,actual:e,expected:!0,operator:`==`}))},n=((e,n)=>t(e,n)),r=(e,t,n)=>{if(!Object.is(e,t))throw zC(n,()=>new LC({actual:e,expected:t,operator:`strictEqual`}))},i=(t,n,i)=>{if(e){r(t,n,i);return}if(t!=n)throw zC(i,()=>new LC({actual:t,expected:n,operator:`==`}))},a=(e,t,n)=>{if(Object.is(e,t))throw zC(n,()=>new LC({actual:e,expected:t,operator:`notStrictEqual`}))},o=(t,n,r)=>{if(e){a(t,n,r);return}if(t==n)throw zC(r,()=>new LC({actual:t,expected:n,operator:`!=`}))},s=(e,t,n)=>{if(!HC(e,t,!0,new WeakMap))throw zC(n,()=>new LC({actual:e,expected:t,operator:`deepStrictEqual`}))},c=(t,n,r)=>{if(e){s(t,n,r);return}if(!HC(t,n,!1,new WeakMap))throw zC(r,()=>new LC({actual:t,expected:n,operator:`deepEqual`}))},l=(e,t,n)=>{if(HC(e,t,!0,new WeakMap))throw zC(n,()=>new LC({actual:e,expected:t,operator:`notDeepStrictEqual`}))};return n.ok=t,n.equal=i,n.notEqual=o,n.strictEqual=r,n.notStrictEqual=a,n.deepEqual=c,n.deepStrictEqual=s,n.notDeepEqual=(t,n,r)=>{if(e){l(t,n,r);return}if(HC(t,n,!1,new WeakMap))throw zC(r,()=>new LC({actual:t,expected:n,operator:`notDeepEqual`}))},n.notDeepStrictEqual=l,n.throws=(e,t,n)=>{let r,i=!1;try{e()}catch(e){r=e,i=!0}if(!i)throw zC(typeof t==`string`?t:n,()=>new LC({message:`Missing expected exception`,operator:`throws`}));if(!(typeof t==`string`||t instanceof Error)&&!GC(r,t))throw zC(n,()=>new LC({message:`Got unwanted exception`,actual:r,operator:`throws`}))},n.doesNotThrow=(e,t)=>{try{e()}catch(e){throw zC(t,()=>new LC({message:`Got unwanted exception`,actual:e,operator:`doesNotThrow`}))}},n.fail=e=>{throw zC(e,()=>new LC({message:`Failed`,operator:`fail`}))},n.AssertionError=LC,n}const qC=KC(!0);qC.strict=qC;const JC=KC(!1);JC.strict=qC;const YC=Symbol.for(`nodejs.util.inspect.custom`),XC=Symbol.for(`nodejs.util.promisify.custom`);function ZC(e){return`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}'`}function QC(e){if(e===null)return`null`;let t=typeof e;if(t===`string`)return ZC(e);if(t===`number`)return Object.is(e,-0)?`-0`:String(e);if(t===`bigint`)return`${String(e)}n`;if(t===`boolean`||t===`undefined`)return String(e);if(t===`symbol`)return e.toString();if(t===`function`){let t=e.name;return t?`[Function: ${t}]`:`[Function (anonymous)]`}return null}function $C(e){return e instanceof RegExp?e.toString():e instanceof Date?Number.isNaN(e.getTime())?`Invalid Date`:e.toISOString():e instanceof Error?e.stack||`${e.name}: ${e.message}`:null}function ew(e,t,n){if(Array.isArray(e))return e.length===0?`[]`:`[ ${e.map(e=>tw(e,t+1,n)).join(`, `)} ]`;if(e instanceof Map){let r=[...e].map(([e,r])=>`${tw(e,t+1,n)} => ${tw(r,t+1,n)}`);return`Map(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}if(e instanceof Set){let r=[...e].map(e=>tw(e,t+1,n));return`Set(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}let r=Object.keys(e),i=e.constructor?e.constructor.name:``,a=i&&i!==`Object`?`${i} `:``;return r.length===0?`${a}{}`:`${a}{ ${r.map(r=>`${/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)?r:ZC(r)}: ${tw(e[r],t+1,n)}`).join(`, `)} }`}function tw(e,t,n){let r=QC(e);if(r!==null)return r;let i=e,a=$C(i);if(a!==null)return a;let o=i[YC];if(typeof o==`function`)try{return String(o.call(i,n.maxDepth,n.opts))}catch{}if(n.seen.has(e))return`[Circular *1]`;if(n.maxDepth!==null&&t>n.maxDepth)return Array.isArray(e)?`[Array]`:`[Object]`;n.seen.add(e);try{return ew(i,t,n)}finally{n.seen.delete(e)}}function nw(e,t={}){let n=t.depth===void 0?2:t.depth;return tw(e,0,{seen:new Set,maxDepth:n,opts:t})}function rw(e,t,n,r){if(e===`%%`)return`%`;if(n.i>=t.length)return e;let i=t[n.i];switch(e){case`%s`:return n.i++,typeof i==`string`?i:typeof i==`bigint`?`${String(i)}n`:i==null||typeof i==`number`||typeof i==`boolean`?String(i):nw(i,{depth:r.depth===void 0?2:r.depth});case`%d`:return n.i++,typeof i==`bigint`?`${String(i)}n`:Number.isNaN(Number(i))?`NaN`:String(Number(i));case`%i`:return n.i++,typeof i==`bigint`?`${String(i)}n`:String(Number.parseInt(i,10));case`%f`:return n.i++,String(typeof i==`bigint`?i:Number.parseFloat(i));case`%j`:n.i++;try{return JSON.stringify(i)??`undefined`}catch{return`[Circular]`}case`%o`:return n.i++,nw(i,{depth:4});case`%O`:return n.i++,nw(i,{depth:null});case`%c`:return n.i++,``;default:return e}}function iw(e,...t){let n=t[0];if(typeof n!=`string`)return t.map(e=>typeof e==`string`?e:nw(e)).join(` `);let r={i:1},i=n.replace(/%[sdifjoOc%]/g,n=>rw(n,t,r,e));for(;r.i<t.length;r.i++){let e=t[r.i];i+=` ${typeof e==`string`?e:nw(e)}`}return i}function aw(...e){return iw({},...e)}function ow(e,t){if(e==null)throw TypeError(`The constructor to "inherits" must not be null or undefined`);if(t==null)throw TypeError(`The super constructor to "inherits" must not be null or undefined`);if(t.prototype===void 0)throw TypeError(`The super constructor to "inherits" must have a prototype`);e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype)}function sw(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type function`);let t=e[XC];if(t){if(typeof t!=`function`)throw TypeError(`The [util.promisify.custom] property must be of type function`);return t}function n(...t){return new Promise((n,r)=>{e.call(this,...t,(e,...t)=>{if(e){r(e);return}n(t.length>1?t:t[0])})})}return Object.setPrototypeOf(n,Object.getPrototypeOf(e)),Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)),n}const cw=nw;cw.custom=YC;const lw=sw;lw.custom=XC;const uw={format:aw,formatWithOptions:iw,inspect:cw,inherits:ow,promisify:lw};function dw(e){return typeof e==`string`?new Uint8Array(DC(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function fw(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 pw(e,t,n){return DC(e(dw(t),fw(n)))}function mw(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=pw(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const hw={gzipSync:(e,t)=>pw(US,e,t),gunzipSync:(e,t)=>pw(qS,e,t),deflateSync:(e,t)=>pw(VS,e,t),inflateSync:(e,t)=>pw(qS,e,t),deflateRawSync:(e,t)=>pw(HS,e,t),inflateRawSync:(e,t)=>pw(JS,e,t),gzip:(e,t,n)=>mw(US,e,t,n),gunzip:(e,t,n)=>mw(qS,e,t,n),deflate:(e,t,n)=>mw(VS,e,t,n),inflate:(e,t,n)=>mw(qS,e,t,n),deflateRaw:(e,t,n)=>mw(HS,e,t,n),inflateRaw:(e,t,n)=>mw(JS,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}},gw={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
|
|
4853
4853
|
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function _w(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 vw(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const yw={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:_w,pathToFileURL:vw};var bw=class{_events=new Map;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}addListener(e,t){return this.on(e,t)}off(e,t){let n=this._events.get(e);if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&this._events.delete(e)}return this}removeListener(e,t){return this.off(e,t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}removeAllListeners(e){return e===void 0?this._events.clear():this._events.delete(e),this}listenerCount(e){return this._events.get(e)?.length??0}listeners(e){return[...this._events.get(e)??[]]}};const xw=Object.assign(bw,{EventEmitter:bw,default:bw});var Sw=class{_events=new Map;writable=!0;readable=!0;on(e,t){let n=this._events.get(e);return n?n.push(t):this._events.set(e,[t]),this}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};return this.on(e,n)}off(e,t){let n=this._events.get(e);if(n){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}return this}emit(e,...t){let n=this._events.get(e);if(!n||n.length===0)return!1;for(let e of[...n])e(...t);return!0}pipe(e){return e}removeListener(e,t){return this.off(e,t)}removeAllListeners(){return this._events.clear(),this}},Cw=class extends Sw{read(){return null}destroy(){return this}},ww=class extends Sw{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},Tw=class extends Sw{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const Ew={Readable:Cw,Writable:ww,Transform:Tw,PassThrough:class extends Tw{},Stream:Sw};let Dw=1;function Ow(e){if(typeof e==`string`)return e;if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}return e==null?``:String(e)}function kw(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?DC(e):DC(e).toString(t)}function Aw(e,t){if(e.length===0)return kw(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function jw(e,t,n){t.length>0&&e.emit(`data`,kw(t,n)),e.readable=!1,e.emit(`end`)}function Mw(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(Ow(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(Ow(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var Nw=class extends bw{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=Dw++,this.spawnfile=n,this.spawnargs=r,this.stdout=new Cw,this.stderr=new Cw,this.stdin=Mw(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){jw(this.stdout,e.stdout,t),jw(this.stderr,e.stderr,t),this.exitCode=e.exitCode;let n=this.killed?null:e.exitCode,r=this.killed?this.signalCode:null;this.emit(`exit`,n,r),this.emit(`close`,n,r)}kill(e=`SIGTERM`){return this.killed=!0,this.signalCode=e,this.handle.kill(e).catch(()=>{}),!0}};function Pw(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new Nw(o,r,i,a);return n.input!==void 0&&s.stdin.write(Ow(n.input)),queueMicrotask(()=>o.stdin.end()),s},n=(e,t,n,r)=>{if(typeof r!=`function`)return;let i=[],a=[];e.stdout.on(`data`,e=>i.push(e)),e.stderr.on(`data`,e=>a.push(e)),e.once(`error`,e=>r(e,Aw(i,t),Aw(a,t))),e.once(`close`,(o,s)=>{let c=Aw(i,t),l=Aw(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${Ow(l)}`),{code:o===null?void 0:o,killed:e.killed,signal:s??null,cmd:n}),c,l)})},r=(e,r,i)=>{let a=typeof r==`function`?r:i,o=r&&typeof r==`object`?r:{},s=o.encoding===void 0?`utf8`:o.encoding,c=t(e,o,s,e,[]);return n(c,s,e,a),c},i=(e,r,i,a)=>{let o=[],s={},c;Array.isArray(r)?(o=r,typeof i==`function`?c=i:(s=i??{},c=typeof a==`function`?a:void 0)):typeof r==`function`?c=r:r&&typeof r==`object`&&(s=r,c=typeof i==`function`?i:void 0);let l=s.encoding===void 0?`utf8`:s.encoding,u=[e,...o],d=t(u,s,l,e,o);return n(d,l,u.join(` `),c),d},a=(e,n,r)=>{let i=[],a={};Array.isArray(n)?(i=n,a=r??{}):n&&typeof n==`object`&&(a=n);let o=a.encoding===void 0?`buffer`:a.encoding,s=a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i];return t(s,a,o,e,i)},o=(e,t)=>new Promise((n,i)=>{r(e,t,(e,t,r)=>{if(e){i(Object.assign(e,{stdout:t,stderr:r}));return}n({stdout:t,stderr:r})})}),s=(e,t,n)=>new Promise((r,a)=>{i(e,Array.isArray(t)?t:[],Array.isArray(t)?n:t,(e,t,n)=>{if(e){a(Object.assign(e,{stdout:t,stderr:n}));return}r({stdout:t,stderr:n})})}),c=e=>()=>{throw Error(`child_process.${e} is not available in the browser realm`)},l=(e,t)=>{Object.defineProperty(e,XC,{value:t,enumerable:!1,configurable:!0})};return l(r,o),l(i,s),{exec:r,execFile:i,spawn:a,execSync:c(`execSync`),spawnSync:c(`spawnSync`),execFileSync:c(`execFileSync`),fork:c(`fork`),ChildProcess:Nw}}function Fw(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 Iw=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 };`)}},Lw=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=Fw(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 Iw(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 Iw(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?.())}},Rw=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 Lw(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()}},zw=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 Lw(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 Rw(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 Bw(e){let t=async t=>new zw(e),n=async(t,n)=>new zw(e);return{chromium:{launch:t,connect:n,connectOverCDP:n},firefox:{launch:t,connect:n},webkit:{launch:t,connect:n}}}const Vw=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`]),Hw={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 Uw(e,t){let n=Hw[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function Ww(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function Gw(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function Kw(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function qw(e){let t=Ww(e.argv[1]??``),n=Kw(t,`references`),r=Kw(t,`assets`),i=Kw(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)+`
|
|
4854
|
-
`),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 ${Gw(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}function Jw(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function Yw(e){let t=Jw(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function Xw(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function Zw(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function Qw(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var $w=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=Jw(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=Yw(Jw(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=Yw(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=Yw(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}readFile(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n||n.isDirectory)throw Xw(t);if(n.truncated)throw Zw(t);return n.content}writeFile(e,t){this.touched=!0;let n=Jw(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1})}exists(e){this.touched=!0;let t=Jw(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n)throw Xw(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.content.byteLength}}readdir(e){this.touched=!0;let t=Jw(e);if(!this.tree.get(t)?.isDirectory)throw Xw(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=Jw(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=Yw(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw Xw(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0})}rm(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r)throw Xw(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e)}this.tree.delete(n)}copyFile(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r||r.isDirectory)throw Xw(n);let i=Jw(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1})}rename(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r)throw Xw(n);let i=Jw(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n)}unlink(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n)throw Xw(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t)}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=Jw(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!Qw(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function eT(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var tT=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function nT(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function rT(e,t){let n;try{n=await e.call(`vfs`,`snapshot`,[t])}catch{n={entries:[]}}return new $w(n)}function iT(e){return{usbBridge:JT(e),serialBridge:XT(e),hidBridge:QT(e)}}async function aT(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=cT(i,a),{processShim:s,getDidCallProcessExit:c}=lT(e,i,a),l=!!e.env?.NO_COLOR,u=$S({isTTY:!l,noColor:l}),d=ZS({writeStdout:i,writeStderr:a,exit:e=>{throw new tT(e)},color:u}),f=new _v(t),p=_T(f,C),m=await rT(f,e.cwd);Object.assign(p,vT(m,e.cwd));let h=dT(f,m,e.cwd),g=mT(h,{cwd:e.cwd}),_=qw({argv:e.argv,fs:p,exec:h}),v=MT(f),{usbBridge:y,serialBridge:b,hidBridge:x}=iT(f),S=uy({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,jT(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=hT({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=eT(T),D=await xT(f,e.code,e.cwd,T),O=wT({graph:D,fsBridge:p,processShim:s,childProcess:Pw(h),nodeConsole:o,sliccyModules:w,shimmedPackages:CT(f)}).require,k={exports:{},filename:e.filename},A=D.entrySource!==void 0,j=D.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let N=await AT(j,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,A);await oT(f,m,a),c()||await sT(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:N})}async function oT(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){n(`[sync-fs] flush failed: ${e instanceof Error?e.message:String(e)}\n`)}}async function sT(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 cT(e,t){return{log:(...t)=>e(`${t.map(nT).join(` `)}
|
|
4855
|
-
`),info:(...t)=>e(`${t.map(
|
|
4856
|
-
`),warn:(...e)=>t(`${e.map(
|
|
4857
|
-
`),error:(...e)=>t(`${e.map(
|
|
4858
|
-
`)}}function lT(e,t,n){let r=!!e.env?.NO_COLOR,i=gT(e.stdin??``),a=XS(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new tT(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function uT(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function dT(e,t,n){let r=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),t.resetBaseline()},i=async(r=!1)=>{if(t?.wasUsed())try{let i=await e.call(`vfs`,`snapshot`,[n]);r?t.applySnapshotPreservingMutations(i):t.applySnapshot(i)}catch{}},a=async t=>{await r();try{return await e.call(`exec`,`run`,[t])}finally{await i()}},o=async t=>{await r();try{return await e.call(`exec`,`spawn`,[t])}finally{await i()}},s=1,c=Object.assign(a,{spawn:o,start:(t,n)=>{let a=s++,o=[],c=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(c||u||l)return;l=!0;let s=o.length>0?o.join(``):n?.stdin,p={};s!==void 0&&(p.stdin=s),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await r(),u){await i(!0);return}c=!0;let n=await e.call(`exec`,`start`,[a,t,p]);await i(!0),d(n)}catch(e){await i(!0),f(e)}})()};return{kill:t=>c?e.call(`exec`,`kill`,[a,t]):(u=!0,d({stdout:``,stderr:``,exitCode:uT(t)}),Promise.resolve(!0)),stdin:{write:e=>{!c&&!u&&o.push(e)},end:()=>m()},done:p}}});return c.exec=c,c}function fT(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 pT(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`,fT(JSON.stringify(t.schema)));let i=t.readOnly===void 0?`/workspace/`:Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly),a=t.cwd===void 0?n||`.`:String(t.cwd),o=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,`--read-only`,i,a,o,String(e)]}function mT(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(pT(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 hT(e){return{...e,time:rC,fmt:fC,pool:pC}}function gT(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}function _T(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function vT(e,t){function n(e){return e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e}return{readFileSync(t,r){let i=typeof r==`string`?r:r?.encoding,a=e.readFile(n(t));if(i===`utf8`||i===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(t,r){let i;i=typeof r==`string`?new TextEncoder().encode(r):r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new TextEncoder().encode(String(r)),e.writeFile(n(t),i)},existsSync(t){return e.exists(n(t))},mkdirSync(t,r){e.mkdir(n(t),r?.recursive)},statSync(t){let r=e.stat(n(t));return{isFile:()=>r.isFile,isDirectory:()=>r.isDirectory,size:r.size}},readdirSync(t){return e.readdir(n(t))},rmSync(t,r){let i=n(t);r?.force&&!e.exists(i)||e.rm(i,r?.recursive)},copyFileSync(t,r){e.copyFile(n(t),n(r))},mkdtempSync(t){return e.mkdtemp(n(t))},unlinkSync(t){e.unlink(n(t))},renameSync(t,r){e.rename(n(t),n(r))}}}function yT(e,t){return e?.startsWith(`/`)?eT(e):t}function bT(e){return e.includes(`require`)||e.includes(`import`)}async function xT(e,t,n,r){return bT(t)?e.call(`module`,`buildGraph`,[t,yT(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function ST(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 CT(e){return{playwright:Bw(e)}}function wT(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={}}=e,c=new Map(t.files.map(e=>[e.path,e.cjsSource])),l=new Map(t.files.map(e=>[e.path,e.kind])),u=new Map,d=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:DT(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=TT(t,n,r,i);if(a.hit)return a;if(Vw.has(t))throw Uw(e,t);if(en.has(t))throw kT(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},f=(e,n)=>{let r=d(n);if(r.hit)return r.value;let i=e?.[n];if(i)return p(i);throw n in t.errors?Error(t.errors[n]):ET(n)};function p(e){let n=u.get(e);if(n)return n.exports;let i=c.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};u.set(e,o);let s=n=>f(t.edges[e],n),d=eT(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,d,e,r,a,globalThis.Buffer,globalThis),l.get(e)===`cjs`&&ST(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function TT(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:wC}:e===`crypto`?{hit:!0,value:IC}: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:JC}:e===`assert/strict`?{hit:!0,value:qC}:e===`util`?{hit:!0,value:uw}:e===`events`?{hit:!0,value:xw}:e===`os`?{hit:!0,value:gw}:e===`stream`?{hit:!0,value:Ew}:e===`url`?{hit:!0,value:yw}:e===`zlib`?{hit:!0,value:hw}:{hit:!1}}function ET(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 DT(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 OT={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function kT(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${OT[t]||``}`)}async function AT(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";
|
|
4859
|
-
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof tT?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function jT(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;return e?.body!==void 0&&e?.body!==null&&e?.body!==``&&(a=typeof e.body==`string`?e.body:String(e.body)),{method:r,headers:i,body:a}}function MT(e){return{findTab:t=>e.call(`browser`,`findTab`,[VT(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,HT(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[NT(t),PT(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[NT(t),PT(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[NT(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[NT(t),n]),fetch:(t,n,r={})=>BT(n,r).then(n=>e.call(`browser`,`evalAsync`,[NT(t),n])),websocket:UT(e)}}function NT(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 PT(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 FT(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 IT(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:FT(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function LT(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:FT(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:FT(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:FT(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await IT(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function RT(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 zT(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 BT(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 LT(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=RT(c),d=zT(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function VT(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 HT(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function UT(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=NT(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`,[])}}}function WT(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 GT(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function KT(e){return e==null?[]:Array.isArray(e)?e:[e]}function qT(e,t){let n=t.handle,r=e=>({status:e.status,data:GT(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,WT(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,WT(r)])}}function JT(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>qT(e,t)),request:async t=>qT(e,await e.call(`usb`,`request`,[KT(t)]))}}function YT(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?WT(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,WT(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function XT(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>YT(e,t)),request:async t=>YT(e,await e.call(`serial`,`request`,[KT(t)]))}}function ZT(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:GT(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,WT(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,WT(r)]),receiveFeatureReport:async t=>GT((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 QT(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>ZT(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[KT(t)]))[0];if(!n)throw Error(`No device selected.`);return ZT(e,n)}}}function $T(){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 eE(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=$T(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&aT(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 tE(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=$T(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Ov(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 nE=eE(),rE=tE();function iE(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?oE():rE({kind:e,ctx:t}):typeof Worker<`u`?aE():nE({kind:e,ctx:t})}function aE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return sE(new Worker(new URL(`/assets/js-realm-worker-B4uCLm52.js`,``+import.meta.url),{type:`module`}))}function oE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return sE(new Worker(new URL(`/assets/py-realm-worker-VuYxvTG9.js`,``+import.meta.url),{type:`module`}))}function sE(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function cE(){if(cn())return decodeURIComponent(un(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var lE=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Oe,analyzeMetafileSync:()=>Me,build:()=>we,buildSync:()=>ke,context:()=>Te,default:()=>Be,formatMessages:()=>De,formatMessagesSync:()=>je,initialize:()=>Re,stop:()=>Ne,transform:()=>Ee,transformSync:()=>Ae,version:()=>Ce}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4854
|
+
`),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 ${Gw(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}function Jw(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function Yw(e){let t=Jw(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function Xw(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function Zw(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function Qw(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var $w=class{tree=new Map;initialPaths=new Set;initialContent=new Map;initialIsDirectory=new Map;mkdtempCounter=0;tombstones=new Set;removedDirs=new Set;touched=!1;constructor(e){this.loadSnapshot(e)}loadSnapshot(e){this.tree=new Map,this.tombstones=new Set,this.removedDirs=new Set,this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map,this.tree.set(`/`,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(`/`),this.initialIsDirectory.set(`/`,!0);for(let t of e.entries){let e=Jw(t.path);this.tree.set(e,{content:t.content,isDirectory:t.isDirectory,truncated:t.truncated,size:t.size}),this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}for(let t of e.entries){let e=Yw(Jw(t.path));for(;e!==`/`&&!this.tree.has(e);)this.tree.set(e,{content:new Uint8Array,isDirectory:!0}),this.initialPaths.add(e),this.initialIsDirectory.set(e,!0),e=Yw(e)}}wasUsed(){return this.touched}applySnapshot(e){this.loadSnapshot(e)}applySnapshotPreservingMutations(e){let t=this.getMutations();this.loadSnapshot(e);for(let e of t.deleted){if(this.tree.get(e)?.isDirectory){let t=e===`/`?`/`:e+`/`;for(let n of Array.from(this.tree.keys()))n!==e&&n.startsWith(t)&&this.tree.delete(n)}this.tree.delete(e)}for(let e of t.created)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:e.isDirectory});for(let e of t.modified)this.ensureParentDirs(e.path),this.tree.set(e.path,{content:e.content,isDirectory:!1})}resetBaseline(){this.initialPaths=new Set,this.initialContent=new Map,this.initialIsDirectory=new Map;for(let[e,t]of this.tree.entries())this.initialPaths.add(e),this.initialIsDirectory.set(e,t.isDirectory),t.isDirectory||this.initialContent.set(e,t.content)}ensureParentDirs(e){let t=Yw(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}commitWrite(e,t){this.writeFile(e,t);let n=Jw(e);for(this.initialContent.set(n,t);n!==`/`;){let e=this.tree.get(n);e&&(this.initialPaths.add(n),this.initialIsDirectory.set(n,e.isDirectory)),n=Yw(n)}}readFile(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n||n.isDirectory)throw Xw(t);if(n.truncated)throw Zw(t);return n.content}writeFile(e,t){this.touched=!0;let n=Jw(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1}),this.tombstones.delete(n),this.removedDirs.delete(n)}exists(e){this.touched=!0;let t=Jw(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n)throw Xw(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.size??n.content.byteLength}}readdir(e){this.touched=!0;let t=Jw(e);if(!this.tree.get(t)?.isDirectory)throw Xw(t);let n=t===`/`?`/`:t+`/`,r=new Set;for(let e of this.tree.keys()){if(e===t||e===`/`||!e.startsWith(n))continue;let i=e.slice(n.length).split(`/`)[0];i&&r.add(i)}return Array.from(r)}mkdir(e,t){this.touched=!0;let n=Jw(e);if(this.tree.has(n)){if(this.tree.get(n).isDirectory)return;throw Object.assign(Error(`EEXIST: file already exists, '${n}'`),{code:`EEXIST`})}let r=Yw(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw Xw(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0}),this.tombstones.delete(n),this.removedDirs.delete(n)}rm(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r)throw Xw(n);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,r=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));if(r.length>0&&!t)throw Object.assign(Error(`ENOTEMPTY: directory not empty, '${n}'`),{code:`ENOTEMPTY`});for(let e of r)this.tree.delete(e),this.tombstones.add(e);t&&this.removedDirs.add(n)}this.tree.delete(n),this.tombstones.add(n)}copyFile(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r||r.isDirectory)throw Xw(n);if(r.truncated)throw Zw(n);let i=Jw(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1}),this.tombstones.delete(i),this.removedDirs.delete(i)}rename(e,t){this.touched=!0;let n=Jw(e),r=this.tree.get(n);if(!r)throw Xw(n);let i=Jw(t);if(r.isDirectory){let e=n===`/`?`/`:n+`/`,t=Array.from(this.tree.keys()).filter(t=>t!==n&&t.startsWith(e));this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n);for(let e of t){let t=this.tree.get(e),r=i+e.slice(n.length);this.tree.set(r,t),this.tree.delete(e)}this.tombstones.add(n),this.removedDirs.add(n),this.tombstones.delete(i),this.removedDirs.delete(i);return}this.ensureParentDirs(i),this.tree.set(i,r),this.tree.delete(n),this.tombstones.add(n),this.tombstones.delete(i),this.removedDirs.delete(i)}unlink(e){this.touched=!0;let t=Jw(e),n=this.tree.get(t);if(!n)throw Xw(t);if(n.isDirectory)throw Object.assign(Error(`EISDIR: illegal operation on a directory, unlink '${t}'`),{code:`EISDIR`});this.tree.delete(t),this.tombstones.add(t)}isTombstoned(e){let t=Jw(e);if(this.tombstones.has(t))return!0;for(let e of this.removedDirs)if(t===e||t.startsWith(`${e}/`))return!0;return!1}mkdtemp(e){this.touched=!0;for(let t=0;t<100;t++){let t=`_${String(this.mkdtempCounter).padStart(6,`0`)}`;this.mkdtempCounter++;let n=Jw(e+t);if(!this.tree.has(n))return this.mkdir(n,!0),n}throw Error(`mkdtemp: failed to create unique directory after 100 attempts`)}getMutations(){let e=[],t=[],n=[];for(let[r,i]of this.tree.entries()){if(r===`/`)continue;if(!this.initialPaths.has(r)){e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}let a=this.initialIsDirectory.get(r);if(a!==void 0&&a!==i.isDirectory){n.push(r),e.push({path:r,content:i.content,isDirectory:i.isDirectory});continue}if(!i.isDirectory){let e=this.initialContent.get(r);e&&!Qw(e,i.content)&&t.push({path:r,content:i.content})}}for(let e of this.initialPaths)e!==`/`&&(this.tree.has(e)||n.push(e));return{created:e,modified:t,deleted:n}}};function eT(e){return`slicc-sync-fs-`+e}const tT=`sync-fs-ack`,nT=`sync-fs-res`;function rT(e,t){return Object.assign(Error(`${e}: sync-fs bridge, '${t}'`),{code:e})}function iT(e,t){let n=`/__slicc/fs-sync`+(e.startsWith(`/`)?e:`/${e}`).split(`/`).map(encodeURIComponent).join(`/`);return t?`${n}?op=${t}`:n}function aT(e,t={}){let n=t.timeoutMs??3e4;function r(t,r,i,a){let o=new XMLHttpRequest;try{o.open(t,iT(r,a),!1),o.responseType=`arraybuffer`,o.timeout=n,o.setRequestHeader(`x-slicc-fs-token`,e),i?o.send(new Uint8Array(i)):o.send()}catch{throw rT(`EIO`,r)}return o}function i(e,t){try{let t=new Uint8Array(e.response);return JSON.parse(new TextDecoder().decode(t))}catch{throw rT(`EIO`,t)}}function a(e,t){throw rT(e.getResponseHeader(`x-slicc-fs`)===`1`&&e.getResponseHeader(`x-slicc-fs-errno`)||`EIO`,t)}function o(e){return e.status>=200&&e.status<300&&e.getResponseHeader(`x-slicc-fs`)===`1`}return{readFile(e){let t=r(`GET`,e);if(o(t))return new Uint8Array(t.response);if(t.status>=200&&t.status<300)throw rT(`EIO`,e);a(t,e)},writeFile(e,t){let n=r(`POST`,e,t);if(!o(n)){if(n.status>=200&&n.status<300)throw rT(`EIO`,e);a(n,e)}},stat(e){let t=r(`GET`,e,void 0,`stat`);if(o(t)){let n=i(t,e);if(!n||typeof n.isFile!=`boolean`||typeof n.isDirectory!=`boolean`||typeof n.size!=`number`)throw rT(`EIO`,e);return{isFile:n.isFile,isDirectory:n.isDirectory,size:n.size}}if(t.status>=200&&t.status<300)throw rT(`EIO`,e);a(t,e)},readdir(e){let t=r(`GET`,e,void 0,`readdir`);if(o(t)){let n=i(t,e);if(!Array.isArray(n)||!n.every(e=>typeof e==`string`))throw rT(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw rT(`EIO`,e);a(t,e)},exists(e){let t=r(`GET`,e,void 0,`exists`);if(o(t)){let n=i(t,e);if(typeof n!=`boolean`)throw rT(`EIO`,e);return n}if(t.status>=200&&t.status<300)throw rT(`EIO`,e);a(t,e)}}}function oT(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var sT=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function cT(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function lT(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 $w(r)}function uT(e,t){if(e.syncFsToken)return e=>t(`[sync-fs] snapshot failed, sync metadata will be incomplete: ${e}\n`)}function dT(e){return e.syncFsToken?aT(e.syncFsToken):void 0}function fT(e){return{usbBridge:iE(e),serialBridge:oE(e),hidBridge:cE(e)}}async function pT(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=gT(i,a),{processShim:s,getDidCallProcessExit:c}=_T(e,i,a),l=!!e.env?.NO_COLOR,u=$S({isTTY:!l,noColor:l}),d=ZS({writeStdout:i,writeStderr:a,exit:e=>{throw new sT(e)},color:u}),f=new _v(t),p=TT(f,C),m=await lT(f,e.cwd,uT(e,a));Object.assign(p,OT(m,e.cwd,dT(e)));let h=yT(f,m,e.cwd,a),g=ST(h,{cwd:e.cwd}),_=qw({argv:e.argv,fs:p,exec:h}),v=HT(f),{usbBridge:y,serialBridge:b,hidBridge:x}=fT(f),S=uy({fetch:C});async function C(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,VT(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=CT({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=oT(T),D=await jT(f,e.code,e.cwd,T),O=PT({graph:D,fsBridge:p,processShim:s,childProcess:Pw(h),nodeConsole:o,sliccyModules:w,shimmedPackages:NT(f)}).require,k={exports:{},filename:e.filename},A=D.entrySource!==void 0,j=D.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let N=await BT(j,{process:s,console:o,require:O,module:k,exports:k.exports,fetch:C,__dirname:E,__filename:T},a,A);await mT(f,m,a),c()||await hT(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:N})}async function mT(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 hT(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 gT(e,t){return{log:(...t)=>e(`${t.map(cT).join(` `)}
|
|
4855
|
+
`),info:(...t)=>e(`${t.map(cT).join(` `)}
|
|
4856
|
+
`),warn:(...e)=>t(`${e.map(cT).join(` `)}
|
|
4857
|
+
`),error:(...e)=>t(`${e.map(cT).join(` `)}
|
|
4858
|
+
`)}}function _T(e,t,n){let r=!!e.env?.NO_COLOR,i=wT(e.stdin??``),a=XS(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new sT(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function vT(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function yT(e,t,n,r){let i=async()=>{if(!t?.wasUsed())return;let n=t.getMutations();(n.created.length||n.modified.length||n.deleted.length)&&await e.call(`vfs`,`flushWrites`,[n]),t.resetBaseline()},a=async(i=!1)=>{if(t?.wasUsed())try{let r=await e.call(`vfs`,`snapshot`,[n]);i?t.applySnapshotPreservingMutations(r):t.applySnapshot(r)}catch(e){let t=e instanceof Error?e.message:String(e);r?.(`[sync-fs] re-snapshot after exec failed: ${t}\n`)}},o=async t=>{await i();try{return await e.call(`exec`,`run`,[t])}finally{await a()}},s=async t=>{await i();try{return await e.call(`exec`,`spawn`,[t])}finally{await a()}},c=1,l=Object.assign(o,{spawn:s,start:(t,n)=>{let r=c++,o=[],s=!1,l=!1,u=!1,d,f,p=new Promise((e,t)=>{d=e,f=t}),m=()=>{if(s||u||l)return;l=!0;let c=o.length>0?o.join(``):n?.stdin,p={};c!==void 0&&(p.stdin=c),n?.stdinKind!==void 0&&(p.stdinKind=n.stdinKind),n?.args!==void 0&&(p.args=n.args),(async()=>{try{if(await i(),u){await a(!0);return}s=!0;let n=await e.call(`exec`,`start`,[r,t,p]);await a(!0),d(n)}catch(e){await a(!0),f(e)}})()};return{kill:t=>s?e.call(`exec`,`kill`,[r,t]):(u=!0,d({stdout:``,stderr:``,exitCode:vT(t)}),Promise.resolve(!0)),stdin:{write:e=>{!s&&!u&&o.push(e)},end:()=>m()},done:p}}});return l.exec=l,l}function bT(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 xT(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`,bT(JSON.stringify(t.schema)));let i=t.readOnly===void 0?`/workspace/`:Array.isArray(t.readOnly)?t.readOnly.join(`,`):String(t.readOnly),a=t.cwd===void 0?n||`.`:String(t.cwd),o=t.allowedCommands===void 0?`*`:String(t.allowedCommands);return[`agent`,...r,`--read-only`,i,a,o,String(e)]}function ST(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(xT(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 CT(e){return{...e,time:rC,fmt:fC,pool:pC}}function wT(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}function TT(e,t){function n(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(typeof e==`string`?e:String(e))}async function r(t,n){let r=typeof n==`string`?n:n?.encoding;if(r===null||r===`buffer`){let n=await e.call(`vfs`,`readFileBinary`,[t]),r=globalThis.Buffer;return r?r.from(n instanceof Uint8Array?n:new Uint8Array(n)):n}return e.call(`vfs`,`readFile`,[t])}async function i(t,r){return typeof r==`string`?e.call(`vfs`,`writeFile`,[t,r]):e.call(`vfs`,`writeFileBinary`,[t,n(r)])}async function a(t,r){let i=new Uint8Array;if(await e.call(`vfs`,`exists`,[t])){let n=await e.call(`vfs`,`readFileBinary`,[t]);i=n instanceof Uint8Array?n:new Uint8Array(n)}let a=n(r),o=new Uint8Array(i.byteLength+a.byteLength);o.set(i),o.set(a,i.byteLength),await e.call(`vfs`,`writeFileBinary`,[t,o])}async function o(t,n,r){let i=await e.call(`vfs`,`stat`,[t]);if(i.isFile){let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]);return}if(!i.isDirectory||!r?.recursive)throw Error(`cp: '${t}' is a directory (use {recursive: true})`);await c(n);let a=await e.call(`vfs`,`readDir`,[t]);for(let e of a)await o(`${t}/${e}`,`${n}/${e}`,r)}async function s(t,n){if(n?.force&&!await e.call(`vfs`,`exists`,[t]))return!0;if((await e.call(`vfs`,`stat`,[t])).isFile)return e.call(`vfs`,`rm`,[t]);if(!n?.recursive)throw Error(`rm: '${t}' is a directory (use {recursive: true})`);let r=await e.call(`vfs`,`readDir`,[t]);for(let e of r)await s(`${t}/${e}`,n);return e.call(`vfs`,`rm`,[t])}async function c(t){await e.call(`vfs`,`mkdir`,[t])}async function l(t){for(let n=0;n<5;n++){let n=`${t}${Math.random().toString(36).slice(2,10)+Math.random().toString(36).slice(2,6)}`;if(!await e.call(`vfs`,`exists`,[n]))return await e.call(`vfs`,`mkdir`,[n]),n}throw Error(`mkdtemp: failed to create unique directory after 5 attempts`)}async function u(t,n){try{await e.call(`vfs`,`rename`,[t,n])}catch{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r]),await e.call(`vfs`,`rm`,[t])}}async function d(t){if(!await e.call(`vfs`,`exists`,[t]))throw Object.assign(Error(`ENOENT: no such file or directory, access '${t}'`),{code:`ENOENT`})}let f={readFile:r,readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:i,writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),appendFile:a,cp:o,rm:s,readDir:t=>e.call(`vfs`,`readDir`,[t]),readdir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:(t,n)=>e.call(`vfs`,`mkdir`,[t]),mkdtemp:l,rename:u,access:d,unlink:t=>e.call(`vfs`,`rm`,[t]),rmdir:t=>e.call(`vfs`,`rm`,[t]),copyFile:async(t,n)=>{let r=await e.call(`vfs`,`readFileBinary`,[t]);await e.call(`vfs`,`writeFileBinary`,[n,r])},fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength},promises:null};return f.promises=f,f}function ET(e,t,n=``){return Object.assign(Error(`${e}: sync-fs, ${n?`${n} `:``}'${t}'`),{code:e})}function DT(e){if(typeof e==`string`)return new TextEncoder().encode(e);if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new TextEncoder().encode(String(e))}function OT(e,t,n){function r(e){return Jw(e.startsWith(`/`)?e:t+(t.endsWith(`/`)?``:`/`)+e)}function i(t){try{return e.readFile(t)}catch(r){let i=r?.code;if(n&&!e.isTombstoned(t)&&(i===`ENOENT`||i===`ENOSYNC`))return n.readFile(t);throw r}}function a(t,r){n?(n.writeFile(t,r),e.commitWrite(t,r)):e.writeFile(t,r)}function o(t){if(e.exists(t))return!0;if(!n||e.isTombstoned(t))return!1;try{return n.exists(t)}catch{return!1}}function s(t){try{return e.stat(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.stat(t)}}function c(t){try{return e.readdir(t)}catch(r){let i=r?.code;if(!n||e.isTombstoned(t)||i!==`ENOENT`)throw r;return n.readdir(t)}}let l=e=>({isFile:()=>e.isFile,isDirectory:()=>e.isDirectory,size:e.size}),u=(e,t)=>e===`/`?`/${t}`:`${e}/${t}`;function d(t,n){if(!s(t).isDirectory){a(n,i(t));return}e.mkdir(n,!0);for(let e of c(t))d(u(t,e),u(n,e))}return{readFileSync(e,t){let n=typeof t==`string`?t:t?.encoding,a=i(r(e));if(n===`utf8`||n===`utf-8`)return new TextDecoder().decode(a);let o=globalThis.Buffer;return o?o.from(a):a},writeFileSync(e,t){a(r(e),DT(t))},appendFileSync(e,t){let n=r(e),o=new Uint8Array;try{o=i(n)}catch(e){if(e?.code!==`ENOENT`)throw e}let s=DT(t),c=new Uint8Array(o.byteLength+s.byteLength);c.set(o),c.set(s,o.byteLength),a(n,c)},truncateSync(e,t=0){let n=r(e),o=i(n),s=new Uint8Array(t);s.set(o.subarray(0,Math.min(t,o.byteLength))),a(n,s)},existsSync(e){return o(r(e))},accessSync(e){let t=r(e);if(!o(t))throw ET(`ENOENT`,t,`access`)},mkdirSync(t,n){e.mkdir(r(t),n?.recursive)},statSync(e){return l(s(r(e)))},lstatSync(e){return l(s(r(e)))},realpathSync(e){let t=r(e);if(!o(t))throw ET(`ENOENT`,t,`realpath`);return t},readdirSync(e){return c(r(e))},rmSync(t,n){let i=r(t);n?.force&&!e.exists(i)||e.rm(i,n?.recursive)},rmdirSync(t,n){let i=r(t);if(o(i)&&!s(i).isDirectory)throw ET(`ENOTDIR`,i,`rmdir`);e.rm(i,n?.recursive)},copyFileSync(e,t){a(r(t),i(r(e)))},cpSync(e,t){d(r(e),r(t))},chmodSync(e){let t=r(e);if(!o(t))throw ET(`ENOENT`,t,`chmod`)},mkdtempSync(t){return e.mkdtemp(r(t))},unlinkSync(t){e.unlink(r(t))},renameSync(t,n){e.rename(r(t),r(n))}}}function kT(e,t){return e?.startsWith(`/`)?oT(e):t}function AT(e){return e.includes(`require`)||e.includes(`import`)}async function jT(e,t,n,r){return AT(t)?e.call(`module`,`buildGraph`,[t,kT(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function MT(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 NT(e){return{playwright:Bw(e)}}function PT(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o,shimmedPackages:s={}}=e,c=new Map(t.files.map(e=>[e.path,e.cjsSource])),l=new Map(t.files.map(e=>[e.path,e.kind])),u=new Map,d=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:LT(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=FT(t,n,r,i);if(a.hit)return a;if(Vw.has(t))throw Uw(e,t);if(en.has(t))throw zT(e,t);return t in s?{hit:!0,value:s[t]}:{hit:!1}},f=(e,n)=>{let r=d(n);if(r.hit)return r.value;let i=e?.[n];if(i)return p(i);throw n in t.errors?Error(t.errors[n]):IT(n)};function p(e){let n=u.get(e);if(n)return n.exports;let i=c.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};u.set(e,o);let s=n=>f(t.edges[e],n),d=oT(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,s,d,e,r,a,globalThis.Buffer,globalThis),l.get(e)===`cjs`&&MT(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function FT(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:wC}:e===`crypto`?{hit:!0,value:IC}: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:JC}:e===`assert/strict`?{hit:!0,value:qC}:e===`util`?{hit:!0,value:uw}:e===`events`?{hit:!0,value:xw}:e===`os`?{hit:!0,value:gw}:e===`stream`?{hit:!0,value:Ew}:e===`url`?{hit:!0,value:yw}:e===`zlib`?{hit:!0,value:hw}:{hit:!1}}function IT(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 LT(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 RT={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function zT(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${RT[t]||``}`)}async function BT(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";
|
|
4859
|
+
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof sT?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function VT(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;return e?.body!==void 0&&e?.body!==null&&e?.body!==``&&(a=typeof e.body==`string`?e.body:String(e.body)),{method:r,headers:i,body:a}}function HT(e){return{findTab:t=>e.call(`browser`,`findTab`,[ZT(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,QT(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[UT(t),WT(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[UT(t),WT(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[UT(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[UT(t),n]),fetch:(t,n,r={})=>XT(n,r).then(n=>e.call(`browser`,`evalAsync`,[UT(t),n])),websocket:$T(e)}}function UT(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 WT(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 GT(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 KT(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:GT(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function qT(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:GT(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:GT(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:GT(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await KT(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function JT(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 YT(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 XT(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 qT(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=JT(c),d=YT(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function ZT(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 QT(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function $T(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=UT(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`,[])}}}function eE(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 tE(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function nE(e){return e==null?[]:Array.isArray(e)?e:[e]}function rE(e,t){let n=t.handle,r=e=>({status:e.status,data:tE(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,eE(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,eE(r)])}}function iE(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>rE(e,t)),request:async t=>rE(e,await e.call(`usb`,`request`,[nE(t)]))}}function aE(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?eE(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,eE(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function oE(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>aE(e,t)),request:async t=>aE(e,await e.call(`serial`,`request`,[nE(t)]))}}function sE(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:tE(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,eE(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,eE(r)]),receiveFeatureReport:async t=>tE((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 cE(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>sE(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[nE(t)]))[0];if(!n)throw Error(`No device selected.`);return sE(e,n)}}}function lE(){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 uE(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=lE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&pT(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 dE(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=lE(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&Ov(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 fE=uE(),pE=dE();function mE(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?gE():pE({kind:e,ctx:t}):typeof Worker<`u`?hE():fE({kind:e,ctx:t})}function hE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return _E(new Worker(new URL(`/assets/js-realm-worker-vnTP6x9C.js`,``+import.meta.url),{type:`module`}))}function gE(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return _E(new Worker(new URL(`/assets/py-realm-worker-VuYxvTG9.js`,``+import.meta.url),{type:`module`}))}function _E(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,addEventListener:(t,n,r)=>e.addEventListener(t,n,r),removeEventListener:(t,n)=>e.removeEventListener(t,n),terminate(){if(!n){n=!0;try{e.terminate()}catch{}}}}}function vE(){if(cn())return decodeURIComponent(un(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var yE=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>Oe,analyzeMetafileSync:()=>Me,build:()=>we,buildSync:()=>ke,context:()=>Te,default:()=>Be,formatMessages:()=>De,formatMessagesSync:()=>je,initialize:()=>Re,stop:()=>Ne,transform:()=>Ee,transformSync:()=>Ae,version:()=>Ce}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=(r&1)==0;r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
|
|
4860
4860
|
|
|
4861
4861
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
4862
4862
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
@@ -5550,8 +5550,8 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
5550
5550
|
})(postMessage)`],{type:`text/javascript`});r=new Worker(URL.createObjectURL(e))}else{let e=(e=>{var t=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())});let n,r={};for(let e=self;e;e=Object.getPrototypeOf(e))for(let t of Object.getOwnPropertyNames(e))t in r||Object.defineProperty(r,t,{get:()=>self[t]});(()=>{let e=()=>{let e=Error(`not implemented`);return e.code=`ENOSYS`,e};if(!r.fs){let t=``;r.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1,O_DIRECTORY:-1},writeSync(e,n){t+=i.decode(n);let r=t.lastIndexOf(`
|
|
5551
5551
|
`);return r!=-1&&(console.log(t.substring(0,r)),t=t.substring(r+1)),n.length},write(t,n,r,i,a,o){if(r!==0||i!==n.length||a!==null){o(e());return}o(null,this.writeSync(t,n))},chmod(t,n,r){r(e())},chown(t,n,r,i){i(e())},close(t,n){n(e())},fchmod(t,n,r){r(e())},fchown(t,n,r,i){i(e())},fstat(t,n){n(e())},fsync(e,t){t(null)},ftruncate(t,n,r){r(e())},lchown(t,n,r,i){i(e())},link(t,n,r){r(e())},lstat(t,n){n(e())},mkdir(t,n,r){r(e())},open(t,n,r,i){i(e())},read(t,n,r,i,a,o){o(e())},readdir(t,n){n(e())},readlink(t,n){n(e())},rename(t,n,r){r(e())},rmdir(t,n){n(e())},stat(t,n){n(e())},symlink(t,n,r){r(e())},truncate(t,n,r){r(e())},unlink(t,n){n(e())},utimes(t,n,r,i){i(e())}}}if(r.process||={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw e()},pid:-1,ppid:-1,umask(){throw e()},cwd(){throw e()},chdir(){throw e()}},r.path||={resolve(...e){return e.join(`/`)}},!r.crypto)throw Error(`globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)`);if(!r.performance)throw Error(`globalThis.performance is not available, polyfill required (performance.now only)`);if(!r.TextEncoder)throw Error(`globalThis.TextEncoder is not available, polyfill required`);if(!r.TextDecoder)throw Error(`globalThis.TextDecoder is not available, polyfill required`);let n=new TextEncoder(`utf-8`),i=new TextDecoder(`utf-8`);r.Go=class{constructor(){this.argv=[`js`],this.env={},this.exit=e=>{e!==0&&console.warn(`exit code:`,e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let e=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},t=e=>this.mem.getUint32(e+0,!0)+this.mem.getInt32(e+4,!0)*4294967296,a=e=>{let t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;let n=this.mem.getUint32(e,!0);return this._values[n]},o=(e,t)=>{let n=2146959360;if(typeof t==`number`&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,n,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let r=this._ids.get(t);r===void 0&&(r=this._idPool.pop(),r===void 0&&(r=this._values.length),this._values[r]=t,this._goRefCounts[r]=0,this._ids.set(t,r)),this._goRefCounts[r]++;let i=0;switch(typeof t){case`object`:t!==null&&(i=1);break;case`string`:i=2;break;case`symbol`:i=3;break;case`function`:i=4;break}this.mem.setUint32(e+4,n|i,!0),this.mem.setUint32(e,r,!0)},s=e=>{let n=t(e+0),r=t(e+8);return new Uint8Array(this._inst.exports.mem.buffer,n,r)},c=e=>{let n=t(e+0),r=t(e+8),i=Array(r);for(let e=0;e<r;e++)i[e]=a(n+e*8);return i},l=e=>{let n=t(e+0),r=t(e+8);return i.decode(new DataView(this._inst.exports.mem.buffer,n,r))},u=(e,t)=>(this._inst.exports.testExport0(),this._inst.exports.testExport(e,t)),d=Date.now()-performance.now();this.importObject={_gotest:{add:(e,t)=>e+t,callExport:u},gojs:{"runtime.wasmExit":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;let n=t(e+8),i=t(e+16),a=this.mem.getInt32(e+24,!0);r.fs.writeSync(n,new Uint8Array(this._inst.exports.mem.buffer,i,a))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":t=>{t>>>=0,e(t+8,(d+performance.now())*1e6)},"runtime.walltime":t=>{t>>>=0;let n=new Date().getTime();e(t+8,n/1e3),this.mem.setInt32(t+16,n%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;let n=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(n,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(n);)console.warn(`scheduleTimeoutEvent: missed timeout event`),this._resume()},t(e+8))),this.mem.setInt32(e+16,n,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(s(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;let t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){let e=this._values[t];this._values[t]=null,this._ids.delete(e),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,o(e+24,l(e+8))},"syscall/js.valueGet":e=>{e>>>=0;let t=Reflect.get(a(e+8),l(e+16));e=this._inst.exports.getsp()>>>0,o(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(a(e+8),l(e+16),a(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(a(e+8),l(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,o(e+24,Reflect.get(a(e+8),t(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(a(e+8),t(e+16),a(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{let t=a(e+8),n=Reflect.get(t,l(e+16)),r=c(e+32),i=Reflect.apply(n,t,r);e=this._inst.exports.getsp()>>>0,o(e+56,i),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.apply(t,void 0,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{let t=a(e+8),n=c(e+16),r=Reflect.construct(t,n);e=this._inst.exports.getsp()>>>0,o(e+40,r),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":t=>{t>>>=0,e(t+16,parseInt(a(t+8).length))},"syscall/js.valuePrepareString":t=>{t>>>=0;let r=n.encode(String(a(t+8)));o(t+16,r),e(t+24,r.length)},"syscall/js.valueLoadString":e=>{e>>>=0;let t=a(e+8);s(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,+(a(e+8)instanceof a(e+16)))},"syscall/js.copyBytesToGo":t=>{t>>>=0;let n=s(t+8),r=a(t+32);if(!(r instanceof Uint8Array||r instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},"syscall/js.copyBytesToJS":t=>{t>>>=0;let n=a(t+8),r=s(t+16);if(!(n instanceof Uint8Array||n instanceof Uint8ClampedArray)){this.mem.setUint8(t+48,0);return}let i=r.subarray(0,n.length);n.set(i),e(t+40,i.length),this.mem.setUint8(t+48,1)},debug:e=>{console.log(e)}}}}run(e){return t(this,null,function*(){if(!(e instanceof WebAssembly.Instance))throw Error(`Go.run: WebAssembly.Instance expected`);this._inst=e,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,r,this],this._goRefCounts=Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[r,5],[this,6]]),this._idPool=[],this.exited=!1;let t=4096,i=e=>{let r=t,i=n.encode(e+`\0`);return new Uint8Array(this.mem.buffer,t,i.length).set(i),t+=i.length,t%8!=0&&(t+=8-t%8),r},a=this.argv.length,o=[];this.argv.forEach(e=>{o.push(i(e))}),o.push(0),Object.keys(this.env).sort().forEach(e=>{o.push(i(`${e}=${this.env[e]}`))}),o.push(0);let s=t;if(o.forEach(e=>{this.mem.setUint32(t,e,!0),this.mem.setUint32(t+4,0,!0),t+=8}),t>=12288)throw Error(`total length of command line and environment variables exceeds limit`);this._inst.exports.run(a,s),this.exited&&this._resolveExitPromise(),yield this._exitPromise})}_resume(){if(this.exited)throw Error(`Go program has already exited`);this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(e){let t=this;return function(){let n={id:e,this:this,args:arguments};return t._pendingEvent=n,t._resume(),n.result}}}})(),n=({data:t})=>{let a=new TextDecoder,o=r.fs,s=``;o.writeSync=(t,n)=>{if(t===1)e(n);else if(t===2){s+=a.decode(n);let e=s.split(`
|
|
5552
5552
|
`);e.length>1&&console.log(e.slice(0,-1).join(`
|
|
5553
|
-
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=me({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Fe=()=>{r.terminate(),Pe=void 0,Fe=void 0,Ie=void 0},Ie={build:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`build`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),context:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`context`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),transform:(e,t)=>new Promise((n,r)=>{a.then(r),d.transform({callName:`transform`,refs:null,input:e,options:t||{},isTTY:!1,fs:{readFile(e,t){t(Error(`Internal error`),null)},writeFile(e,t){t(null)}},callback:(e,t)=>e?r(e):n(t)})}),formatMessages:(e,t)=>new Promise((n,r)=>{a.then(r),d.formatMessages({callName:`formatMessages`,refs:null,messages:e,options:t,callback:(e,t)=>e?r(e):n(t)})}),analyzeMetafile:(e,t)=>new Promise((n,r)=>{a.then(r),d.analyzeMetafile({callName:`analyzeMetafile`,refs:null,metafile:typeof e==`string`?e:JSON.stringify(e),options:t,callback:(e,t)=>e?r(e):n(t)})})}}),Be=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);const
|
|
5554
|
-
`);return t===-1?``:e.slice(t+1)}function DE(e){return nt(e).dir}const OE=[`node`,`require`,`default`],kE=[`node`,`import`,`default`],AE=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,jE=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,ME=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,NE=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,PE=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function FE(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function IE(e){let t=Sn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!FE(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(AE,`require`,`require`),r(jE,`import`,`import`),r(ME,`import`,`import`),r(NE,`import`,`export`),r(PE,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function LE(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=EE(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 RE(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??OE,s=e.importConditions??kE,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 LE(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=DE(e),p={};for(let{specifier:t,kind:i}of IE(n)){let n;try{n=await tn(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 tn(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 zE(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||$t.has(e)||Vw.has(e))}async function BE(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 IE(t))if(zE(e))try{let t=await RE({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?kE:OE,requireConditions:OE,importConditions:kE});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&&(an(t)||Cn(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 VE(){return globalThis.navigator?.hid??null}function HE(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function UE(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&HE(e)===HE(t)&&!!e.productName}var WE=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(UE(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 GE=null;function KE(){return GE||=new WE,GE}const qE=4*1024*1024;function JE(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 YE(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function XE(e){e.opened||await e.open()}function ZE(e,t){if(e>4194304)throw Error(`${t} exceeds the ${qE}-byte (4 MiB) v1 limit`)}function QE(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function $E(e,t){return(await t.getDevices()).map(t=>JE(e.register(t),t))}async function eD(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>JE(e.register(t),t))}function tD(e,t){return JE(t,YE(e,t))}async function nD(e,t){await YE(e,t).open()}async function rD(e,t){await YE(e,t).close()}async function iD(e,t,n,r){ZE(r.byteLength,`send report payload`);let i=YE(e,t);await XE(i),await i.sendReport(n,r)}async function aD(e,t,n,r){ZE(r.byteLength,`send feature report payload`);let i=YE(e,t);await XE(i),await i.sendFeatureReport(n,r)}async function oD(e,t,n){let r=YE(e,t);return await XE(r),{reportId:n,bytes:QE(await r.receiveFeatureReport(n))}}async function sD(e,t,n){let r=YE(e,t);await XE(r);let i=e=>{n({reportId:e.reportId,bytes:QE(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const cD=6e4;function lD(){return se()}function uD(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),cD);oe(`hid-device`,e??[],void 0,{timeoutMs:cD}).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 dD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var fD=class{registry;constructor(e){this.registry=e}hid(){let e=VE();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return $E(this.registry,this.hid())}async request(e){if(lD()){let t=await uD(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=>JE(this.registry.register(e),e))}return eD(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(tD(this.registry,e))}open(e){return nD(this.registry,e)}close(e){return rD(this.registry,e)}sendReport(e,t,n){return iD(this.registry,e,t,dD(n))}sendFeatureReport(e,t,n){return aD(this.registry,e,t,dD(n))}async receiveFeatureReport(e,t){let n=await oD(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return sD(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},pD=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:dD(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:dD(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 mD(e,t){return e&&VE()?new fD(KE()):t?new pD(t):null}function hD(e){return async function(t,n){let r=t instanceof Request?t:null,i=gD(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=vD(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=bD(n.body,a),c=n.body;else if(r&&a!==`GET`&&a!==`HEAD`){let e=await r.arrayBuffer();s=e.byteLength===0?void 0:new TextDecoder(`utf-8`).decode(new Uint8Array(e)),c=void 0}else s=void 0,c=void 0;c instanceof URLSearchParams&&o&&!yD(o,`content-type`)&&(o[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`);let l=await e(i,{method:a,headers:o,body:s}),u=new Headers;for(let[e,t]of Object.entries(l.headers))try{u.set(e,t)}catch{}let d=l.status===204||l.status===205||l.status===304||!l.body||l.body.byteLength===0?null:l.body,f=new Response(d,{status:l.status,statusText:l.statusText,headers:u});try{Object.defineProperty(f,"url",{value:l.url||i,writable:!1,configurable:!0,enumerable:!1})}catch{}return f}}function gD(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function _D(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 vD(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=_D(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function yD(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function bD(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 new TextDecoder(`utf-8`).decode(e);if(e instanceof ArrayBuffer)return new TextDecoder(`utf-8`).decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder(`utf-8`).decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}throw typeof Blob<`u`&&e instanceof Blob?Error(`node fetch shim: Blob request bodies are not supported (use a string, Uint8Array, or URLSearchParams)`):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, or URLSearchParams`)}}function xD(){return globalThis.navigator?.serial??null}var SD=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 CD=null;function wD(){return CD||=new SD,CD}const TD=4*1024*1024;function ED(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 DD(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function OD(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function kD(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 AD(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return ED(n,e.get(n))})}async function jD(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return ED(i,e.get(i))}function MD(e,t){return ED(t,DD(e,t))}async function ND(e,t,n){let r=DD(e,t);await r.port.open(n),r.opened=!0}async function PD(e,t){let n=DD(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 FD(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 ID(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 LD(e,t,n){let r=DD(e,t),i=Math.min(n.maxBytes??4194304,TD),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=kD(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=FD(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=OD(c,a.value);let e=u();if(e)return e}}return c}async function RD(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${TD}-byte (4 MiB) v1 limit`);return await ID(DD(e,t)).write(n),n.length}async function zD(e,t){return DD(e,t).port.getSignals()}async function BD(e,t,n){await DD(e,t).port.setSignals(n)}const VD=6e4;function HD(){return se()}function UD(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),VD);oe(`serial-port`,e??[],void 0,{timeoutMs:VD}).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 WD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var GD=class{registry;constructor(e){this.registry=e}serial(){let e=xD();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return AD(this.registry,this.serial())}async request(e){if(HD()){let t=await UD(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 ED(r,this.registry.get(r))}return jD(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(MD(this.registry,e))}open(e,t){return ND(this.registry,e,t)}close(e){return PD(this.registry,e)}read(e,t){return LD(this.registry,e,t)}write(e,t){return RD(this.registry,e,t)}getSignals(e){return zD(this.registry,e)}setSignals(e,t){return BD(this.registry,e,t)}},KD=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?WD(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:WD(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 qD(e,t){return e&&xD()?new GD(wD()):t?new KD(t):null}function JD(){return globalThis.navigator?.usb??null}function YD(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var XD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(YD(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 ZD=null;function QD(){return ZD||=new XD,ZD}const $D=4*1024*1024;function eO(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 tO(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function nO(e,t){if(e>4194304)throw Error(`${t} exceeds the ${$D}-byte (4 MiB) v1 limit`)}function rO(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function iO(e,t){return(await t.getDevices()).map(t=>eO(e.register(t),t))}async function aO(e,t,n){let r=await t.requestDevice({filters:n});return eO(e.register(r),r)}function oO(e,t){return eO(t,tO(e,t))}async function sO(e,t){await tO(e,t).open()}async function cO(e,t){await tO(e,t).close()}async function lO(e,t,n){await tO(e,t).selectConfiguration(n)}async function uO(e,t,n){await tO(e,t).claimInterface(n)}async function dO(e,t,n){await tO(e,t).releaseInterface(n)}async function fO(e,t,n,r){nO(r,`control-in length`);let i=await tO(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?rO(i.data):new ArrayBuffer(0)}}async function pO(e,t,n,r){nO(r.byteLength,`control-out payload`);let i=await tO(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function mO(e,t,n,r){nO(r,`transfer-in length`);let i=await tO(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?rO(i.data):new ArrayBuffer(0)}}async function hO(e,t,n,r){nO(r.byteLength,`transfer-out payload`);let i=await tO(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function gO(e,t){await tO(e,t).reset()}const _O=6e4;function vO(){return se()}function yO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),_O);oe(`usb-device`,e??[],void 0,{timeoutMs:_O}).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 bO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var xO=class{registry;constructor(e){this.registry=e}usb(){let e=JD();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return iO(this.registry,this.usb())}async request(e){if(vO()){let t=await yO(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 eO(this.registry.register(n),n)}return aO(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(oO(this.registry,e))}open(e){return sO(this.registry,e)}close(e){return cO(this.registry,e)}selectConfig(e,t){return lO(this.registry,e,t)}claim(e,t){return uO(this.registry,e,t)}release(e,t){return dO(this.registry,e,t)}async controlIn(e,t,n){let r=await fO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return pO(this.registry,e,t,bO(n))}async transferIn(e,t,n){let r=await mO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return hO(this.registry,e,t,bO(n))}reset(e){return gO(this.registry,e)}},SO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:bO(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:bO(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function CO(e,t){return e&&JD()?new xO(QD()):t?new SO(t):null}const wO=n(`realm-host`);function TO(e,t,n={}){let r=new Map,i=!1,a={subscriptions:r,pushEvent:(t,n=[])=>{if(!i)try{e.postMessage(t,n)}catch{}}},o=new Map,s={spawns:o,opts:n},c=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;EO(e,i,t,n,a,s)};return e.addEventListener(`message`,c),e.start?.(),{dispose:()=>{if(!i){i=!0,e.removeEventListener(`message`,c);for(let{controller:e}of o.values())try{e.signal.aborted||e.abort()}catch{}o.clear();for(let e of r.values())try{Promise.resolve(e()).catch(()=>{})}catch{}r.clear()}}}}async function EO(e,t,n,r,i,a){try{let o=await DO(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=pk(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 DO(e,t,n,r,i){switch(e.channel){case`vfs`:return NO(e.op,e.args,t);case`exec`:return UO(e.op,e.args,t,i);case`fetch`:return qO(e.op,e.args,t);case`browser`:return ZO(e.op,e.args,OO(n),n);case`usb`:return uk(e.op,e.args,AO(n));case`serial`:return dk(e.op,e.args,jO(n));case`hid`:return fk(e.op,e.args,MO(n),r);case`module`:return YO(e.op,e.args,t);case`wasm`:return XO(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function OO(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 kO(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 AO(e){if(e.usbBackend)return e.usbBackend;let t=CO(Ue(),He());if(!t)throw Error(`usb is not available in this runtime`);return t}function jO(e){if(e.serialBackend)return e.serialBackend;let t=qD(Ue(),He());if(!t)throw Error(`serial is not available in this runtime`);return t}function MO(e){if(e.hidBackend)return e.hidBackend;let t=mD(Ue(),He());if(!t)throw Error(`hid is not available in this runtime`);return t}async function NO(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 zO(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await BO(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const PO=10485760;function FO(e){return e.fileCount>=500||e.totalBytes>=PO}async function IO(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 LO(e,t,n,r){if(n>1048576){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0});return}if(r.totalBytes+n>PO){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function RO(e,t,n){if(FO(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(FO(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await IO(e,t,r,n):i.isFile&&await LO(e,t,i.size,n)}}async function zO(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await RO(e,t,n),t!==`/tmp`&&await RO(e,`/tmp`,n),{entries:n.entries}}async function BO(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const VO=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),HO=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function UO(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 GO(t,n,r);if(e===`kill`)return KO(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function WO(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 GO(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??{};WO(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 KO(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&VO.has(r)?r:`SIGTERM`;HO.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 qO(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?hD(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 JO(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 YO(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=JO(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return BE({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:wE({ipk:s}),transpileEntry:TE({ipk:s})})}async function XO(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);return Tn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function ZO(e,t,n,r){switch(e){case`findTab`:return ek(n,t[0]??{});case`ensureTab`:{let e=t[0];return tk(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return nk(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return nk(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return ok(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return sk(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await kO(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return kO(r).update(e,n)}case`wsClose`:{let e=t[0];return kO(r).close(e)}case`wsList`:return kO(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 ak(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function QO(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function $O(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=QO()?He():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){wO.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function ek(e,t){let n=await $O(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=ck(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 tk(e,t,n){let r=await $O(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=lk(t);if(e){let t=r.find(t=>lk(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function nk(e,t,n,r){return e.withTab(t,async()=>rk(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function rk(e){if(typeof e!=`string`)return e;let t=ik(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=ik(t);if(typeof e==`object`&&e)return e}return t}return e}function ik(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 ak(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(){
|
|
5553
|
+
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=me({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Fe=()=>{r.terminate(),Pe=void 0,Fe=void 0,Ie=void 0},Ie={build:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`build`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),context:e=>new Promise((t,n)=>{a.then(n),d.buildOrContext({callName:`context`,refs:null,options:e,isTTY:!1,defaultWD:`/`,callback:(e,r)=>e?n(e):t(r)})}),transform:(e,t)=>new Promise((n,r)=>{a.then(r),d.transform({callName:`transform`,refs:null,input:e,options:t||{},isTTY:!1,fs:{readFile(e,t){t(Error(`Internal error`),null)},writeFile(e,t){t(null)}},callback:(e,t)=>e?r(e):n(t)})}),formatMessages:(e,t)=>new Promise((n,r)=>{a.then(r),d.formatMessages({callName:`formatMessages`,refs:null,messages:e,options:t,callback:(e,t)=>e?r(e):n(t)})}),analyzeMetafile:(e,t)=>new Promise((n,r)=>{a.then(r),d.analyzeMetafile({callName:`analyzeMetafile`,refs:null,metafile:typeof e==`string`?e:JSON.stringify(e),options:t,callback:(e,t)=>e?r(e):n(t)})})}}),Be=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);const bE=yE.version;let xE=null;async function SE(e={}){return xE||=wE(e.onProgress,e.ipk).catch(e=>{throw xE=null,e}),xE}async function CE(e){let t;try{t=await tn(`esbuild-wasm/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=`${nt(t.path).dir}/esbuild.wasm`;if(!await e.reader.exists(n))return null;try{return await e.readBytes(n)}catch{return null}}async function wE(e,t){let n=e??(()=>{});if(cn())return n(`esbuild ready (node service)`),yE;if(!t)throw Error("esbuild-wasm is not available: install via `ipk add esbuild-wasm` or invoke through `ipx esbuild`");let r=await CE(t);if(!r)throw Error("esbuild-wasm is not installed in node_modules: run `ipk add esbuild-wasm` or invoke through `ipx esbuild`");n(`esbuild.wasm loaded from ipk node_modules (${r.byteLength} bytes)`);let i=await wn(r);return await yE.initialize({wasmModule:i,worker:!bn()}),n(`esbuild ready`),yE}function TE(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function EE(e){return e instanceof Error?e.message:String(e)}function DE(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function OE(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:DE(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function kE(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:DE(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const AE=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,jE=/\bimport\s*\.\s*meta\b/g;function ME(e,t){let n=JSON.stringify(t);return e.replace(AE,n).replace(jE,`({ url: ${n} })`)}async function NE(e,t,n,r){let i=await e();return i.transpileModule(ME(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function PE(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>SE(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>fn(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!an(e))return e;let a=TE(t),o;try{return await OE(n,e,t,a)}catch(e){o=e}try{return await NE(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${EE(o)}; typescript fallback: ${EE(e)}`)}}}function FE(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>SE(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>fn(t));return async({source:e,filename:t})=>{if(!an(e)&&!Cn(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?TE(t):void 0,o=i?t:`[eval].js`,s;try{return await kE(n,e,t,a)}catch(e){s=e}try{return await NE(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${EE(s)}; typescript fallback: ${EE(e)}`)}}}function IE(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
5554
|
+
`);return t===-1?``:e.slice(t+1)}function LE(e){return nt(e).dir}const RE=[`node`,`require`,`default`],zE=[`node`,`import`,`default`],BE=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,VE=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,HE=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,UE=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,WE=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function GE(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function KE(e){let t=Sn(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!GE(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(BE,`require`,`require`),r(VE,`import`,`import`),r(HE,`import`,`import`),r(UE,`import`,`export`),r(WE,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function qE(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=IE(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 JE(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??RE,s=e.importConditions??zE,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 qE(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=LE(e),p={};for(let{specifier:t,kind:i}of KE(n)){let n;try{n=await tn(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 tn(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 YE(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||$t.has(e)||Vw.has(e))}async function XE(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 KE(t))if(YE(e))try{let t=await JE({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?zE:RE,requireConditions:RE,importConditions:zE});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&&(an(t)||Cn(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 ZE(){return globalThis.navigator?.hid??null}function QE(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function $E(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&QE(e)===QE(t)&&!!e.productName}var eD=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if($E(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 tD=null;function nD(){return tD||=new eD,tD}const rD=4*1024*1024;function iD(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 aD(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function oD(e){e.opened||await e.open()}function sD(e,t){if(e>4194304)throw Error(`${t} exceeds the ${rD}-byte (4 MiB) v1 limit`)}function cD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function lD(e,t){return(await t.getDevices()).map(t=>iD(e.register(t),t))}async function uD(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>iD(e.register(t),t))}function dD(e,t){return iD(t,aD(e,t))}async function fD(e,t){await aD(e,t).open()}async function pD(e,t){await aD(e,t).close()}async function mD(e,t,n,r){sD(r.byteLength,`send report payload`);let i=aD(e,t);await oD(i),await i.sendReport(n,r)}async function hD(e,t,n,r){sD(r.byteLength,`send feature report payload`);let i=aD(e,t);await oD(i),await i.sendFeatureReport(n,r)}async function gD(e,t,n){let r=aD(e,t);return await oD(r),{reportId:n,bytes:cD(await r.receiveFeatureReport(n))}}async function _D(e,t,n){let r=aD(e,t);await oD(r);let i=e=>{n({reportId:e.reportId,bytes:cD(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const vD=6e4;function yD(){return se()}function bD(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),vD);oe(`hid-device`,e??[],void 0,{timeoutMs:vD}).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 xD(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var SD=class{registry;constructor(e){this.registry=e}hid(){let e=ZE();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return lD(this.registry,this.hid())}async request(e){if(yD()){let t=await bD(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=>iD(this.registry.register(e),e))}return uD(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(dD(this.registry,e))}open(e){return fD(this.registry,e)}close(e){return pD(this.registry,e)}sendReport(e,t,n){return mD(this.registry,e,t,xD(n))}sendFeatureReport(e,t,n){return hD(this.registry,e,t,xD(n))}async receiveFeatureReport(e,t){let n=await gD(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return _D(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},CD=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`hid-list`,void 0)).devices}async request(t){return(await this.rpc.call(`hid-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).devices}async info(e){return(await this.rpc.call(`hid-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`hid-open`,{handle:e})}async close(e){await this.rpc.call(`hid-close`,{handle:e})}async sendReport(e,t,n){await this.rpc.call(`hid-send-report`,{handle:e,reportId:t,bytes:xD(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:xD(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 wD(e,t){return e&&ZE()?new SD(nD()):t?new CD(t):null}function TD(e){return async function(t,n){let r=t instanceof Request?t:null,i=ED(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=OD(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=AD(n.body,a),c=n.body;else if(r&&a!==`GET`&&a!==`HEAD`){let e=await r.arrayBuffer();s=e.byteLength===0?void 0:new TextDecoder(`utf-8`).decode(new Uint8Array(e)),c=void 0}else s=void 0,c=void 0;c instanceof URLSearchParams&&o&&!kD(o,`content-type`)&&(o[`Content-Type`]=`application/x-www-form-urlencoded;charset=UTF-8`);let l=await e(i,{method:a,headers:o,body:s}),u=new Headers;for(let[e,t]of Object.entries(l.headers))try{u.set(e,t)}catch{}let d=l.status===204||l.status===205||l.status===304||!l.body||l.body.byteLength===0?null:l.body,f=new Response(d,{status:l.status,statusText:l.statusText,headers:u});try{Object.defineProperty(f,"url",{value:l.url||i,writable:!1,configurable:!0,enumerable:!1})}catch{}return f}}function ED(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function DD(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 OD(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=DD(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function kD(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function AD(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 new TextDecoder(`utf-8`).decode(e);if(e instanceof ArrayBuffer)return new TextDecoder(`utf-8`).decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder(`utf-8`).decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}throw typeof Blob<`u`&&e instanceof Blob?Error(`node fetch shim: Blob request bodies are not supported (use a string, Uint8Array, or URLSearchParams)`):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, or URLSearchParams`)}}function jD(){return globalThis.navigator?.serial??null}var MD=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 ND=null;function PD(){return ND||=new MD,ND}const FD=4*1024*1024;function ID(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 LD(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function RD(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function zD(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 BD(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return ID(n,e.get(n))})}async function VD(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return ID(i,e.get(i))}function HD(e,t){return ID(t,LD(e,t))}async function UD(e,t,n){let r=LD(e,t);await r.port.open(n),r.opened=!0}async function WD(e,t){let n=LD(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 GD(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 KD(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 qD(e,t,n){let r=LD(e,t),i=Math.min(n.maxBytes??4194304,FD),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=zD(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=GD(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=RD(c,a.value);let e=u();if(e)return e}}return c}async function JD(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${FD}-byte (4 MiB) v1 limit`);return await KD(LD(e,t)).write(n),n.length}async function YD(e,t){return LD(e,t).port.getSignals()}async function XD(e,t,n){await LD(e,t).port.setSignals(n)}const ZD=6e4;function QD(){return se()}function $D(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),ZD);oe(`serial-port`,e??[],void 0,{timeoutMs:ZD}).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 eO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var tO=class{registry;constructor(e){this.registry=e}serial(){let e=jD();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return BD(this.registry,this.serial())}async request(e){if(QD()){let t=await $D(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 ID(r,this.registry.get(r))}return VD(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(HD(this.registry,e))}open(e,t){return UD(this.registry,e,t)}close(e){return WD(this.registry,e)}read(e,t){return qD(this.registry,e,t)}write(e,t){return JD(this.registry,e,t)}getSignals(e){return YD(this.registry,e)}setSignals(e,t){return XD(this.registry,e,t)}},nO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;static READ_MARGIN_MS=3e4;async list(){return(await this.rpc.call(`serial-list`,void 0)).devices}async request(t){return(await this.rpc.call(`serial-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`serial-device-info`,{handle:e})).device}async open(e,t){await this.rpc.call(`serial-open`,{handle:e,options:t})}async close(e){await this.rpc.call(`serial-close`,{handle:e})}async read(t,n){let r=(n.timeoutMs??1e3)+e.READ_MARGIN_MS,i=await this.rpc.call(`serial-read`,{handle:t,maxBytes:n.maxBytes,until:n.until?eO(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:eO(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 rO(e,t){return e&&jD()?new tO(PD()):t?new nO(t):null}function iO(){return globalThis.navigator?.usb??null}function aO(e,t){return e===t||e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var oO=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(aO(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 sO=null;function cO(){return sO||=new oO,sO}const lO=4*1024*1024;function uO(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 dO(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function fO(e,t){if(e>4194304)throw Error(`${t} exceeds the ${lO}-byte (4 MiB) v1 limit`)}function pO(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function mO(e,t){return(await t.getDevices()).map(t=>uO(e.register(t),t))}async function hO(e,t,n){let r=await t.requestDevice({filters:n});return uO(e.register(r),r)}function gO(e,t){return uO(t,dO(e,t))}async function _O(e,t){await dO(e,t).open()}async function vO(e,t){await dO(e,t).close()}async function yO(e,t,n){await dO(e,t).selectConfiguration(n)}async function bO(e,t,n){await dO(e,t).claimInterface(n)}async function xO(e,t,n){await dO(e,t).releaseInterface(n)}async function SO(e,t,n,r){fO(r,`control-in length`);let i=await dO(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?pO(i.data):new ArrayBuffer(0)}}async function CO(e,t,n,r){fO(r.byteLength,`control-out payload`);let i=await dO(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function wO(e,t,n,r){fO(r,`transfer-in length`);let i=await dO(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?pO(i.data):new ArrayBuffer(0)}}async function TO(e,t,n,r){fO(r.byteLength,`transfer-out payload`);let i=await dO(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function EO(e,t){await dO(e,t).reset()}const DO=6e4;function OO(){return se()}function kO(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),DO);oe(`usb-device`,e??[],void 0,{timeoutMs:DO}).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 AO(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var jO=class{registry;constructor(e){this.registry=e}usb(){let e=iO();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return mO(this.registry,this.usb())}async request(e){if(OO()){let t=await kO(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 uO(this.registry.register(n),n)}return hO(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(gO(this.registry,e))}open(e){return _O(this.registry,e)}close(e){return vO(this.registry,e)}selectConfig(e,t){return yO(this.registry,e,t)}claim(e,t){return bO(this.registry,e,t)}release(e,t){return xO(this.registry,e,t)}async controlIn(e,t,n){let r=await SO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return CO(this.registry,e,t,AO(n))}async transferIn(e,t,n){let r=await wO(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return TO(this.registry,e,t,AO(n))}reset(e){return EO(this.registry,e)}},MO=class e{rpc;constructor(e){this.rpc=e}static REQUEST_TIMEOUT_MS=5*6e4;async list(){return(await this.rpc.call(`usb-list`,void 0)).devices}async request(t){return(await this.rpc.call(`usb-request`,{filters:t},{timeoutMs:e.REQUEST_TIMEOUT_MS})).device}async info(e){return(await this.rpc.call(`usb-device-info`,{handle:e})).device}async open(e){await this.rpc.call(`usb-open`,{handle:e})}async close(e){await this.rpc.call(`usb-close`,{handle:e})}async selectConfig(e,t){await this.rpc.call(`usb-select-configuration`,{handle:e,configurationValue:t})}async claim(e,t){await this.rpc.call(`usb-claim-interface`,{handle:e,interfaceNumber:t})}async release(e,t){await this.rpc.call(`usb-release-interface`,{handle:e,interfaceNumber:t})}async controlIn(e,t,n){let r=await this.rpc.call(`usb-control-transfer-in`,{handle:e,setup:t,length:n});return{status:r.status,bytes:new Uint8Array(r.bytes)}}async controlOut(e,t,n){return this.rpc.call(`usb-control-transfer-out`,{handle:e,setup:t,bytes:AO(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:AO(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function NO(e,t){return e&&iO()?new jO(cO()):t?new MO(t):null}const PO=new Map;function FO(e){let t=crypto.randomUUID();return PO.set(t,e),t}function IO(e){return PO.get(e)??null}function LO(e){PO.delete(e)}const RO=n(`realm-host`);function zO(e,t,n={}){let r=new Map,i=n.syncFsBridgeEnabled?FO({fs:t.fs,cwd:t.cwd}):void 0,a=!1,o={subscriptions:r,pushEvent:(t,n=[])=>{if(!a)try{e.postMessage(t,n)}catch{}}},s=new Map,c={spawns:s,opts:n},l=r=>{if(r.data?.type!==`realm-rpc-req`)return;let i=r.data;BO(e,i,t,n,o,c)};return e.addEventListener(`message`,l),e.start?.(),{syncFsToken:i,dispose:()=>{if(!a){a=!0,i&&LO(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 BO(e,t,n,r,i,a){try{let o=await VO(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=Ok(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 VO(e,t,n,r,i){switch(e.channel){case`vfs`:return qO(e.op,e.args,t);case`exec`:return ik(e.op,e.args,t,i);case`fetch`:return ck(e.op,e.args,t);case`browser`:return fk(e.op,e.args,HO(n),n);case`usb`:return Tk(e.op,e.args,WO(n));case`serial`:return Ek(e.op,e.args,GO(n));case`hid`:return Dk(e.op,e.args,KO(n),r);case`module`:return uk(e.op,e.args,t);case`wasm`:return dk(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function HO(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 UO(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 WO(e){if(e.usbBackend)return e.usbBackend;let t=NO(Ue(),He());if(!t)throw Error(`usb is not available in this runtime`);return t}function GO(e){if(e.serialBackend)return e.serialBackend;let t=rO(Ue(),He());if(!t)throw Error(`serial is not available in this runtime`);return t}function KO(e){if(e.hidBackend)return e.hidBackend;let t=wD(Ue(),He());if(!t)throw Error(`hid is not available in this runtime`);return t}async function qO(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 ek(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await tk(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const JO=10485760;function YO(e){return e.fileCount>=500||e.totalBytes>=JO}function XO(e){return e.entries.length>=2e4}async function ZO(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 QO(e,t,n,r){if(n>1048576||YO(r)||r.totalBytes+n>JO){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0,size:n});return}let i=await e.fs.readFileBuffer(t);r.entries.push({path:t,content:i,isDirectory:!1}),r.fileCount+=1,r.totalBytes+=i.byteLength}async function $O(e,t,n){if(XO(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(XO(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await ZO(e,t,r,n):i.isFile&&await QO(e,t,i.size,n)}}async function ek(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await $O(e,t,n),t!==`/tmp`&&await $O(e,`/tmp`,n),{entries:n.entries}}async function tk(e,t){for(let n of t.deleted)await e.fs.rm(n,{recursive:!0});for(let n of t.created)n.isDirectory?await e.fs.mkdir(n.path,{recursive:!0}):await e.fs.writeFile(n.path,n.content);for(let n of t.modified)await e.fs.writeFile(n.path,n.content)}const nk=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),rk=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function ik(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 ok(t,n,r);if(e===`kill`)return sk(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function ak(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 ok(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??{};ak(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 sk(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&nk.has(r)?r:`SIGTERM`;rk.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 ck(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?TD(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 lk(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 uk(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=lk(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return XE({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:PE({ipk:s}),transpileEntry:FE({ipk:s})})}async function dk(e,t,n){if(e!==`compile`)throw Error(`realm-host: unknown wasm op '${e}'`);let r=typeof t[0]==`string`?t[0]:null;if(r===null)throw Error(`realm-host: wasm.compile requires a path argument`);return Tn(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function fk(e,t,n,r){switch(e){case`findTab`:return hk(n,t[0]??{});case`ensureTab`:{let e=t[0];return gk(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return _k(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return _k(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return xk(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return Sk(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await UO(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return UO(r).update(e,n)}case`wsClose`:{let e=t[0];return UO(r).close(e)}case`wsList`:return UO(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 bk(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function pk(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function mk(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=pk()?He():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){RO.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function hk(e,t){let n=await mk(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=Ck(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 gk(e,t,n){let r=await mk(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=wk(t);if(e){let t=r.find(t=>wk(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function _k(e,t,n,r){return e.withTab(t,async()=>vk(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function vk(e){if(typeof e!=`string`)return e;let t=yk(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=yk(t);if(typeof e==`object`&&e)return e}return t}return e}function yk(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 bk(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(){
|
|
5555
5555
|
try {
|
|
5556
5556
|
var entries = performance.getEntriesByType('resource');
|
|
5557
5557
|
var now = performance.now();
|
|
@@ -5564,14 +5564,14 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
5564
5564
|
} catch (e) {
|
|
5565
5565
|
return true;
|
|
5566
5566
|
}
|
|
5567
|
-
})()`,{returnByValue:!0}))return})}async function
|
|
5567
|
+
})()`,{returnByValue:!0}))return})}async function xk(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 Sk(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 Ck(e){try{return new URL(e).hostname}catch{return null}}function wk(e){try{return new URL(e).origin}catch{return null}}async function Tk(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 Ek(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 Dk(e,t,n,r){switch(e){case`list`:return n.list();case`request`:return n.request(t[0]??[]);case`info`:return n.info(t[0]);case`open`:return n.open(t[0]);case`close`:return n.close(t[0]);case`sendReport`:return n.sendReport(t[0],t[1],t[2]);case`sendFeatureReport`:return n.sendFeatureReport(t[0],t[1],t[2]);case`receiveFeatureReport`:return n.receiveFeatureReport(t[0],t[1]);case`subscribeInputReports`:{let e=t[0];if(r.subscriptions.has(e))return!0;let i=await n.subscribeInputReports(e,t=>{let n=t.bytes instanceof Uint8Array?t.bytes:new Uint8Array(t.bytes),i={type:`realm-event`,channel:`hid-input-report`,payload:{handle:e,reportId:t.reportId,bytes:n}};r.pushEvent(i,[n.buffer])});return r.subscriptions.set(e,i),!0}case`unsubscribeInputReports`:{let e=t[0],n=r.subscriptions.get(e);return n?(r.subscriptions.delete(e),await n(),!0):!0}default:throw Error(`realm-host: unknown hid op '${e}'`)}}function Ok(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 kk(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=zO(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid,syncFsBridgeEnabled:e.syncFsBridgeEnabled});return new Promise(t=>{let a=!1,o=null,s=null,c=null,l=null,u=()=>{s&&r.controlPort.removeEventListener(`message`,s),r.removeEventListener&&(c&&r.removeEventListener(`error`,c),l&&r.removeEventListener(`messageerror`,l)),o?.(),i.dispose()},d=(i,o)=>{if(!a){a=!0,u();try{r.terminate()}catch{}e.pm.exit(n.pid,o),t(i)}};s=e=>{let t=e.data;if(t?.type===`realm-done`){let t=e.data;d({stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode},t.exitCode)}else if(t?.type===`realm-error`){let t=e.data;d({stdout:``,stderr:t.message+`
|
|
5568
5568
|
`,exitCode:1},1)}},c=e=>{let t=e.message??`realm error`;d({stdout:``,stderr:t+`
|
|
5569
5569
|
`,exitCode:1},1)},l=()=>{d({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
5570
|
-
`,exitCode:1},1)},o=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?d({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?d({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&d({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,s),r.addEventListener&&(r.addEventListener(`error`,c),r.addEventListener(`messageerror`,l));let f={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints};r.controlPort.postMessage(f)})}const hk=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function gk(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 hk.decode(n)}function _k(e){return e}async function vk(e,t,n,r,i={}){return await n.fs.exists(e)?yk(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 yk(e,t,n,r,i={}){let a=i.realmFactory??bk(),o=r?.processManager??Ck()??Sk(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await mk({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:Object.fromEntries(n.env.entries()),cwd:n.cwd,filename:c,stdin:_k(n.stdin),ctx:n,ppid:r?.getParentPid?.()})}function bk(){return typeof Worker<`u`||typeof document<`u`?iE():eE()}let xk=null;function Sk(){return xk||=new Qt,xk}function Ck(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function wk(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}async function Tk(e,t){let n=e.trim();if(!n||kt(At(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:`sudo: approval denied`};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const Ek=`https://api.tessl.io`,Dk=`https://browse.sh/api/skills`,Ok=`/workspace/skills`,kk=qt,Ak=`application/vnd.github.v3+json`,jk=`https://www.sliccy.com/skills/`,Mk=`${jk}catalog.json`;function Nk(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Pk(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function Fk(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:Pk(e.installAll)},affinity:{apps:Nk(e.apps),tasks:Nk(e.tasks),role:Nk(e.role),purpose:Nk(e.purpose)},priority:n}})}const Ik={apps:3,tasks:2,role:1,purpose:1};function Lk(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*Ik.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*Ik.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=Ik.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=Ik.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 Rk(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 zk(e){let t=new Set;try{let n=await e.readDir(Ok);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 Vk(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function Hk(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}function Uk(e,t){let n=e instanceof Error?e.message:String(e),r;try{r=new URL(t).host}catch{return n}return!r||n.includes(r)?n:`${n} (host: ${r} — network or CORS error)`}let Wk;function Gk(){return Wk||=ut.create({dbName:kk}),Wk}async function Kk(){try{return(await(await Gk()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{return}}function qk(e,t=Ak){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function Jk(e){let t=await Kk();return{hasToken:!!t,request:async(n,r=Ak)=>{try{return await e(n,{headers:qk(t,r)})}catch(e){throw Error(Uk(e,n))}}}}function Yk(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}async function Xk(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}async function Zk(){try{let e=globalThis.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function Qk(){await Zk(),await Xk()}async function $k(e,t,n,r,i=!1){let a=`${Ok}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}function eA(e){let t=_e(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function tA(e,t,n){let r=eA(e.body),i=r?` GitHub said: ${r}`:``,a=Yk(e.headers,`retry-after`),o=Yk(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}async function nA(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,o;try{o=await n(i,{headers:{"User-Agent":`slicc-upskill`}})}catch(e){return{status:`error`,message:Uk(e,i)}}if(o.status===404)return r===`main`?nA(e,t,n,`master`):{status:`error`,message:`codeload returned HTTP 404`};if(o.status!==200)return{status:`error`,message:`codeload returned HTTP ${o.status}`};let s=a(i);s||=ge(o.body);try{return{status:`ok`,files:Ft(s)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function rA(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function iA(e,t,n,r){let i=0;for(let[a,o]of Object.entries(e)){if(!a.startsWith(t))continue;let e=a.slice(t.length);if(!e||a.endsWith(`/`))continue;let s=`${n}/${e}`,c=s.substring(0,s.lastIndexOf(`/`));c!==n&&await r.mkdir(c,{recursive:!0}),await r.writeFile(s,o),i++}return i}async function aA(e,t,n,r,i,o,s){for(let c of e)if(c.type===`file`&&c.download_url){let e=await s.request(c.download_url,`*/*`);if(e.status!==200)throw Error(tA(e,`${n}/${r}/${c.path}`,s.hasToken));let i=a(c.download_url);await o.writeFile(`${t}/${c.name}`,i??e.body)}else if(c.type===`dir`){let e=`https://api.github.com/repos/${n}/${r}/contents/${c.path}`,a=i?`${e}?ref=${encodeURIComponent(i)}`:e,l=await s.request(a);if(l.status!==200)throw Error(tA(l,`${n}/${r}/${c.path}`,s.hasToken));let u=B(l.body);await o.mkdir(`${t}/${c.name}`,{recursive:!0}),await aA(u,`${t}/${c.name}`,n,r,i,o,s)}}function oA(e){let t=e.match(/github\.com\/([^/?#]+)\/([^/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function sA(e,t,n,r,i,a){if(i){let n=await nA(e,t,i,a);if(n.status===`ok`){let e=rA(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(tA(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=B(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function cA(e,t,n,r,i,a,o=!1,s,c){try{let l=`${Ok}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await nA(e,t,s,c);if(a.status===`ok`){let o=rA(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;if(await i.mkdir(l,{recursive:!0}),await iA(o,s,l,i)>0)return await Zk(),await Xk(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${tA(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=B(f.body);await i.mkdir(l,{recursive:!0});try{await aA(p,l,e,t,c,i,a)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await Qk(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function lA(e){let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+?)(?:\/(.+?))?)?\/?$/);if(t)return{owner:t[1],repo:t[2],branch:t[3],path:t[4]};let n=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./-]+))?$/);return n?{owner:n[1],repo:n[2],branch:n[3]}:null}async function uA(e,t){try{let n=Vk(t);if(!n)return[];let r=await e(`${jk}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?Fk(B(r.body).data):[]}catch{return[]}}async function dA(e){let t;try{t=await e(Mk,{headers:{Accept:`application/json`}})}catch(e){throw Error(Uk(e,Mk))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return Fk(B(t.body).data)}function fA(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 pA(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 $k(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 mA(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 sA(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 cA(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 hA(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 pA(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=fA(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 $k(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 gA(e,t,n,r,i,a,o,s,c,l){let u=await Jk(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 mA(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 cA(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 _A(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 vA(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([dA(t),uA(t,a.company),zk(e)]);o=Hk(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${Mk}: ${e instanceof Error?e.message:String(e)}`])}let c=Lk(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=_A(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await nA(a,o,t);return c.status===`error`?gA(n,i,a,o,d,u,r,s,t,e):hA(n,i,rA(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await Qk(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function yA(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let bA,xA;async function SA(e){if(bA)return bA;if(xA)return xA;xA=(async()=>{let t;try{t=await e(Dk,{headers:{Accept:`application/json`}})}catch(e){throw Error(Uk(e,Dk))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=B(t.body),r=Array.isArray(n)?n:n.skills??[];return bA=r,r})();try{return await xA}catch(e){throw xA=void 0,e}}async function CA(e,t){let n=await SA(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 wA=/^[A-Za-z0-9._-]+$/;function TA(e){return!e||e===`.`||e===`..`?!1:wA.test(e)}function EA(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(`/`)||!TA(r)||!TA(i))return null;let a=yA(r);return TA(a)?{hostname:a,task:i}:null}function DA(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 OA(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(`
|
|
5571
|
-
`)}function
|
|
5572
|
-
`}\n${t}\n\n${e.slice(n[0].length)}`:`${t}\n\n${e}`}async function
|
|
5573
|
-
`}function
|
|
5574
|
-
`;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function
|
|
5570
|
+
`,exitCode:1},1)},o=e.pm.onSignal((e,t)=>{e.pid===n.pid&&(t===`SIGKILL`?d({stdout:``,stderr:``,exitCode:137},137):t===`SIGINT`?d({stdout:``,stderr:``,exitCode:130},130):t===`SIGTERM`&&d({stdout:``,stderr:``,exitCode:143},143))}),r.controlPort.addEventListener(`message`,s),r.addEventListener&&(r.addEventListener(`error`,c),r.addEventListener(`messageerror`,l));let f={type:`realm-init`,kind:e.kind,code:e.code,argv:e.realmArgv??e.argv,env:e.env,cwd:e.cwd,filename:e.filename,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,opfsMountDbName:e.opfsMountDbName,mountPoints:e.mountPoints,...i.syncFsToken===void 0?{}:{syncFsToken:i.syncFsToken}};r.controlPort.postMessage(f)})}let Ak=!1;function jk(e){Ak=e}function Mk(){return Ak}const Nk=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function Pk(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 Nk.decode(n)}function Fk(e){return e}async function Ik(e,t,n,r,i={}){return await n.fs.exists(e)?Lk(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 Lk(e,t,n,r,i={}){let a=i.realmFactory??Rk(),o=r?.processManager??Vk()??Bk(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await kk({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:Object.fromEntries(n.env.entries()),cwd:n.cwd,filename:c,stdin:Fk(n.stdin),ctx:n,ppid:r?.getParentPid?.(),syncFsBridgeEnabled:Mk()})}function Rk(){return typeof Worker<`u`||typeof document<`u`?mE():uE()}let zk=null;function Bk(){return zk||=new Qt,zk}function Vk(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function Hk(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`){for(r++;r<e.length&&e[r]!==`"`;)n+=e[r],r++;r++}else if(i===`'`){for(r++;r<e.length&&e[r]!==`'`;)n+=e[r],r++;r++}else i===`\\`&&r+1<e.length&&e[r+1]===` `?(n+=` `,r+=2):/\s/.test(i)?(n.length>0&&(t.push(n),n=``),r++):(n+=i,r++)}return n.length>0&&t.push(n),t}async function Uk(e,t){let n=e.trim();if(!n||kt(At(t.policy,n),t.defaultDisposition??`allow`)!==`require-approval`)return{allowed:!0};let r=await t.broker.requestApproval({kind:`command`,detail:n});if(r.decision===`deny`)return{allowed:!1,message:`sudo: approval denied`};if(r.decision===`always`){let e=r.pattern?.trim()||n;await t.persistGrant(e)}return{allowed:!0}}const Wk=`https://api.tessl.io`,Gk=`https://browse.sh/api/skills`,Kk=`/workspace/skills`,qk=qt,Jk=`application/vnd.github.v3+json`,Yk=`https://www.sliccy.com/skills/`,Xk=`${Yk}catalog.json`;function Zk(e){if(e?.trim())return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function Qk(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`true`||t===`1`||t===`yes`}function $k(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:Qk(e.installAll)},affinity:{apps:Zk(e.apps),tasks:Zk(e.tasks),role:Zk(e.role),purpose:Zk(e.purpose)},priority:n}})}const eA={apps:3,tasks:2,role:1,purpose:1};function tA(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*eA.apps,r.push(`apps(${i.join(`, `)})`));let a=(e.affinity.tasks??[]).filter(e=>t.tasks.includes(e));return a.length&&(n+=a.length*eA.tasks,r.push(`tasks(${a.join(`, `)})`)),(e.affinity.role??[]).includes(t.role)&&(n+=eA.role,r.push(`role(${t.role})`)),(e.affinity.purpose??[]).includes(t.purpose)&&(n+=eA.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 nA(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 rA(e){let t=new Set;try{let n=await e.readDir(Kk);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 iA(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 aA(e){return typeof e!=`string`||!e?null:e.toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||null}function oA(e,t){if(t.length===0)return e;let n=new Set(t.map(e=>e.name));return[...e.filter(e=>!n.has(e.name)),...t]}function sA(e,t){let n=e instanceof Error?e.message:String(e),r;try{r=new URL(t).host}catch{return n}return!r||n.includes(r)?n:`${n} (host: ${r} — network or CORS error)`}let cA;function lA(){return cA||=ut.create({dbName:qk}),cA}async function uA(){try{return(await(await lA()).readTextFile(`/workspace/.git/github-token`)).trim()||void 0}catch{return}}function dA(e,t=Jk){let n={Accept:t,"User-Agent":`slicc-upskill`};return e&&(n.Authorization=`Bearer ${e}`),n}async function fA(e){let t=await uA();return{hasToken:!!t,request:async(n,r=Jk)=>{try{return await e(n,{headers:dA(t,r)})}catch(e){throw Error(sA(e,n))}}}}function pA(e,t){if(!e)return;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}async function mA(){try{let e=(typeof window<`u`?window:globalThis).__slicc_reloadSkills;if(typeof e==`function`){await e();return}typeof chrome<`u`&&chrome?.runtime?.sendMessage&&chrome.runtime.sendMessage({source:`panel`,payload:{type:`reload-skills`}})}catch{}}async function hA(){try{let e=globalThis.__slicc_sprinkleManager;e&&typeof e.openNewAutoOpenSprinkles==`function`&&await e.openNewAutoOpenSprinkles()}catch{}}async function gA(){await hA(),await mA()}async function _A(e,t,n,r,i=!1){let a=`${Kk}/${t}`;try{if(await r.stat(a),!i)return{ok:!1,error:`skill "${t}" already exists (use --force to overwrite)`};await r.rm(a,{recursive:!0})}catch{}let o=e.replace(/^\/|\/$/g,``),s=o?o+`/`:``;await r.mkdir(a,{recursive:!0});let c=0;try{for(let[e,t]of Object.entries(n)){if(!e.startsWith(s))continue;let n=e.slice(s.length);if(!n||e.endsWith(`/`))continue;let i=`${a}/${n}`,o=i.replace(/\/+/g,`/`);if(o.includes(`/../`)||o.includes(`/..`)||!o.startsWith(a+`/`))continue;let l=i.substring(0,i.lastIndexOf(`/`));l!==a&&await r.mkdir(l,{recursive:!0}),await r.writeFile(i,t),c++}}catch(e){throw await r.rm(a,{recursive:!0}).catch(()=>{}),e}return c===0?(await r.rm(a,{recursive:!0}).catch(()=>{}),{ok:!1,error:`no files found for skill "${t}" in ZIP`}):{ok:!0}}function vA(e){let t=_e(e);if(!t)return;try{let e=JSON.parse(t);if(typeof e.message==`string`&&e.message.trim())return e.message.trim()}catch{}let n=t.trim();if(n)return n.slice(0,200)}function yA(e,t,n){let r=vA(e.body),i=r?` GitHub said: ${r}`:``,a=pA(e.headers,`retry-after`),o=pA(e.headers,`x-ratelimit-remaining`),s=r?.toLowerCase()??``;if(e.status===429||o===`0`||s.includes(`rate limit`))return n?`GitHub rate-limited access to ${t} (HTTP ${e.status}). The configured github.token was used, so retry later${a?` after about ${a} seconds`:``}.${i}`:`GitHub rate-limited anonymous access to ${t} (HTTP ${e.status}). This often happens on shared VPNs or corporate egress IPs because unauthenticated GitHub API requests are limited per IP. Configure a token with: git config github.token <PAT>, then retry. You can also retry off VPN or later.${i}`;if(e.status===401)return n?`GitHub rejected the configured github.token while accessing ${t} (HTTP 401). Update it with: git config github.token <PAT>, then retry.${i}`:`GitHub requires authentication to access ${t} (HTTP 401). Configure a token with: git config github.token <PAT>, then retry.${i}`;if(e.status===404)return`GitHub could not find ${t} (HTTP 404). Check the repository, path, and permissions.${i}`;if(e.status===403)return n?`GitHub denied access to ${t} (HTTP 403). Check that your github.token can access this repository or retry later if GitHub is throttling requests.${i}`:`GitHub denied anonymous access to ${t} (HTTP 403). If this repo is public on a shared VPN, you may have hit GitHub's shared IP limit; otherwise the repository or path may require authentication. Configure a token with: git config github.token <PAT>, then retry.${i}`;let c=e.statusText?` ${e.statusText}`:``;return`GitHub request for ${t} failed (HTTP ${e.status}${c}).${i}`}async function bA(e,t,n,r=`main`){let i=`https://codeload.github.com/${e}/${t}/zip/refs/heads/${r}`,o;try{o=await n(i,{headers:{"User-Agent":`slicc-upskill`}})}catch(e){return{status:`error`,message:sA(e,i)}}if(o.status===404)return r===`main`?bA(e,t,n,`master`):{status:`error`,message:`codeload returned HTTP 404`};if(o.status!==200)return{status:`error`,message:`codeload returned HTTP ${o.status}`};let s=a(i);s||=ge(o.body);try{return{status:`ok`,files:Ft(s)}}catch(e){return{status:`error`,message:`failed to unzip: ${e instanceof Error?e.message:String(e)}`}}}function xA(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.indexOf(`/`);if(e<0)continue;let i=n.slice(e+1);i&&(t[i]=r)}return t}async function SA(e,t,n,r){let i=0;for(let[a,o]of Object.entries(e)){if(!a.startsWith(t))continue;let e=a.slice(t.length);if(!e||a.endsWith(`/`))continue;let s=`${n}/${e}`,c=s.substring(0,s.lastIndexOf(`/`));c!==n&&await r.mkdir(c,{recursive:!0}),await r.writeFile(s,o),i++}return i}async function CA(e,t,n,r,i,o,s){for(let c of e)if(c.type===`file`&&c.download_url){let e=await s.request(c.download_url,`*/*`);if(e.status!==200)throw Error(yA(e,`${n}/${r}/${c.path}`,s.hasToken));let i=a(c.download_url);await o.writeFile(`${t}/${c.name}`,i??e.body)}else if(c.type===`dir`){let e=`https://api.github.com/repos/${n}/${r}/contents/${c.path}`,a=i?`${e}?ref=${encodeURIComponent(i)}`:e,l=await s.request(a);if(l.status!==200)throw Error(yA(l,`${n}/${r}/${c.path}`,s.hasToken));let u=B(l.body);await o.mkdir(`${t}/${c.name}`,{recursive:!0}),await CA(u,`${t}/${c.name}`,n,r,i,o,s)}}function wA(e){let t=e.match(/github\.com\/([^/?#]+)\/([^/?#]+)/);return t?{owner:t[1],repo:t[2].replace(/\.git$/,``)}:null}async function TA(e,t,n,r,i,a){if(i){let n=await bA(e,t,i,a);if(n.status===`ok`){let e=xA(n.files),t=[],i=r?r.replace(/^\/|\/$/g,``)+`/`:``;for(let n of Object.keys(e))if(n.startsWith(i)&&(n.split(`/`).pop()||``)===`SKILL.md`){let e=n.replace(/\/SKILL\.md$/,``),r=e.split(`/`).pop()||e;t.push({name:r,path:e})}return{skills:t}}}let o=[];async function s(r){let i=`https://api.github.com/repos/${e}/${t}/contents/${r}`,c=a?`${i}?ref=${encodeURIComponent(a)}`:i,l=await n.request(c);if(l.status!==200)throw Error(yA(l,`${e}/${t}${r?`/${r}`:``}`,n.hasToken));let u=B(l.body);for(let e of u)if(e.type===`file`&&e.name===`SKILL.md`){let t=e.path.replace(`/SKILL.md`,``),n=t.split(`/`).pop()||t;o.push({name:n,path:t})}else e.type===`dir`&&await s(e.path)}try{return await s(r||``),{skills:o}}catch(e){return{skills:[],error:e instanceof Error?e.message:String(e)}}}async function EA(e,t,n,r,i,a,o=!1,s,c){try{let l=`${Kk}/${r}`;try{if(await i.stat(l),!o)return{stdout:``,stderr:`upskill: skill "${r}" already exists (use --force to overwrite)\n`,exitCode:1};await i.rm(l,{recursive:!0})}catch{}if(s){let a=await bA(e,t,s,c);if(a.status===`ok`){let o=xA(a.files),s=n.replace(/^\/|\/$/g,``)+`/`;if(await i.mkdir(l,{recursive:!0}),await SA(o,s,l,i)>0)return await hA(),await mA(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}}let u=`https://api.github.com/repos/${e}/${t}/contents/${n}`,d=c?`${u}?ref=${encodeURIComponent(c)}`:u,f=await a.request(d);if(f.status!==200)return{stdout:``,stderr:`upskill: ${yA(f,`${e}/${t}/${n}`,a.hasToken)}\n`,exitCode:1};let p=B(f.body);await i.mkdir(l,{recursive:!0});try{await CA(p,l,e,t,c,i,a)}catch(e){try{await i.rm(l,{recursive:!0})}catch{}throw e}return await gA(),{stdout:`Installed skill "${r}" from ${e}/${t}\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`upskill: failed to install from GitHub: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function DA(e){let t=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?(?:\/tree\/([^/]+?)(?:\/(.+?))?)?\/?$/);if(t)return{owner:t[1],repo:t[2],branch:t[3],path:t[4]};let n=e.match(/^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_.-]+)(?:@([a-zA-Z0-9_./-]+))?$/);return n?{owner:n[1],repo:n[2],branch:n[3]}:null}async function OA(e,t){try{let n=aA(t);if(!n)return[];let r=await e(`${Yk}${n}.json`,{headers:{Accept:`application/json`}});return r.status===200?$k(B(r.body).data):[]}catch{return[]}}async function kA(e){let t;try{t=await e(Xk,{headers:{Accept:`application/json`}})}catch(e){throw Error(sA(e,Xk))}if(t.status!==200)throw Error(`HTTP ${t.status}`);return $k(B(t.body).data)}function AA(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 jA(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 _A(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 MA(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 TA(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 EA(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 NA(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 jA(d,e,n,c,o,s,r.count,i,a);l.push(...t.results),u+=t.line;continue}let f=AA(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 _A(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 PA(e,t,n,r,i,a,o,s,c,l){let u=await fA(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 MA(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 EA(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 FA(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 IA(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=iA(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=iA(JSON.parse(t));break}catch{}}catch{}if(!a)return i(`no-profile`);let o,s;try{let[n,r,i]=await Promise.all([kA(t),OA(t,a.company),rA(e)]);o=oA(n,r),s=i}catch(e){return i(`catalog-fetch`,[`upskill: failed to fetch skill catalog from ${Xk}: ${e instanceof Error?e.message:String(e)}`])}let c=tA(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=FA(await Promise.allSettled(Array.from(l.entries()).map(async([n,i])=>{let[a,o]=n.split(`/`),c=await bA(a,o,t);return c.status===`error`?PA(n,i,a,o,d,u,r,s,t,e):NA(n,i,xA(c.files),d,u,r,s,e)})),f,p);let h=(Date.now()-r)/1e3;return p.length>0&&(await gA(),m+=`\nInstalled ${p.length} recommended skill(s) in ${h.toFixed(1)}s\n`),{installedNames:p,errors:f,skipped:null,log:m,elapsedSeconds:h}}function LA(e){let t=e.toLowerCase();return t.startsWith(`www.`)?t.slice(4):t}let RA,zA;async function BA(e){if(RA)return RA;if(zA)return zA;zA=(async()=>{let t;try{t=await e(Gk,{headers:{Accept:`application/json`}})}catch(e){throw Error(sA(e,Gk))}if(t.status!==200)throw Error(`browse.sh returned HTTP ${t.status}`);let n=B(t.body),r=Array.isArray(n)?n:n.skills??[];return RA=r,r})();try{return await zA}catch(e){throw zA=void 0,e}}async function VA(e,t){let n=await BA(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 HA=/^[A-Za-z0-9._-]+$/;function UA(e){return!e||e===`.`||e===`..`?!1:HA.test(e)}function WA(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(`/`)||!UA(r)||!UA(i))return null;let a=LA(r);return UA(a)?{hostname:a,task:i}:null}function GA(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 KA(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(`
|
|
5571
|
+
`)}function qA(e,t){let n=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return n?`${n[1]}${n[2]||`
|
|
5572
|
+
`}\n${t}\n\n${e.slice(n[0].length)}`:`${t}\n\n${e}`}async function JA(e,t,n,r,i=!1){let a=`${e}/${t}`,o=`${Gk}/${e}/${t}`,s;try{let e=await r(o,{headers:{Accept:`application/json`}});if(e.status===404)return{stdout:``,stderr:`upskill: browse.sh skill "${a}" not found\n`,exitCode:1};if(e.status!==200)return{stdout:``,stderr:`upskill: browse.sh returned HTTP ${e.status} for "${a}"\n`,exitCode:1};s=B(e.body)}catch(e){return{stdout:``,stderr:`upskill: failed to fetch browse.sh skill "${a}": ${sA(e,o)}\n`,exitCode:1}}let c;if(s.skillMdUrl)try{let e=await r(s.skillMdUrl,{headers:{Accept:`text/plain`}});e.status===200&&(c=_e(e.body))}catch{}if(!c&&s.skillMd&&(c=s.skillMd),!c)return{stdout:``,stderr:`upskill: browse.sh skill "${a}" has no SKILL.md content\n`,exitCode:1};let l=GA(c,`name`),u=t.replace(/-[A-Za-z0-9]{4,8}$/,``),d=l||u||t;if(!UA(d)||d.length>64)return{stdout:``,stderr:`upskill: refusing to install browse.sh skill with unsafe name "${d}"\n`,exitCode:1};if(!UA(e))return{stdout:``,stderr:`upskill: refusing to install browse.sh skill with unsafe hostname "${e}"\n`,exitCode:1};let f=`browse-${e}-${d}`,p=`${Kk}/${f}`;try{if(await n.stat(p),!i)return{stdout:``,stderr:`upskill: skill "${f}" already exists (use --force to overwrite)\n`,exitCode:1};await n.rm(p,{recursive:!0})}catch{}let m=KA(s,a),h=qA(c,m);return await n.mkdir(p,{recursive:!0}),await n.writeFile(`${p}/SKILL.md`,h),await gA(),{stdout:`Installed skill "${f}" from browse.sh (${a})\n`,stderr:``,exitCode:0}}function YA(){return`Discovery roots: /workspace/skills plus accessible **/.agents/skills/*, **/.claude/skills/*, and **/.claude-plugin/marketplace.json skill collections anywhere in the VFS.
|
|
5573
|
+
`}function XA(e){switch(e){case`native`:return`native`;case`agents`:return`.agents`;case`claude`:return`.claude`;case`marketplace`:return`marketplace`}}function ZA(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)} ${XA(t.source).padEnd(11)} ${i}\n`}return o+=`\n${YA()}`,o}function QA(e){let t=`Skill: ${e.name}\n`;if(t+=`Description: ${e.description||`(none)`}\n`,t+=`Source: ${XA(e.source)}\n`,t+=`Source root: ${e.sourceRoot}\n`,e.skillFilePath&&(t+=`Instructions: ${e.skillFilePath}\n`),e.shadowedPaths?.length){t+=`Shadowed paths:
|
|
5574
|
+
`;for(let n of e.shadowedPaths)t+=` - ${n}\n`}return t}function $A(){return{stdout:`usage: upskill <command> [options]
|
|
5575
5575
|
|
|
5576
5576
|
Install skills from GitHub repositories, the Tessl registry, or browse.sh.
|
|
5577
5577
|
|
|
@@ -5585,7 +5585,7 @@ Commands:
|
|
|
5585
5585
|
tessl:<name> Install skill from Tessl registry
|
|
5586
5586
|
browse:<hostname>/<task> Install site-specific skill from browse.sh
|
|
5587
5587
|
|
|
5588
|
-
${
|
|
5588
|
+
${YA()}
|
|
5589
5589
|
GitHub Installation:
|
|
5590
5590
|
upskill owner/repo List available skills in repo
|
|
5591
5591
|
upskill owner/repo --skill name Install specific skill
|
|
@@ -5627,14 +5627,14 @@ Examples:
|
|
|
5627
5627
|
upskill aemcoder/skills@fix/stateless-tab-targeting --all
|
|
5628
5628
|
upskill tessl:postgres-pro
|
|
5629
5629
|
upskill browse:weather.gov/get-forecast-1uezib
|
|
5630
|
-
`,stderr:``,exitCode:0}}function
|
|
5630
|
+
`,stderr:``,exitCode:0}}function ej(e){return G(`skill`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return{stdout:`usage: skill <command> [options]
|
|
5631
5631
|
|
|
5632
5632
|
Commands:
|
|
5633
5633
|
list List discoverable skills
|
|
5634
5634
|
info <name> Show details about a skill
|
|
5635
5635
|
read <name> Read the SKILL.md instructions
|
|
5636
5636
|
|
|
5637
|
-
${
|
|
5637
|
+
${YA()}
|
|
5638
5638
|
For installing skills from registries or GitHub, use 'upskill':
|
|
5639
5639
|
upskill search "query" Search registries (Tessl + browse.sh)
|
|
5640
5640
|
upskill owner/repo --list List skills in GitHub repo
|
|
@@ -5646,53 +5646,53 @@ Examples:
|
|
|
5646
5646
|
skill list
|
|
5647
5647
|
skill info bluebubbles
|
|
5648
5648
|
skill read bluebubbles
|
|
5649
|
-
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-
|
|
5650
|
-
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:
|
|
5649
|
+
`,stderr:``,exitCode:0};let r=t[0],i=await import(`./skills-B5bs2JnW.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${YA()}Install skills with: upskill owner/repo --all\n`,stderr:``,exitCode:0}:{stdout:ZA(t,`Discoverable skills`),stderr:``,exitCode:0}}case`info`:{let n=t[1];if(!n)return{stdout:``,stderr:`skill: info requires a skill name
|
|
5650
|
+
`,exitCode:1};let r=await i.getSkillInfo(e,n);return r?{stdout:QA(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
|
|
5651
5651
|
`,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+`
|
|
5652
|
-
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}async function
|
|
5652
|
+
`,stderr:``,exitCode:0}}default:return{stdout:``,stderr:`skill: unknown command "${r}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`skill: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}async function tj(e,t){let n=`${Wk}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=20`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){throw Error(sA(e,n))}if(r.status!==200)throw Error(`Tessl returned HTTP ${r.status}`);let i=B(r.body);if(!i.data)return[];let a=new Map;for(let e of i.data){if(e.type!==`skill`)continue;let t=e.attributes,n=wA(t.sourceUrl),r=n?`${n.owner}/${n.repo}`:void 0,i=t.scores.aggregate==null?null:Math.round(t.scores.aggregate*100),o=t.sourceUrl||e.id,s=a.get(o);if(s&&s.qualityScore!=null&&i!=null&&s.qualityScore>=i)continue;let c=t.path.replace(/\/SKILL\.md$/i,``),l=c.split(`/`).pop()||t.name,u=n?`upskill ${n.owner}/${n.repo} --path ${c.split(`/`).slice(0,-1).join(`/`)||`.`} --skill ${l}`:`upskill tessl:${t.name}`;a.set(o,{name:t.name,displayName:t.name,summary:t.description||``,source:`tessl`,qualityScore:i,installHint:u,featured:t.featured,sourceRepo:r})}return Array.from(a.values())}async function nj(e,t){let n=`${Wk}/experimental/search?q=${encodeURIComponent(e)}&contentType=skills&page%5Bsize%5D=5`,r;try{r=await t(n,{headers:{Accept:`application/json`}})}catch(e){return{error:`Tessl search failed: ${sA(e,n)}`}}if(r.status!==200)return{error:`Tessl search failed (HTTP ${r.status})`};let i=B(r.body).data?.find(t=>t.type===`skill`&&t.attributes.name===e);if(!i)return{error:`skill "${e}" not found on Tessl registry`};let a=wA(i.attributes.sourceUrl);if(!a)return{error:`skill "${e}" has no GitHub source URL`};let o=i.attributes.path.replace(/\/SKILL\.md$/i,``);return{owner:a.owner,repo:a.repo,skillPath:o,skillName:e}}const rj=[{label:`Tessl`,host:new URL(Wk).host,fetch:tj},{label:`browse.sh`,host:new URL(Gk).host,fetch:VA}];function ij(e){let t=[],n=e.reduce((e,t)=>Math.max(e,t.length),0);for(let r=0;r<n;r++)for(let n of e)r<n.length&&t.push(n[r]);return t}async function aj(e,t,n=1){let r=await Promise.allSettled(rj.map(n=>n.fetch(e,t))),i=r.map(e=>e.status===`fulfilled`?e.value:[]),a=r.every(e=>e.status===`rejected`),o=ij(i),s=``;for(let e=0;e<r.length;e++){let t=r[e];if(t.status===`rejected`){let n=rj[e],r=t.reason instanceof Error?t.reason.message:String(t.reason);s+=`warning: ${n.label} registry unavailable (${n.host}): ${r}\n`}}if(o.length===0){let t=a?`${s}upskill: registries failed to respond\n`:s;return{stdout:`No skills found for "${e}"\n\nTry a different search term or browse the registries at https://tessl.io/registry or https://browse.sh\n`,stderr:t,exitCode:+!!a}}let c=o.length,l=Math.ceil(c/10),u=Math.max(1,Math.min(n,l)),d=(u-1)*10,f=o.slice(d,d+10),p=`Search results for "${e}" (page ${u}/${l}, ${c} total):\n\n`;for(let e of f){let t=e.qualityScore==null?` `:String(e.qualityScore).padStart(3),n=`[${e.source}]`,r=e.sourceRepo?` ${e.sourceRepo}`:``;p+=` ${e.name.padEnd(30)} ${t} ${n.padEnd(10)}${r}\n`,e.summary&&(p+=` ${e.summary}\n`),p+=`
|
|
5653
5653
|
`}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:
|
|
5654
5654
|
`,p+=` From Tessl: upskill <owner/repo> --skill <name>
|
|
5655
5655
|
`,p+=` From browse.sh: upskill browse:<hostname>/<task>
|
|
5656
|
-
`,{stdout:p,stderr:``,exitCode:0}}function
|
|
5656
|
+
`,{stdout:p,stderr:``,exitCode:0}}function oj(e,t,n){let r=`upskill ${e}`;return t&&(r+=` --branch ${t}`),n&&(r+=` --path ${n}`),r}async function sj(e,t){let n=[],r;try{r=await t(e,{method:`GET`})}catch(t){return n.push({rel:Ke,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=Je(i,e),o=[];for(let e of a){if(!e.rel.includes(Ke))continue;let t=Qe([e]);t?.verb===`upskill`&&o.push({target:t.target,branch:t.branch,path:t.path,instruction:t.instruction,installHint:oj(t.target,t.branch,t.path)})}return{links:o,failures:n}}function cj(e,t,n){if(!e||t.length===0)return[];let r=[];for(let i of t){if(!i.hostname||LA(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 lj(e){let t=e.active?` [active]`:``,n=`${e.title||`(untitled)`}${t}\n`;if(n+=` ${e.url}\n`,e.origin.length>0){n+=` Origin-advertised:
|
|
5657
5657
|
`;for(let t of e.origin)n+=` ${t.installHint}`,t.instruction&&(n+=` # ${t.instruction}`),n+=`
|
|
5658
5658
|
`}if(e.catalog.length>0){n+=` Browse.sh catalog:
|
|
5659
5659
|
`;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.
|
|
5660
5660
|
`);for(let t of e.failures)n+=` (discovery failed: ${t.error})\n`;return n+=`
|
|
5661
|
-
`,n}async function
|
|
5661
|
+
`,n}async function uj(e,t,n,r){if(!n)return{stdout:``,stderr:`upskill: browser APIs unavailable in this environment
|
|
5662
5662
|
`,exitCode:1};let i;try{i=await n.listPages()}catch{try{i=await n.listAllTargets()}catch(e){return{stdout:``,stderr:`upskill: failed to list browser tabs: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}if(i.length===0)return r?{stdout:JSON.stringify({tabs:[]},null,2)+`
|
|
5663
5663
|
`,stderr:``,exitCode:0}:{stdout:`No open browser tabs.
|
|
5664
|
-
`,stderr:``,exitCode:0};let a=[],o=``;try{a=await
|
|
5665
|
-
`,stderr:o,exitCode:0};let l=``;for(let e of c)l+=
|
|
5664
|
+
`,stderr:``,exitCode:0};let a=[],o=``;try{a=await BA(t)}catch(e){o=`upskill: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}\n`}let s=await rA(e),c=[];for(let e of i){let n=``;try{n=new URL(e.url).hostname}catch{}let r=n?LA(n):``,i=[],o=[];if(n&&/^https?:/i.test(e.url)){let n=await sj(e.url,t);i=n.links,o=n.failures}let l=cj(r,a,s);c.push({targetId:e.targetId,title:e.title,url:e.url,hostname:r,active:e.active,origin:i,catalog:l,failures:o})}if(r)return{stdout:JSON.stringify({tabs:c},null,2)+`
|
|
5665
|
+
`,stderr:o,exitCode:0};let l=``;for(let e of c)l+=lj(e);return{stdout:l,stderr:o,exitCode:0}}async function dj(e,t,n){if(n){let n=await IA(e,t);return n.skipped===`no-profile`?{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
|
|
5666
5666
|
`,exitCode:1}:n.skipped===`catalog-fetch`?{stdout:``,stderr:n.errors.map(e=>`${e}\n`).join(``),exitCode:1}:n.skipped===`all-installed`?{stdout:`No new skill recommendations — all matching skills are already installed.
|
|
5667
5667
|
`,stderr:``,exitCode:0}:{stdout:n.log,stderr:n.errors.map(e=>`${e}\n`).join(``),exitCode:+(n.errors.length>0)}}let r=null;try{let t=await e.readDir(`/home`);for(let n of t)try{let t=await e.readTextFile(`/home/${n.name}/.welcome.json`);r=JSON.parse(t);break}catch{}}catch{}if(!r)return{stdout:``,stderr:`upskill: no user profile found. Complete the welcome onboarding first, or create /home/<name>/.welcome.json manually.
|
|
5668
|
-
`,exitCode:1};let i,a;try{let[n,o,s]=await Promise.all([(async()=>{let e=await t(
|
|
5668
|
+
`,exitCode:1};let i,a;try{let[n,o,s]=await Promise.all([(async()=>{let e=await t(Xk,{headers:{Accept:`application/json`}});if(e.status!==200)throw Error(`HTTP ${e.status}`);return $k(B(e.body).data)})(),OA(t,r.company),rA(e)]);i=oA(n,o),a=s}catch(e){return{stdout:``,stderr:`upskill: failed to fetch skill catalog from ${Xk}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let o=tA(i,r).filter(e=>!a.has(e.entry.name));if(o.length===0)return{stdout:`No new skill recommendations — all matching skills are already installed.
|
|
5669
5669
|
`,stderr:``,exitCode:0};let s=`Recommended skills for you:
|
|
5670
5670
|
|
|
5671
|
-
`,c=0;for(let e of o){c++;let t=
|
|
5672
|
-
`,{stdout:s,stderr:``,exitCode:0}}function
|
|
5671
|
+
`,c=0;for(let e of o){c++;let t=nA(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
|
|
5672
|
+
`,{stdout:s,stderr:``,exitCode:0}}function fj(e){return!e||e.startsWith(`-`)?{stdout:``,stderr:`upskill: --branch requires a value
|
|
5673
5673
|
`,exitCode:1}:qe(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
|
|
5674
|
-
`,exitCode:1}}function
|
|
5675
|
-
`,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=
|
|
5676
|
-
`,stderr:``,exitCode:0}}async function
|
|
5677
|
-
`,exitCode:1};let a=await
|
|
5674
|
+
`,exitCode:1}}function pj(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`||!Xe(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
|
|
5675
|
+
`,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=fj(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 mj(e){let t=await(await import(`./skills-B5bs2JnW.js`).then(e=>e.t)).discoverSkills(e);return t.length===0?{stdout:`No discoverable local skills found.\n\n${YA()}`,stderr:``,exitCode:0}:{stdout:ZA(t,`Discoverable local skills`),stderr:``,exitCode:0}}async function hj(e,t,n){if(!t)return{stdout:``,stderr:`upskill: ${e} requires a skill name\n`,exitCode:1};let r=await import(`./skills-B5bs2JnW.js`).then(e=>e.t);if(e===`info`){let e=await r.getSkillInfo(n,t);return e?{stdout:QA(e),stderr:``,exitCode:0}:{stdout:``,stderr:`upskill: skill "${t}" not found\n`,exitCode:1}}let i=await r.readSkillInstructions(n,t);return i===null?{stdout:``,stderr:`upskill: no SKILL.md found for "${t}"\n`,exitCode:1}:{stdout:i+`
|
|
5676
|
+
`,stderr:``,exitCode:0}}async function gj(e,t,n,r,i,a,o){let s=``,c=``,l=0,u=e.length;for(let d=0;d<e.length;d++){let f=e[d],p=await _A(f.path,f.name,r,i,a),m=d+1,h=((Date.now()-o)/1e3).toFixed(1),g=(Date.now()-o)/m,_=m<u?` (~${Math.round((u-m)*g/1e3)}s remaining)`:``;p.ok?(s+=`[${m}/${u}] Installed "${f.name}" from ${t}/${n} (${h}s)${_}\n`,l++):(s+=`[${m}/${u}] Failed "${f.name}": ${p.error}${_}\n`,c+=`upskill: ${p.error}\n`)}return{output:s,errors:c,successCount:l}}async function _j(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 EA(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 vj(e,t,n,r,i,a,o,s){let c=``,l=``,u=0;for(let d of e){let e=await EA(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 yj(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 bj(e,t,n,r){let{owner:i,repo:a}=e,o=t.branch??e.branch,s=t.subPath??e.path,c=await fA(r),l=await TA(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:yj(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:yj(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 bA(i,a,r,o);if(e.status===`ok`){let r=await gj(u,i,a,xA(e.files),n,t.force,f);({output:p,errors:m,successCount:h}=r)}else{let e=await _j(u,i,a,c,n,t.force,o,f);({output:p,errors:m,successCount:h}=e)}}else({output:p,errors:m,successCount:h}=await vj(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 gA()),{stdout:p,stderr:m,exitCode:+!!m}}function xj(e,t,n){return G(`upskill`,async(r,i)=>{if(r.length===0||r.includes(`--help`)||r.includes(`-h`))return $A();if(r[0]===`tabs`)return uj(e,t,n,r.includes(`--json`));if(r[0]===`recommendations`)return dj(e,t,r.includes(`--install`));if(r[0]===`list`)return mj(e);if(r[0]===`info`||r[0]===`read`)return hj(r[0],r[1],e);if(r[0]===`search`)return Sj(r,t);let a=pj(r);if(a.earlyReturn)return a.earlyReturn;if(!a.sourceRef)return $A();if(a.sourceRef.startsWith(`tessl:`))return Cj(a.sourceRef,a.force,e,t);let o=WA(a.sourceRef);if(o)return JA(o.hostname,o.task,e,t,a.force);let s=DA(a.sourceRef);return s?bj(s,a,e,t):{stdout:``,stderr:`upskill: unrecognized source "${a.sourceRef}"\n\nExpected: owner/repo, tessl:<name>, or browse:<hostname>/<task>\n`,exitCode:1}})}async function Sj(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?aj(a,t,i):$A()}async function Cj(e,t,n,r){let i=e.slice(6);if(!i)return{stdout:``,stderr:`upskill: tessl: requires a skill name
|
|
5677
|
+
`,exitCode:1};let a=await nj(i,r);if(`error`in a)return{stdout:``,stderr:`upskill: ${a.error}\n`,exitCode:1};let o=await fA(r);return EA(a.owner,a.repo,a.skillPath,a.skillName,n,o,t,r)}function wj(){return{stdout:`usage: afplay [-v volume] [-r rate] <file>
|
|
5678
5678
|
|
|
5679
5679
|
Plays an audio file using the Web Audio API.
|
|
5680
5680
|
-v volume Volume level (0 to 1, default 1)
|
|
5681
5681
|
-r rate Playback rate (0.25 to 4, default 1)
|
|
5682
|
-
`,stderr:``,exitCode:0}}let
|
|
5683
|
-
`,exitCode:1};let o=r.fs.resolvePath(r.cwd,e),s;try{s=new Uint8Array(await r.fs.readFileBuffer(o))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}let c=_n(o);if(!c.startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};if(!i)try{let e=new ArrayBuffer(s.byteLength);return new Uint8Array(e).set(s),await a.call(`play-audio`,{bytes:e,mimeType:c,volume:t},{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}try{let e=
|
|
5682
|
+
`,stderr:``,exitCode:0}}let Tj=null;function Ej(){return(!Tj||Tj.state===`closed`)&&(Tj=new AudioContext),Tj}async function Dj(e,t,n,r){let i=Ue()&&typeof AudioContext<`u`,a=He();if(!i&&!a)return{stdout:``,stderr:`afplay: Web Audio API unavailable in this environment
|
|
5683
|
+
`,exitCode:1};let o=r.fs.resolvePath(r.cwd,e),s;try{s=new Uint8Array(await r.fs.readFileBuffer(o))}catch{return{stdout:``,stderr:`afplay: cannot open ${e}: No such file\n`,exitCode:1}}let c=_n(o);if(!c.startsWith(`audio/`))return{stdout:``,stderr:`afplay: ${e} is not an audio file\n`,exitCode:1};if(!i)try{let e=new ArrayBuffer(s.byteLength);return new Uint8Array(e).set(s),await a.call(`play-audio`,{bytes:e,mimeType:c,volume:t},{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}try{let e=Ej();e.state===`suspended`&&await e.resume();let r=new ArrayBuffer(s.byteLength);new Uint8Array(r).set(s);let i=await e.decodeAudioData(r),a=e.createBufferSource();a.buffer=i,a.playbackRate.value=n;let o=e.createGain();return o.gain.value=t,a.connect(o),o.connect(e.destination),new Promise(e=>{a.onended=()=>{e({stdout:``,stderr:``,exitCode:0})},a.start()})}catch(t){return{stdout:``,stderr:`afplay: failed to play ${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}}function Oj(){return G(`afplay`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return wj();let n=1,r=1,i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a===`-v`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -v requires a volume value
|
|
5684
5684
|
`,exitCode:1};if(n=parseFloat(e[++t]),isNaN(n)||n<0||n>1)return{stdout:``,stderr:`afplay: volume must be between 0 and 1
|
|
5685
5685
|
`,exitCode:1}}else if(a===`-r`){if(t+1>=e.length||e[t+1].startsWith(`-`))return{stdout:``,stderr:`afplay: -r requires a rate value
|
|
5686
5686
|
`,exitCode:1};if(r=parseFloat(e[++t]),isNaN(r)||r<.25||r>4)return{stdout:``,stderr:`afplay: rate must be between 0.25 and 4
|
|
5687
5687
|
`,exitCode:1}}else if(a.startsWith(`-`))return{stdout:``,stderr:`afplay: unknown option: ${a}\n`,exitCode:1};else{if(i!==null)return{stdout:``,stderr:`afplay: only one file can be specified
|
|
5688
|
-
`,exitCode:1};i=a}}return i?
|
|
5688
|
+
`,exitCode:1};i=a}}return i?Dj(i,n,r,t):wj()})}function kj(){return G(`chime`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`usage: chime
|
|
5689
5689
|
|
|
5690
5690
|
Plays a notification chime sound.
|
|
5691
5691
|
Alias for: afplay /shared/sounds/chime.mp3
|
|
5692
|
-
`,stderr:``,exitCode:0}:
|
|
5692
|
+
`,stderr:``,exitCode:0}:Dj(`/shared/sounds/chime.mp3`,1,1,t))}const Aj=n(`agent-command`);function jj(e,t,n){let r=t[n+1];return r===void 0||r.length>0&&r.startsWith(`-`)?{error:`agent: ${e} requires a value`}:r===``?{error:`agent: ${e} requires a non-empty value`}:{value:r,consumed:2}}function Mj(e,t,n){let r=jj(e,t,n);return`error`in r?{error:r.error,consumed:0}:Ai(r.value)?{value:r.value,consumed:r.consumed}:{error:`agent: ${e} must be one of: ${ki.join(`, `)}`,consumed:0}}function Nj(e,t){let n=jj(`--read-only`,e,t);if(`error`in n)return{error:n.error,consumed:0};let r=Rj(n.value);return r.length===0?{error:`agent: --read-only requires a non-empty value`,consumed:0}:{value:r,consumed:n.consumed}}function Pj(e,t){let n=e[t+1];if(n===void 0||n===``||n.length>0&&n.startsWith(`-`))return{error:`agent: --schema-b64 requires a value`,consumed:0};try{let e=atob(n),t=JSON.parse(new TextDecoder().decode(Uint8Array.from(e,e=>e.charCodeAt(0))));return typeof t!=`object`||!t?{error:`agent: --schema-b64 must decode to a JSON object`,consumed:0}:{value:t,consumed:2}}catch{return{error:`agent: --schema-b64 must be valid base64-encoded JSON`,consumed:0}}}function Fj(e,t,n,r){if(r.positionals.length===2)return r.positionals.push(e),{consumed:1};if(e===`-h`||e===`--help`)return r.help=!0,{consumed:1};if(e===`--model`){let i=jj(e,t,n);return`error`in i?{error:i.error,consumed:0}:(r.modelId=i.value,{consumed:i.consumed})}if(e===`--thinking`||e===`--effort`){let i=Mj(e,t,n);return i.error?{error:i.error,consumed:0}:(r.thinkingLevel=i.value,{consumed:i.consumed})}if(e===`--read-only`){let e=Nj(t,n);return e.error?{error:e.error,consumed:0}:(r.visiblePaths=e.value,{consumed:e.consumed})}if(e===`--schema-b64`){let e=Pj(t,n);return e.error?{error:e.error,consumed:0}:(r.schemaOut=e.value,{consumed:e.consumed})}return e.length>0&&e.startsWith(`-`)?{error:`agent: unknown flag '${e}'`,consumed:0}:(r.positionals.push(e),{consumed:1})}function Ij(e){if(e.help)return{help:!0};if(e.positionals.length<3)return{error:`agent: missing required argument ${[`<cwd>`,`<allowed-commands>`,`<prompt>`][e.positionals.length]}`};if(e.positionals.length>3)return{error:`agent: too many arguments`};let[t,n,r]=e.positionals;return{cwd:t,allowedCommandsRaw:n,prompt:r}}function Lj(e){let t={positionals:[],help:!1},n=0;for(;n<e.length;){let r=Fj(e[n],e,n,t);if(r.error)return{help:!1,error:r.error};n+=r.consumed}let r=Ij(t);if(`help`in r)return{help:!0};if(`error`in r)return{help:!1,error:r.error};let i=r;return{help:!1,cwd:i.cwd,allowedCommandsRaw:i.allowedCommandsRaw,prompt:i.prompt,modelId:t.modelId,visiblePaths:t.visiblePaths,thinkingLevel:t.thinkingLevel,structuredOutputSchema:t.schemaOut}}function Rj(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function zj(e,t){return e.startsWith(`/`)?rt(e):rt(`${t.length>0?t:`/`}/${e}`)}function Bj(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function Vj(e){return e==null?`
|
|
5693
5693
|
`:e.replace(/\n+$/,``)+`
|
|
5694
|
-
`}function
|
|
5695
|
-
`}function
|
|
5694
|
+
`}function Hj(e){return e==null||e===``?``:e.replace(/\n+$/,``)+`
|
|
5695
|
+
`}function Uj(){let e=globalThis.__slicc_agent;if(!(!e||typeof e.spawn!=`function`))return e}function Wj(e,t,n){return t?`agent: cwd not found: ${n}\n`:e&&!e.isDirectory?`agent: cwd not a directory: ${n}\n`:null}function Gj(e,t,n){let r=e;return typeof r.canWrite==`function`&&!r.canWrite(t)?`agent: cwd not writable: ${n}\n`:null}function Kj(e,t,n,r,i,a){let o={cwd:t,allowedCommands:n,prompt:r};e.modelId!==void 0&&(o.modelId=e.modelId),e.visiblePaths!==void 0&&(o.visiblePaths=e.visiblePaths),e.thinkingLevel!==void 0&&(o.thinkingLevel=e.thinkingLevel),e.structuredOutputSchema!==void 0&&(o.structuredOutputSchema=e.structuredOutputSchema),i.cwd&&i.cwd.length>0&&(o.invokingCwd=i.cwd);let s=a?.();return s!==void 0&&s.length>0&&(o.parentJid=s),o}function qj(e={}){let{getParentJid:t}=e;return G(`agent`,async(e,n)=>{let r=Lj(e);if(r.help)return{stdout:`usage: agent <cwd> <allowed-commands> <prompt>
|
|
5696
5696
|
|
|
5697
5697
|
Spawns a sub-scoop, feeds it a task, blocks until the agent loop completes,
|
|
5698
5698
|
then prints the scoop's final message on stdout.
|
|
@@ -5738,8 +5738,8 @@ Examples:
|
|
|
5738
5738
|
agent --thinking high . "*" "design a careful plan first"
|
|
5739
5739
|
agent --read-only /workspace/,/shared/assets/ . "*" "review the docs"
|
|
5740
5740
|
`,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let i=r.cwd??``;if(i===``)return{stdout:``,stderr:`agent: <cwd> must not be empty
|
|
5741
|
-
`,exitCode:1};let a=
|
|
5742
|
-
`,exitCode:1}})}async function
|
|
5741
|
+
`,exitCode:1};let a=zj(i,n.cwd),o=Bj(r.allowedCommandsRaw??``),s=r.prompt??``,c=null,l=!1;try{c=await n.fs.stat(a)}catch{l=!0}let u=Wj(c,l,i);if(u)return{stdout:``,stderr:u,exitCode:1};let d=Gj(n.fs,a,i);if(d)return{stdout:``,stderr:d,exitCode:1};let f=Uj();return f?Jj(f,Kj(r,a,o,s,n,t)):{stdout:``,stderr:`agent: orchestrator bridge not available
|
|
5742
|
+
`,exitCode:1}})}async function Jj(e,t){try{let n=await e.spawn(t),r=typeof n?.exitCode==`number`?n.exitCode:0,i=n?.finalText;return r===0?{stdout:Vj(i),stderr:``,exitCode:0}:{stdout:``,stderr:Hj(i),exitCode:r}}catch(e){let t=e instanceof Error?e.message:String(e);return Aj.error(`agent bridge threw`,e),{stdout:``,stderr:`${t}\n`,exitCode:1}}}function Yj(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 Xj=new Set([`js`,`mjs`,`cjs`,`jsx`,`ts`,`mts`,`cts`,`tsx`,`json`,`jsonc`,`css`,`graphql`,`gql`,`html`,`svelte`,`vue`,`astro`,`jsh`,`bsh`]),Zj=new Set([`check`,`format`]),Qj=`2.5.3`,$j=`6.0.0`,eM=bE,tM=`@biomejs/wasm-web@${Qj} @biomejs/js-api@${$j} esbuild-wasm@${eM}`,nM={"@biomejs/wasm-web":`@biomejs/wasm-web@${Qj}`,"@biomejs/js-api":`@biomejs/js-api@${$j}`,"esbuild-wasm":`esbuild-wasm@${eM}`},rM=`run: ipk add ${tM} (no network fallback)`,iM=`biome - thin wrapper over the ipk-loaded @biomejs/wasm-web
|
|
5743
5743
|
|
|
5744
5744
|
Usage:
|
|
5745
5745
|
biome <subcommand> [options] [files...]
|
|
@@ -5757,24 +5757,24 @@ Flags:
|
|
|
5757
5757
|
|
|
5758
5758
|
Install:
|
|
5759
5759
|
Inert until the backing packages are installed in node_modules:
|
|
5760
|
-
ipk add ${
|
|
5760
|
+
ipk add ${tM}
|
|
5761
5761
|
All three packages must be present in the VFS \`node_modules\` for
|
|
5762
5762
|
lint/format to run (loading the wasm-web ESM glue also needs the
|
|
5763
5763
|
esbuild-wasm transpiler). There is no bundled binary, no CDN
|
|
5764
5764
|
fallback; a missing package exits non-zero with a clear \`ipk add\` hint.
|
|
5765
|
-
`;function
|
|
5766
|
-
`,
|
|
5765
|
+
`;function aM(e){let t={subcommand:null,paths:[],write:!1,stdinFilePath:null,showHelp:!1,showVersion:!1};if(e.length===0)return t.showHelp=!0,t;for(let n=0;n<e.length;n++){let r=e[n];if(r===`-h`||r===`--help`){t.showHelp=!0;continue}if(r===`-v`||r===`--version`){t.showVersion=!0;continue}if(t.subcommand===null&&Zj.has(r)){t.subcommand=r;continue}if(r===`--write`){t.write=!0;continue}if(r===`--stdin-file-path`){let r=e[n+1];if(typeof r!=`string`||r.startsWith(`-`))throw Error(`biome: --stdin-file-path requires a value`);t.stdinFilePath=r,n+=1;continue}if(r.startsWith(`--stdin-file-path=`)){t.stdinFilePath=r.slice(18);continue}if(r.startsWith(`-`))throw Error(`biome: unknown option: ${r}`);t.paths.push(r)}return t}function oM(e){let t=e.lastIndexOf(`.`);return t<0?!1:Xj.has(e.slice(t+1).toLowerCase())}function sM(e){return e.endsWith(`.jsh`)||e.endsWith(`.bsh`)?`${e.slice(0,-4)}.js`:e}const cM=`async function __slicc() {
|
|
5766
|
+
`,lM=new TextEncoder().encode(cM).length;function uM(e){return e.endsWith(`.jsh`)||e.endsWith(`.bsh`)}function dM(e,t){let n=[e];for(;n.length>0;){let e=n.pop();if(!e||typeof e!=`object`)continue;if(Array.isArray(e)){for(let t of e)n.push(t);continue}let r=e,i=r.span;Array.isArray(i)&&i.length===2&&typeof i[0]==`number`&&typeof i[1]==`number`&&(r.span=[Math.max(0,i[0]-t),Math.max(0,i[1]-t)]),typeof r.sourceCode==`string`&&(r.sourceCode=null);for(let e of Object.keys(r))e===`span`||e===`sourceCode`||n.push(r[e])}}function fM(e){let t=(e.endsWith(`
|
|
5767
5767
|
`)?e.slice(0,-1):e).split(`
|
|
5768
5768
|
`);return t.shift(),t.pop(),t.map(e=>e.startsWith(` `)?e.slice(1):e).join(`
|
|
5769
5769
|
`)+`
|
|
5770
|
-
`}async function
|
|
5770
|
+
`}async function pM(e,t,n){let r=[],i=[];for(let a of n){let n=e.resolvePath(t,a);if(!await e.exists(n)){i.push(a);continue}(await e.stat?.(n))?.isDirectory?await mM(e,n,r):oM(n)&&r.push(n)}return{files:r,missing:i}}async function mM(e,t,n){let r=await e.readdir?.(t)??[];for(let i of r){if(i===`node_modules`||i.startsWith(`.git`))continue;let r=t===`/`?`/${i}`:`${t}/${i}`;(await e.stat?.(r))?.isDirectory?await mM(e,r,n):oM(r)&&n.push(r)}}async function hM(e){let t;try{t=await tn(`@biomejs/wasm-web/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;try{let n=await e.reader.readFile(t.path),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}async function gM(e){let t;try{t=await tn(`@biomejs/wasm-web/package.json`,e.fromDir,e.reader)}catch{return{ok:!1,missing:`@biomejs/wasm-web`}}if(t.type!==`file`)return{ok:!1,missing:`@biomejs/wasm-web`};try{if((await tn(`@biomejs/js-api/web`,e.fromDir,e.reader)).type!==`file`)return{ok:!1,missing:`@biomejs/js-api`}}catch{return{ok:!1,missing:`@biomejs/js-api`}}try{if((await tn(`esbuild-wasm/package.json`,e.fromDir,e.reader)).type!==`file`)return{ok:!1,missing:`esbuild-wasm`}}catch{return{ok:!1,missing:`esbuild-wasm`}}return{ok:!0,wasmPkgDir:nt(t.path).dir}}const _M=`
|
|
5771
5771
|
const fs = require('fs');
|
|
5772
|
-
const JSH_WRAP_PREFIX = ${JSON.stringify(
|
|
5772
|
+
const JSH_WRAP_PREFIX = ${JSON.stringify(cM)};
|
|
5773
5773
|
const JSH_WRAP_SUFFIX = ${JSON.stringify(`
|
|
5774
5774
|
}`)};
|
|
5775
|
-
const JSH_WRAP_PREFIX_BYTES = ${
|
|
5776
|
-
const shiftBiomeSpans = ${
|
|
5777
|
-
const unwrapFormattedJsh = ${
|
|
5775
|
+
const JSH_WRAP_PREFIX_BYTES = ${lM};
|
|
5776
|
+
const shiftBiomeSpans = ${dM.toString()};
|
|
5777
|
+
const unwrapFormattedJsh = ${fM.toString()};
|
|
5778
5778
|
async function compileBiomeWasm(wasmPath) {
|
|
5779
5779
|
// Prefer the host-side WASM compiler: biome's ~37 MB wasm hard-OOMs
|
|
5780
5780
|
// WebAssembly.compile inside this per-task realm worker, so the kernel
|
|
@@ -5879,9 +5879,9 @@ async function main() {
|
|
|
5879
5879
|
process.stdout.write(JSON.stringify(results));
|
|
5880
5880
|
}
|
|
5881
5881
|
main().catch((err) => { process.stderr.write(String(err && err.message || err) + '\\n'); process.exit(1); });
|
|
5882
|
-
`;function
|
|
5883
|
-
`,exitCode:2};let n=await
|
|
5884
|
-
`,exitCode:2};let i=await
|
|
5882
|
+
`;function vM(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}); ${rM}\n`}async function yM(e,t,n,r,i){let a={op:t,write:n,files:r.map(e=>({path:e.path,biomePath:sM(e.path),source:e.source,wrap:uM(e.path)}))},o=[`node`,`[biome-helper]`,JSON.stringify(a),i],s=await Lk(_M,o,e,void 0,{filename:`[biome-helper]`});if(s.exitCode!==0)return{results:[],stderr:vM(s.stderr)??s.stderr,exitCode:s.exitCode};try{return{results:JSON.parse(s.stdout),stderr:``,exitCode:0}}catch(e){return{results:[],stderr:`biome: failed to parse helper output: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function bM(e,t){let n=await gM(t);if(!n.ok)return{stdout:``,stderr:`biome: ${n.missing} is not installed (run: ipk add ${nM[n.missing]??n.missing}); ${rM}\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 ${nM[`@biomejs/wasm-web`]})\n`,exitCode:1}}async function xM(e,t){if(t.paths.length===0&&e.stdin)return{inputs:[{path:t.stdinFilePath??`/stdin.ts`,source:Pk(e.stdin)}],missingErrText:``};if(t.paths.length===0)return{stdout:``,stderr:`biome: no files or directories specified
|
|
5883
|
+
`,exitCode:2};let n=await pM(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 SM(e,t,n,r,i){let a=[],o=[i],s=0,c=0;for(let i of r.results)i.diagnosticsText&&o.push(i.diagnosticsText),s+=i.errorCount,t.write&&i.formatted!==null&&!i.unchanged?(await e.fs.writeFile(i.path,i.formatted),c++):!t.write&&t.subcommand===`format`&&n.length===1&&n[0].path===i.path&&a.push(i.formatted??n[0].source);t.write&&c>0&&o.push(`biome: wrote ${c} file(s)\n`);let l=+(s>0||i.length>0);return{stdout:a.join(``),stderr:o.join(``),exitCode:l}}async function CM(e){let t=await hM(e);return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`biome: @biomejs/wasm-web is not installed (run: ipk add @biomejs/wasm-web@${Qj}); ${rM}\n`,exitCode:1}}function wM(){return G(`biome`,async(e,t)=>{let n;try{n=aM(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}if(n.showHelp)return{stdout:iM,stderr:``,exitCode:0};let r=Yj(t);if(n.showVersion)return CM(r);if(n.subcommand===null)return{stdout:``,stderr:`biome: missing subcommand (expected check or format)
|
|
5884
|
+
`,exitCode:2};let i=await bM(t,r);if(`exitCode`in i)return i;let a=await xM(t,n);if(`exitCode`in a)return a;let o=await yM(t,n.subcommand,n.write,a.inputs,i.wasmPath);return o.exitCode===0?SM(t,n,a.inputs,o,a.missingErrText):{stdout:``,stderr:a.missingErrText+o.stderr,exitCode:o.exitCode}})}n(`tray-sync`);const TM=n(`scoops.tray-leave`);function EM(){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 DM(e={},t=EM()){let n=e.workerBaseUrl??null;if(t.storage)try{t.storage.removeItem(Fe),n===null?t.storage.removeItem(Ie):t.storage.setItem(Ie,n)}catch(t){TM.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 OM=n(`scoops.tray-join`);async function kM(e,t={},n=EM()){if(n.storage){let r=Pe(e);try{n.storage.setItem(Fe,r?.joinUrl??e),r&&n.storage.setItem(Ie,r.workerBaseUrl)}catch(e){OM.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 AM(){return jM()}function jM(){try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayFollowers`);if(e)return JSON.parse(e)}catch{}return[]}function MM(){let e=He();if(e)return async()=>await e.call(`tray-reset`,void 0)}function NM(){return{stdout:`host - display or manage the current tray host status
|
|
5885
5885
|
|
|
5886
5886
|
Usage: host [join <join-url> | reset | leave [--leader <worker-url>]]
|
|
5887
5887
|
|
|
@@ -5892,40 +5892,40 @@ Subcommands:
|
|
|
5892
5892
|
reset Disconnect all followers and create a fresh tray session with a new join URL
|
|
5893
5893
|
leave Leave the current tray (drops follower or stops leader; clears stored URLs)
|
|
5894
5894
|
leave --leader <worker-url> Leave the current role and immediately become a leader on <worker-url>
|
|
5895
|
-
`,stderr:``,exitCode:0}}function
|
|
5896
|
-
`)}\n`}function
|
|
5897
|
-
`)}\n`}function
|
|
5898
|
-
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:
|
|
5895
|
+
`,stderr:``,exitCode:0}}function PM(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 FM(e,t){let n=[`status: ${e.state}`];if(e.session?n.push(`join_url: ${e.session.joinUrl}`):n.push(`join_url: unavailable`),e.error&&n.push(`error: ${e.error}`),e.session&&t.length>0){n.push(`followers:`);for(let e of t){let t=[e.runtimeId];if(e.runtime&&t.push(`(${e.runtime})`),e.connectedAt){let n=Math.round((Date.now()-new Date(e.connectedAt).getTime())/1e3);t.push(`connected ${PM(n)}`)}n.push(` - ${t.join(` `)}`)}}return`${n.join(`
|
|
5896
|
+
`)}\n`}function IM(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: ${PM(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(`
|
|
5897
|
+
`)}\n`}function LM(e={}){let t=e.getStatus??Re,n=e.getFollowerStatus??rr,r=e.getFollowers??jM;return G(`host`,async i=>{if(i.includes(`--help`)||i.includes(`-h`))return NM();if(i[0]===`reset`){let r=e.resetTray??void 0??MM();return KM(n,t,r)}if(i[0]===`join`){let t=e.joinTray??VM();return HM(i.slice(1),t)}if(i[0]===`leave`){let r=e.leaveTray??RM();return UM(i.slice(1),t,n,r)}if(i.length>0)return{stdout:``,stderr:`host: unsupported arguments
|
|
5898
|
+
`,exitCode:1};let a=n();return a.state===`inactive`?{stdout:FM(t(),r()),stderr:``,exitCode:0}:{stdout:IM(a),stderr:``,exitCode:0}})}function RM(){return async({workerBaseUrl:e,requestId:t})=>{let n=He();if(n)return await n.call(`tray-leave`,{workerBaseUrl:e,requestId:t});let r=nr(),i=Re(),a=r.state===`inactive`?i.state===`inactive`?`inactive`:`leader`:`follower`;return await DM({workerBaseUrl:e,requestId:t}),e===null?a===`inactive`?{kind:`noop`}:{kind:`left`,previousMode:a}:{kind:`switched`,previousMode:a,workerBaseUrl:e}}}function zM(){return`host-leave-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function BM(){return`host-join-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function VM(){return async({joinUrl:e,requestId:t})=>{let n=He();if(n){await n.call(`tray-join`,{joinUrl:e,requestId:t});return}await kM(e,{requestId:t})}}async function HM(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
|
|
5899
5899
|
Usage: host join <join-url>
|
|
5900
5900
|
`,exitCode:1};let r=Pe(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".
|
|
5901
|
-
`,exitCode:1};try{return await t({joinUrl:r.joinUrl,requestId:
|
|
5902
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function
|
|
5903
|
-
`,exitCode:0}}try{return{stdout:
|
|
5904
|
-
`,exitCode:1}}}function
|
|
5901
|
+
`,exitCode:1};try{return await t({joinUrl:r.joinUrl,requestId:BM()}),{stdout:`Joining tray as follower: ${r.joinUrl}\nRun \`host\` to check connection status.
|
|
5902
|
+
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host join: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function UM(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=Ne(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
|
|
5903
|
+
`,exitCode:0}}try{return{stdout:WM(await r({workerBaseUrl:i,requestId:zM()})),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.
|
|
5904
|
+
`,exitCode:1}}}function WM(e){switch(e.kind){case`noop`:return`No active tray session.
|
|
5905
5905
|
`;case`left`:{let t=e.previousMode;switch(t){case`leader`:return`Stopped leader. Tray runtime is now dormant.
|
|
5906
5906
|
`;case`follower`:return`Disconnected from leader. Tray runtime is now dormant.
|
|
5907
|
-
`;default:return
|
|
5907
|
+
`;default:return GM(t)}}case`switched`:{let t=e.previousMode;switch(t){case`leader`:return`Stopped leader. Now leader on ${e.workerBaseUrl}\n`;case`follower`:return`Disconnected from leader. Now leader on ${e.workerBaseUrl}\n`;case`inactive`:return`Now leader on ${e.workerBaseUrl}\n`;default:return GM(t)}}default:return GM(e)}}function GM(e){throw Error(`formatLeaveResult: unhandled variant ${JSON.stringify(e)}`)}async function KM(e,t,n){if(e().state!==`inactive`)return{stdout:``,stderr:`host reset: only the leader can reset the tray session
|
|
5908
5908
|
`,exitCode:1};let r=t();if(r.state!==`leader`&&r.state!==`error`)return{stdout:``,stderr:`host reset: no active tray session to reset
|
|
5909
5909
|
`,exitCode:1};if(!n)return{stdout:``,stderr:`host reset: tray reset is not available in this environment
|
|
5910
5910
|
`,exitCode:1};try{return{stdout:`Tray session reset. All followers disconnected.
|
|
5911
|
-
`+
|
|
5911
|
+
`+FM(await n(),[]),stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`host reset: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function qM(e={}){let t=e.getFollowers??AM,n=e.getPanelRpc??He,r=e.getEmitter??(()=>null);return{listRuntimeIds(){return t().filter(e=>e.runtime===`slicc-cherry`).map(e=>e.runtimeId)},async emitSliccEvent(e,t,i){let a=r();if(a)try{return await a(e,t,i)?{delivered:!0}:{delivered:!1,reason:`the follower runtime is not connected to the leader`}}catch(e){return{delivered:!1,reason:`direct emit failed: ${e instanceof Error?e.message:String(e)}`}}let o=n();if(!o)return{delivered:!1,reason:`no page bridge to the leader tray (panel-RPC client)`};try{return(await o.call(`cherry-emit`,{runtimeId:e,name:t,detail:i}))?.delivered?{delivered:!0}:{delivered:!1,reason:`the follower runtime is not connected to the leader`}}catch(e){return{delivered:!1,reason:`panel-RPC delivery failed: ${e instanceof Error?e.message:String(e)}`}}}}}function JM(e){return{stdout:``,stderr:`cherry-emit: ${e}\n`,exitCode:1}}function YM(e){let t={positionals:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r!==`--detail`&&r!==`--runtime`){t.positionals.push(r);continue}let i=e[n+1];if(i===void 0||i.startsWith(`--`))return JM(`${r} requires a value`);r===`--detail`?t.detailJson=i:t.runtime=i,n++}return t}function XM(e,t){return e.length===0?JM(`no cherry follower runtime is connected`):t?e.includes(t)?t:JM(`runtime '${t}' not connected. Available: ${e.join(`, `)}`):e.length>1?JM(`multiple runtimes connected, pass --runtime <id>. Available: ${e.join(`, `)}`):e[0]}function ZM(e){if(e===void 0)return{detail:void 0};try{return{detail:JSON.parse(e)}}catch{return JM(`--detail must be valid JSON`)}}function QM(e={}){let t=e.registry??qM();return G(`cherry-emit`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`cherry-emit - push a slicc.event to a cherry host page through a follower runtime
|
|
5912
5912
|
|
|
5913
5913
|
Usage: cherry-emit <name> [--detail <json>] [--runtime <id>]
|
|
5914
5914
|
|
|
5915
5915
|
--detail <json> JSON payload delivered as the event detail
|
|
5916
5916
|
--runtime <id> Target a specific follower runtime (canonical id, e.g. follower-abc).
|
|
5917
5917
|
Defaults to the sole connected runtime; required when more than one.
|
|
5918
|
-
`,stderr:``,exitCode:0};let n=
|
|
5918
|
+
`,stderr:``,exitCode:0};let n=YM(e);if(`exitCode`in n)return n;let r=n.positionals[0];if(!r)return JM(`event name is required`);let i=XM(t.listRuntimeIds(),n.runtime);if(typeof i!=`string`)return i;let a=ZM(n.detailJson);if(`exitCode`in a)return a;let o=await t.emitSliccEvent(i,r,a.detail);return o.delivered?{stdout:`cherry-emit: sent '${r}' to ${i}\n`,stderr:``,exitCode:0}:JM(`failed to deliver '${r}' to ${i}: ${o.reason}`)})}function $M(e){return e instanceof Error?e.message:String(e)}function eN(){return{stdout:`usage: pbcopy
|
|
5919
5919
|
|
|
5920
5920
|
Copy stdin to the clipboard.
|
|
5921
5921
|
Example: echo hello | pbcopy
|
|
5922
|
-
`,stderr:``,exitCode:0}}function
|
|
5922
|
+
`,stderr:``,exitCode:0}}function tN(){return{stdout:`usage: pbpaste
|
|
5923
5923
|
|
|
5924
5924
|
Paste clipboard contents to stdout.
|
|
5925
|
-
`,stderr:``,exitCode:0}}function
|
|
5925
|
+
`,stderr:``,exitCode:0}}function nN(e){return{stdout:`usage: ${e} [-i|-o]\n\n -i Force copy mode (read from stdin)
|
|
5926
5926
|
-o Force paste mode (write to stdout)
|
|
5927
5927
|
(default) Auto-detect: stdin present = copy, no stdin = paste
|
|
5928
|
-
Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function
|
|
5928
|
+
Example: echo hello | ${e}\n Example: ${e} -o > file.txt\n`,stderr:``,exitCode:0}}async function rN(e,t){let n=!!globalThis.navigator?.clipboard,r=n?null:He();if(!n&&!r)return{stdout:``,stderr:`${t}: clipboard API is unavailable\n`,exitCode:1};try{return n?await navigator.clipboard.writeText(e):await r.call(`clipboard-write-text`,{text:e}),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`${t}: failed to write to clipboard: ${$M(e)}\n`,exitCode:1}}}async function iN(e){let t=!!globalThis.navigator?.clipboard,n=t?null:He();if(!t&&!n)return{stdout:``,stderr:`${e}: clipboard API is unavailable\n`,exitCode:1};try{return{stdout:t?await navigator.clipboard.readText():(await n.call(`clipboard-read-text`,void 0)).text,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: failed to read from clipboard: ${$M(t)}\n`,exitCode:1}}}function aN(){return G(`pbcopy`,async(e,t)=>e.includes(`--help`)||e.includes(`-h`)?eN():rN(Pk(t.stdin),`pbcopy`))}function oN(){return G(`pbpaste`,async e=>e.includes(`--help`)||e.includes(`-h`)?tN():iN(`pbpaste`))}function sN(e){return G(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return nN(e);let r=t.includes(`-i`),i=t.includes(`-o`);if(r&&i)return{stdout:``,stderr:`${e}: cannot use both -i and -o\n`,exitCode:1};if(i)return iN(e);let a=Pk(n.stdin);return r||a.length>0?rN(a,e):iN(e)})}function cN(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}function lN(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`JPEG`:t.endsWith(`.png`)?`PNG`:t.endsWith(`.gif`)?`GIF`:t.endsWith(`.webp`)?`WEBP`:t.endsWith(`.bmp`)?`BMP`:t.endsWith(`.tiff`)||t.endsWith(`.tif`)?`TIFF`:t.endsWith(`.avif`)?`AVIF`:`PNG`}function uN(){return{stdout:`usage: convert [input] [operations...] [output]
|
|
5929
5929
|
|
|
5930
5930
|
Operations:
|
|
5931
5931
|
-resize WxH resize to width x height
|
|
@@ -5940,7 +5940,7 @@ Examples:
|
|
|
5940
5940
|
convert photo.png -resize 50% smaller.png
|
|
5941
5941
|
convert image.jpg -rotate 90 -quality 85 rotated.jpg
|
|
5942
5942
|
convert input.png -crop 100x100+50+50 cropped.png
|
|
5943
|
-
`,stderr:``,exitCode:0}}const
|
|
5943
|
+
`,stderr:``,exitCode:0}}const dN=new Set([`-resize`,`-rotate`,`-crop`,`-quality`]);function fN(e){let t=[],n=[],r=0;for(;r<e.length;){let i=e[r];if(dN.has(i)){if(r+1>=e.length||e[r+1].startsWith(`-`))throw Error(`missing argument for ${i}`);let t=i.slice(1);n.push({type:t,value:e[r+1]}),r+=2;continue}if(i.startsWith(`-`))throw Error(`unsupported option ${i}`);t.push(i),r+=1}if(t.length!==2)throw Error(`expected exactly one input file and one output file`);return{operations:n,positional:t}}function pN(e,t,n){let r=n.match(/^(\d+)%$/);if(r){let e=parseInt(r[1],10),n=Math.round(t.width*e/100),i=Math.round(t.height*e/100);t.resize(n,i);return}let i=n.endsWith(`!`),a=(i?n.slice(0,-1):n).split(`x`);if(a.length!==2)throw Error(`Invalid resize format: ${n}`);let o=parseInt(a[0],10),s=parseInt(a[1],10);if(i){let n=new e.MagickGeometry(o,s);n.ignoreAspectRatio=!0,t.resize(n)}else t.resize(o,s)}function mN(e,t){let n=parseFloat(t);if(isNaN(n))throw Error(`Invalid rotation degrees: ${t}`);e.rotate(n)}function hN(e,t,n){if(!n.match(/^(\d+)x(\d+)\+(\d+)\+(\d+)$/))throw Error(`Invalid crop format: ${n} (expected WxH+X+Y)`);let r=new e.MagickGeometry(n);t.crop(r)}function gN(e,t){let n=parseInt(t,10);if(isNaN(n)||n<0||n>100)throw Error(`Invalid quality: ${t} (must be 0-100)`);e.quality=n}function _N(e,t,n){switch(n.type){case`resize`:pN(e,t,n.value);return;case`rotate`:mN(t,n.value);return;case`crop`:hN(e,t,n.value);return;case`quality`:gN(t,n.value);return}}async function vN(e,t,n,r){for(let r of n)_N(e,t,r);let i=null,a=lN(r);return t.write(a,e=>{i=new Uint8Array(e)}),i}function yN(e=`convert`){return G(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return uN();let r;try{r=fN(t)}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}let[i,a]=r.positional;try{let e=n.fs.resolvePath(n.cwd,i),t=await n.fs.readFileBuffer(e),o=await En({ipk:cN(n)}),s=null;if(await o.ImageMagick.read(t,async e=>{s=await vN(o,e,r.operations,a)}),!s||s.byteLength===0)throw Error(`Failed to generate output image`);let c=n.fs.resolvePath(n.cwd,a);return await n.fs.writeFile(c,s),{stdout:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function bN(){return{stdout:`usage: crontask <command> [options]
|
|
5944
5944
|
|
|
5945
5945
|
Commands:
|
|
5946
5946
|
create [options] Create a new cron task
|
|
@@ -5972,14 +5972,14 @@ Examples:
|
|
|
5972
5972
|
crontask create --name every-5min --scoop poller --cron "*/5 * * * *" --filter "() => ({ time: Date.now() })"
|
|
5973
5973
|
crontask list
|
|
5974
5974
|
crontask delete abc123
|
|
5975
|
-
`,stderr:``,exitCode:0}}function
|
|
5975
|
+
`,stderr:``,exitCode:0}}function xN(){return globalThis.__slicc_lickManager??null}let SN=null;async function CN(){if(SN)return SN;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return SN=e(),SN}async function wN(e,t,n){let r={method:e,headers:m({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(u(`/api/crontasks${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}async function TN(e){let t,n,r,i,a=e.indexOf(`--name`);a!==-1&&e[a+1]&&(t=e[a+1]);let o=e.indexOf(`--cron`);o!==-1&&e[o+1]&&(n=e[o+1]);let s=e.indexOf(`--filter`);s!==-1&&e[s+1]&&(r=e[s+1]);let c=e.indexOf(`--scoop`);if(c!==-1&&e[c+1]&&(i=e[c+1]),!t)return{stdout:``,stderr:`crontask: --name is required
|
|
5976
5976
|
`,exitCode:1};if(!n)return{stdout:``,stderr:`crontask: --cron is required
|
|
5977
5977
|
`,exitCode:1};if(!S()){if(r)return{stdout:``,stderr:`crontask: --filter is not supported in extension mode (CSP restriction)
|
|
5978
|
-
`,exitCode:1};let e=
|
|
5978
|
+
`,exitCode:1};let e=xN(),a=e?await e.createCronTask(t,n,i):await(await CN()).createCronTask(t,n,i),o=`Created cron task "${a.name}"\n`;return o+=`ID: ${a.id}\n`,o+=`Cron: ${a.cron}\n`,a.scoop&&(o+=`Scoop: ${a.scoop}\n`),a.nextRun&&(o+=`Next run: ${new Date(a.nextRun).toLocaleString()}\n`),{stdout:o,stderr:``,exitCode:0}}let{ok:l,data:u}=await wN(`POST`,``,{name:t,cron:n,filter:r,scoop:i});if(!l)return{stdout:``,stderr:`crontask: failed to create: ${u.error??`unknown error`}\n`,exitCode:1};let d=u,f=`Created cron task "${d.name}"\n`;return f+=`ID: ${d.id}\n`,f+=`Cron: ${d.cron}\n`,d.scoop&&(f+=`Scoop: ${d.scoop}\n`),d.filter&&(f+=`Filter: ${d.filter}\n`),d.nextRun&&(f+=`Next run: ${new Date(d.nextRun).toLocaleString()}\n`),{stdout:f,stderr:``,exitCode:0}}function EN(e){let t=`Active cron tasks:
|
|
5979
5979
|
`;for(let n of e)t+=` ${n.id} ${n.name.padEnd(20)} ${n.cron.padEnd(15)}`,n.scoop&&(t+=` -> ${n.scoop}`),n.filter&&(t+=` [filtered]`),t+=` (${n.status})`,n.nextRun&&(t+=` next: ${new Date(n.nextRun).toLocaleString()}`),t+=`
|
|
5980
|
-
`;return t}async function
|
|
5981
|
-
`,stderr:``,exitCode:0}:{stdout:
|
|
5982
|
-
`,stderr:``,exitCode:0}:{stdout:
|
|
5980
|
+
`;return t}async function DN(){if(!S()){let e=xN(),t=e?e.listCronTasks():await(async()=>{let{listCronTasksAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return e()})();return t.length===0?{stdout:`No active cron tasks
|
|
5981
|
+
`,stderr:``,exitCode:0}:{stdout:EN(t),stderr:``,exitCode:0}}let{ok:e,data:t}=await wN(`GET`,``);if(!e)return{stdout:``,stderr:`crontask: failed to list: ${t.error??`unknown error`}\n`,exitCode:1};let n=t;return n.length===0?{stdout:`No active cron tasks
|
|
5982
|
+
`,stderr:``,exitCode:0}:{stdout:EN(n),stderr:``,exitCode:0}}async function ON(e){let t=e[0],n=e[1];if(!n)return{stdout:``,stderr:`crontask: ${t} requires an ID\n`,exitCode:1};if(!S()){let e=xN();return(e?await e.deleteCronTask(n):await(await CN()).deleteCronTask(n))?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}}let{ok:r,status:i,data:a}=await wN(`DELETE`,`/${n}`);return r?{stdout:`Deleted cron task "${n}"\n`,stderr:``,exitCode:0}:i===404?{stdout:``,stderr:`crontask: task "${n}" not found\n`,exitCode:1}:{stdout:``,stderr:`crontask: failed to delete: ${a.error??`unknown error`}\n`,exitCode:1}}function kN(){return G(`crontask`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return bN();let t=e[0];try{switch(t){case`create`:return await TN(e);case`list`:return await DN();case`delete`:case`kill`:return await ON(e);default:return{stdout:``,stderr:`crontask: unknown command "${t}"\n`,exitCode:1}}}catch(e){return{stdout:``,stderr:`crontask: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const AN=`slicc-fs`;async function jN(){try{let e=globalThis.indexedDB;if(!e)return!1;let t=e.databases;return typeof t!=`function`||(await t.call(e)).some(e=>e.name===AN)}catch{return!0}}async function MN(){let e=globalThis.indexedDB;return e?new Promise(t=>{let n;try{n=e.deleteDatabase(AN)}catch{t(`error`);return}n.onsuccess=()=>t(`deleted`),n.onerror=()=>t(`error`),n.onblocked=()=>t(`blocked`)}):`error`}async function NN(){if(!await jN())return{kind:`absent`,message:`legacy slicc-fs IDB not present — nothing to clean`};let e=await MN();return e===`deleted`?{kind:`deleted`,message:`legacy slicc-fs IDB deleted`}:e===`blocked`?{kind:`blocked`,message:`legacy slicc-fs IDB delete blocked by another connection — close other tabs and retry`}:{kind:`error`,message:`legacy slicc-fs IDB delete failed`}}function PN(){return`slicc-fs-cleanup — delete the legacy slicc-fs IndexedDB
|
|
5983
5983
|
|
|
5984
5984
|
Usage:
|
|
5985
5985
|
slicc-fs-cleanup Delete the legacy slicc-fs IDB.
|
|
@@ -5988,7 +5988,7 @@ Usage:
|
|
|
5988
5988
|
SLICC's filesystem lives in OPFS; the legacy slicc-fs IndexedDB from
|
|
5989
5989
|
the pre-OPFS era is never read anymore. This command deletes it on
|
|
5990
5990
|
explicit invocation to reclaim the space.
|
|
5991
|
-
`}const
|
|
5991
|
+
`}const FN={deleted:0,absent:0,blocked:1,error:1};function IN(e={}){let t=e.runCleanup??NN;return G(`slicc-fs-cleanup`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:PN(),stderr:``,exitCode:0};if(e.length>0)return{stdout:``,stderr:`slicc-fs-cleanup: unsupported argument: ${e[0]}\n`,exitCode:1};let n=await t(),r=FN[n.kind];return r===0?{stdout:`${n.message}\n`,stderr:``,exitCode:r}:{stdout:``,stderr:`slicc-fs-cleanup: ${n.message}\n`,exitCode:r}})}function LN(e){return`${e} — report VFS backend and storage usage/quota
|
|
5992
5992
|
|
|
5993
5993
|
Usage:
|
|
5994
5994
|
${e} Show diagnostics (raw bytes).
|
|
@@ -5996,16 +5996,16 @@ Usage:
|
|
|
5996
5996
|
${e} --help Show this help.
|
|
5997
5997
|
|
|
5998
5998
|
Read-only. Cleanup of the legacy IndexedDB lives in 'slicc-fs-cleanup'.
|
|
5999
|
-
`}function
|
|
5999
|
+
`}function RN(){return`diskutil — VFS diagnostics alias
|
|
6000
6000
|
|
|
6001
6001
|
Usage:
|
|
6002
6002
|
diskutil info Show VFS diagnostics (alias for 'df -h').
|
|
6003
6003
|
diskutil --help Show this help.
|
|
6004
6004
|
|
|
6005
6005
|
Read-only. See 'df --help' for the underlying command.
|
|
6006
|
-
`}function
|
|
6007
|
-
`)}\n`}function
|
|
6008
|
-
`,exitCode:1}})}const
|
|
6006
|
+
`}function zN(e){if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`,`TB`,`PB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n>=100?n.toFixed(0):n>=10?n.toFixed(1):n.toFixed(2)} ${t[r]}`}function BN(e,t){return e===null?`unavailable`:t?zN(e):`${e}`}async function VN(e){let t=e.fs?.backend??`unknown`,n=null,r=null,i=null,a=globalThis.navigator?.storage;if(a){try{let e=await a.estimate();n=typeof e.usage==`number`?e.usage:null,r=typeof e.quota==`number`?e.quota:null}catch{}if(typeof a.persisted==`function`)try{i=await a.persisted()}catch{i=null}}let o=null,s=e.legacyIdbExists??jN;try{o=await s()}catch{o=null}return{backend:t,usage:n,quota:r,persisted:i,legacyIdbPresent:o}}function HN(e,t){let n=e.usage!==null&&e.quota!==null&&e.quota>0?`${Math.round(e.usage/e.quota*100)}%`:`unavailable`,r=e.persisted===null?`unavailable`:e.persisted?`true`:`false`,i=e.legacyIdbPresent===null?`unavailable`:e.legacyIdbPresent?`present (slicc-fs)`:`absent`;return`${[`Backend: ${e.backend}`,`Usage: ${BN(e.usage,t)}`,`Quota: ${BN(e.quota,t)}`,`Used: ${n}`,`Persisted: ${r}`,`Legacy IDB: ${i}`].join(`
|
|
6007
|
+
`)}\n`}function UN(e={}){return G(`df`,async t=>{if(t.includes(`--help`))return{stdout:LN(`df`),stderr:``,exitCode:0};let n=new Set([`-h`,`--human-readable`]),r=t.find(e=>!n.has(e));if(r!==void 0)return{stdout:``,stderr:`df: unsupported argument: ${r}\n`,exitCode:1};let i=t.includes(`-h`)||t.includes(`--human-readable`);return{stdout:HN(await VN(e),i),stderr:``,exitCode:0}})}function WN(e={}){return G(`diskutil`,async t=>{if(t.includes(`--help`))return{stdout:RN(),stderr:``,exitCode:0};let n=t[0];return n===`info`?{stdout:HN(await VN(e),!0),stderr:``,exitCode:0}:{stdout:``,stderr:n?`diskutil: unsupported subcommand: ${n} (try 'diskutil info')\n`:`diskutil: missing subcommand (try 'diskutil info')
|
|
6008
|
+
`,exitCode:1}})}const GN=n(`di`),KN=new WeakMap;async function qN(e,t){let n=KN.get(e);if(n)return n;let r;if(await e.exists(`/workspace/node_modules/pyodide/pyodide-lock.json`))try{r=await e.readFile(`/workspace/node_modules/pyodide/pyodide-lock.json`)}catch(e){return GN.error(`failed to read pyodide-lock.json`,e),null}else{let e=`${xv}pyodide-lock.json`,n;try{n=await t(e,{method:`GET`,headers:{Accept:`application/json`},timeoutMs:3e4})}catch(e){return GN.error(`failed to fetch pyodide-lock.json from CDN`,e),null}if(n.status<200||n.status>=300)return GN.error(`pyodide-lock.json CDN fetch returned HTTP ${n.status}`),null;r=_e(n.body)}let i;try{i=JSON.parse(r)}catch(e){return GN.error(`pyodide-lock.json was not valid JSON`,e),null}let a=new Map;for(let[e,t]of Object.entries(i.packages??{}))!t||typeof t.file_name!=`string`||a.set(b_(t.name??e),t);return KN.set(e,a),a}async function JN(e,t,n,r){let i=await qN(e,t);if(!i)return null;let a=i.get(b_(n));if(!a?.file_name||!a.version||!a.sha256)return null;if(r&&r!==a.version)throw Error(`di: ${n}==${r} requested but the Pyodide lockfile pins ${a.name??n}==${a.version} (the Pyodide CDN serves only the locked version — omit the version, or use real uv locally)`);return{name:a.name??n,version:a.version,source:`pyodide-cdn`,fileName:a.file_name,sha256:a.sha256,url:`${xv}${a.file_name}`}}function YN(e,t){let n=`https://pypi.org/pypi/${encodeURIComponent(e)}`;return t?`${n}/${encodeURIComponent(t)}/json`:`${n}/json`}function XN(e){if(!e.endsWith(`.whl`))return null;let t=e.slice(0,-4).split(`-`);return t.length<3?null:t[t.length-1]}async function ZN(e,t,n){let r=`di: PyPI lookup for ${t}${n?`==${n}`:``}`,i=YN(t,n),a;try{a=await e(i,{method:`GET`,headers:{Accept:`application/json`},timeoutMs:3e4})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`${r}: network error (${t})`)}if(a.status===404)throw Error(`di: package '${t}'${n?` version '${n}'`:``} not found on PyPI`);if(a.status<200||a.status>=300){let e=a.statusText?` ${a.statusText}`:``;throw Error(`${r} returned HTTP ${a.status}${e}`)}let o;try{o=JSON.parse(_e(a.body))}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`${r}: response was not valid JSON (${t})`)}let s=o.info?.name??t,c=o.info?.version??n;if(!c)throw Error(`${r}: PyPI did not report a version for '${t}'`);let l=(o.urls??[]).filter(e=>e.packagetype===`bdist_wheel`&&typeof e.filename==`string`&&typeof e.url==`string`);if(l.length===0)throw Error(`di: ${s}==${c} has no wheel on PyPI (sdist/source-only packages are not supported in SLICC's di subset — use real uv locally)`);let u=l.find(e=>XN(e.filename)===`any`);if(!u){let e=l.map(e=>e.filename).join(`, `);throw Error(`di: ${s}==${c} only ships platform-specific wheels (${e}); SLICC's di subset installs pure-Python (none-any) wheels only — use real uv locally for compiled packages`)}let d=u.digests?.sha256;if(!d)throw Error(`di: PyPI did not provide a sha256 digest for ${u.filename}`);return{name:s,version:c,source:`pypi`,fileName:u.filename,sha256:d,url:u.url}}const QN=`/workspace/python_wheels`,$N=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function eP(e){let t=e.trim();if(!t)throw Error(`di: package spec is required`);let n=t,r,i=t.indexOf(`==`);if(i!==-1)n=t.slice(0,i),r=t.slice(i+2);else{let e=t.indexOf(`@`);e!==-1&&(n=t.slice(0,e),r=t.slice(e+1))}if(n=n.trim(),r=r?.trim(),!$N.test(n))throw Error(`di: invalid package name '${n}'`);if(r!==void 0&&r===``)throw Error(`di: empty version in spec '${e}'`);return{name:n,version:r}}function tP(e){return e instanceof Error?e:Error(String(e))}async function nP(e,t,n){return await JN(e,t,n.name,n.version)||ZN(t,n.name,n.version)}async function rP(e,t,n){let r=await nP(e,t,n),i=await g_(t,{url:r.url,sha256:r.sha256,label:`di: download ${r.name}==${r.version}`});await e.mkdir(QN,{recursive:!0});let a=it(QN,r.fileName),o=!0;if(await e.exists(a)){let t=await u_(await e.readFile(a,{encoding:`binary`}));if(t===r.sha256.toLowerCase())o=!1;else throw Error(`di: ${r.fileName} is already staged with different bytes (sha256 ${t} != ${r.sha256.toLowerCase()}); refusing to overwrite`)}else await e.writeFile(a,i);return{name:r.name,version:r.version,source:r.source,fileName:r.fileName,sha256:r.sha256,staged:o}}async function iP(e,t,n,r){let i=await w_(e,n),a=[],o=[];for(let n of r){let r;try{r=eP(n)}catch(e){o.push({spec:n,error:tP(e)});continue}try{a.push(await rP(e,t,r))}catch(e){o.push({spec:n,error:tP(e)})}}if(a.length>0){let t=await B_(e,i),n=t.dependencies,r=await H_(e,i);for(let e of a)n=R_(n,e.name,e.version),r=z_(r,{name:e.name,version:e.version,source:e.source,fileName:e.fileName,sha256:e.sha256});await V_(e,i,{...t,dependencies:n}),await U_(e,i,r)}return{results:a,errors:o,manifestDir:i}}async function aP(e,t){let n=await C_(e,t);if(!n)return null;let r=await B_(e,n),i=await H_(e,n),a=new Map(i.map(e=>[b_(e.name),e]));return r.dependencies.map(e=>{let{name:t,version:n}=S_(e),r=a.get(b_(t));return{name:t,version:n||r?.version||`?`,source:r?.source??`unknown`}})}function oP(e){return`${e} - minimal Python package manager (pure-Python + Pyodide wheels)
|
|
6009
6009
|
|
|
6010
6010
|
Usage:
|
|
6011
6011
|
${e} add <pkg>[@<version>] [<pkg> ...] resolve, stage, and record wheels
|
|
@@ -6018,27 +6018,27 @@ Resolution:
|
|
|
6018
6018
|
staged under /workspace/python_wheels/ and recorded in pyproject.toml + uv.lock.
|
|
6019
6019
|
|
|
6020
6020
|
Anything else is not implemented in SLICC's ${e} subset; use real uv locally.
|
|
6021
|
-
`}function
|
|
6022
|
-
`)}\n`}async function
|
|
6021
|
+
`}function sP(e,t){return{stdout:``,stderr:`${e}: '${t}' is not implemented in SLICC's di/uv subset; use real uv locally. Run '${e} --help' for supported verbs.\n`,exitCode:1}}function cP(e){return e instanceof Error?e.message:String(e)}function lP(e){let t=Math.max(4,...e.map(e=>e.name.length)),n=Math.max(7,...e.map(e=>e.version.length));return`${e.map(e=>`${e.name.padEnd(t)} ${e.version.padEnd(n)} (${e.source})`).join(`
|
|
6022
|
+
`)}\n`}async function uP(e,t,n,r){let i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return{stdout:``,stderr:`${e}: add requires at least one package\n`,exitCode:1};let a;try{a=await iP(r.fs,r.fetch,n.cwd,i)}catch(t){return{stdout:``,stderr:`${e}: ${cP(t)}\n`,exitCode:1}}let o=a.results.map(t=>t.staged?`${e}: added ${t.name}==${t.version} (${t.source}) -> ${t.fileName}`:`${e}: ${t.name}==${t.version} already staged (${t.source})`),s=a.errors.map(t=>`${e}: failed to add ${t.spec}: ${cP(t.error)}`);return{stdout:o.length>0?`${o.join(`
|
|
6023
6023
|
`)}\n`:``,stderr:s.length>0?`${s.join(`
|
|
6024
|
-
`)}\n`:``,exitCode:a.errors.length===0?0:1}}async function
|
|
6024
|
+
`)}\n`:``,exitCode:a.errors.length===0?0:1}}async function dP(e,t,n){let r=await aP(n.fs,t.cwd);return r===null?{stdout:``,stderr:`${e}: no pyproject.toml found (run '${e} add <pkg>' first)\n`,exitCode:0}:r.length===0?{stdout:`${e}: no dependencies recorded\n`,stderr:``,exitCode:0}:{stdout:lP(r),stderr:``,exitCode:0}}function fP(e,t){return G(e,async(n,r)=>{if(n.length===0)return{stdout:oP(e),stderr:`${e}: missing verb\n`,exitCode:1};if(n[0]===`--help`||n[0]===`-h`)return{stdout:oP(e),stderr:``,exitCode:0};let i=n[0],a=n.slice(1);return i===`add`?uP(e,a,r,t):i===`list`?dP(e,r,t):sP(e,i)})}const pP=[`A`,`AAAA`,`MX`,`TXT`,`CNAME`,`NS`,`SOA`,`SRV`,`PTR`,`CAA`],mP={1:`A`,2:`NS`,5:`CNAME`,6:`SOA`,12:`PTR`,15:`MX`,16:`TXT`,28:`AAAA`,33:`SRV`,257:`CAA`},hP={0:`NOERROR`,1:`FORMERR`,2:`SERVFAIL`,3:`NXDOMAIN`,4:`NOTIMP`,5:`REFUSED`};function gP(){return{stdout:`usage: dig <name> [type] [+short] [--json]
|
|
6025
6025
|
|
|
6026
6026
|
Resolve DNS records via Cloudflare DNS-over-HTTPS.
|
|
6027
6027
|
|
|
6028
|
-
Supported types: `+
|
|
6028
|
+
Supported types: `+pP.join(`, `)+` (default: A).
|
|
6029
6029
|
|
|
6030
6030
|
Flags:
|
|
6031
6031
|
+short one answer value per line, no headers
|
|
6032
6032
|
--json raw resolver JSON (pretty-printed)
|
|
6033
6033
|
-h, --help show this help
|
|
6034
|
-
`,stderr:``,exitCode:0}}function
|
|
6034
|
+
`,stderr:``,exitCode:0}}function _P(e){return mP[e]??`TYPE${e}`}function vP(){let e=l();return G(`dig`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return gP();let n=!1,r=!1,i=[];for(let e of t)if(e===`+short`)n=!0;else if(e===`--json`)r=!0;else if(e.startsWith(`--`))return{stdout:``,stderr:`dig: unknown option: ${e}\n`,exitCode:1};else if(e.startsWith(`+`))return{stdout:``,stderr:`dig: unknown option: ${e}\n`,exitCode:1};else i.push(e);if(n&&r)return{stdout:``,stderr:`dig: +short and --json are mutually exclusive
|
|
6035
6035
|
`,exitCode:1};let a=i[0]?.trim();if(!a)return{stdout:``,stderr:`dig: missing domain name
|
|
6036
6036
|
usage: dig <name> [type] [+short] [--json]
|
|
6037
|
-
`,exitCode:1};let o=i[1]?.trim().toUpperCase()??`A`;if(!
|
|
6038
|
-
`,exitCode:1}}if(typeof u.Status==`number`&&u.Status!==0)return{stdout:``,stderr:`dig: ${a}: ${
|
|
6037
|
+
`,exitCode:1};let o=i[1]?.trim().toUpperCase()??`A`;if(!pP.includes(o))return{stdout:``,stderr:`dig: unsupported record type: ${o}\n`,exitCode:1};let s=`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(a)}&type=${o}`,c;try{c=await e(s,{method:`GET`,headers:{Accept:`application/dns-json`}})}catch(e){return{stdout:``,stderr:`dig: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}if(c.status<200||c.status>=300)return{stdout:``,stderr:`dig: lookup failed: ${c.status} ${c.statusText}\n`,exitCode:1};let l=new TextDecoder(`utf-8`).decode(c.body),u;try{u=JSON.parse(l)}catch{return{stdout:``,stderr:`dig: invalid response from resolver
|
|
6038
|
+
`,exitCode:1}}if(typeof u.Status==`number`&&u.Status!==0)return{stdout:``,stderr:`dig: ${a}: ${hP[u.Status]??String(u.Status)}\n`,exitCode:1};if(r)return{stdout:`${JSON.stringify(u,null,2)}\n`,stderr:``,exitCode:0};let d=u.Answer??[];return d.length===0?n?{stdout:``,stderr:``,exitCode:0}:{stdout:`;; no records found
|
|
6039
6039
|
`,stderr:``,exitCode:0}:n?{stdout:`${d.map(e=>e.data).join(`
|
|
6040
|
-
`)}\n`,stderr:``,exitCode:0}:{stdout:`${d.map(e=>`${e.name}\t${e.TTL??0}\tIN\t${
|
|
6041
|
-
`)}\n`,stderr:``,exitCode:0}})}const
|
|
6040
|
+
`)}\n`,stderr:``,exitCode:0}:{stdout:`${d.map(e=>`${e.name}\t${e.TTL??0}\tIN\t${_P(e.type)}\t${e.data}`).join(`
|
|
6041
|
+
`)}\n`,stderr:``,exitCode:0}})}const yP=[`api-catalog`,`service-desc`,`service-meta`,`status`,`https://llmstxt.org/rel/llms-txt`];async function bP(e,t={}){let n=t.fetchImpl??fetch,r=t.timeoutMs??3e3,i={links:e,failures:[]},a=[],o=new Set;for(let s of e)for(let e of s.rel)yP.includes(e)&&(o.has(e)||(o.add(e),a.push(xP(n,s.href,r,t.signal).then(t=>SP(i,e,t)).catch(t=>{i.failures.push({rel:e,href:s.href,error:t instanceof Error?t.message:String(t)})}))));return await Promise.all(a),i}async function xP(e,t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(Error(`timeout`)),n),o=()=>i.abort(Error(`aborted`));r&&r.addEventListener(`abort`,o,{once:!0});try{let n=await e(t,{signal:i.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);return{contentType:n.headers.get(`content-type`)??``,body:await n.text()}}finally{clearTimeout(a),r&&r.removeEventListener(`abort`,o)}}function SP(e,t,n){if(t===`https://llmstxt.org/rel/llms-txt`){e.llmsTxt=n.body;return}let r=n.contentType.includes(`json`)||n.contentType.includes(`linkset`),i=n.body;if(r)try{i=JSON.parse(n.body)}catch{i=n.body}switch(t){case`api-catalog`:e.catalog=i;break;case`service-desc`:e.serviceDesc=i;break;case`service-meta`:e.serviceMeta=i;break;case`status`:e.status=i;break}}function CP(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=h(n?.headers),a=await e(r,{method:n?.method??`GET`,...i?{headers:i}:{}});return new Response(a.body,{status:a.status,statusText:a.statusText,headers:a.headers})}}function wP(){return`discover — fetch a URL and parse RFC 8288 Link headers
|
|
6042
6042
|
|
|
6043
6043
|
Usage:
|
|
6044
6044
|
discover <url> Print parsed links (and any SLICC handoff match)
|
|
@@ -6052,9 +6052,9 @@ Output is always JSON.
|
|
|
6052
6052
|
Examples:
|
|
6053
6053
|
discover ${g}/handoff?handoff=demo
|
|
6054
6054
|
discover --follow ${g}/llms.txt
|
|
6055
|
-
`}function
|
|
6056
|
-
`,exitCode:2};let r=n[0],i=l(),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=Je(o,r),c=Qe(s),u={url:r,status:a.status,links:s,handoff:c};if(t&&s.length>0){let e=await
|
|
6057
|
-
`,stderr:``,exitCode:0}})}function
|
|
6055
|
+
`}function TP(){return G(`discover`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return{stdout:wP(),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
|
|
6056
|
+
`,exitCode:2};let r=n[0],i=l(),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=Je(o,r),c=Qe(s),u={url:r,status:a.status,links:s,handoff:c};if(t&&s.length>0){let e=await bP(s,{fetchImpl:CP(i)});u.discovery={catalog:e.catalog,serviceDesc:e.serviceDesc,serviceMeta:e.serviceMeta,status:e.status,llmsTxt:e.llmsTxt,failures:e.failures}}return{stdout:JSON.stringify(u,null,2)+`
|
|
6057
|
+
`,stderr:``,exitCode:0}})}function EP(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 DP=`esbuild - thin wrapper over the ipk-loaded esbuild-wasm
|
|
6058
6058
|
|
|
6059
6059
|
Usage:
|
|
6060
6060
|
esbuild [options] <entry> Bundle / transform
|
|
@@ -6084,10 +6084,10 @@ Install:
|
|
|
6084
6084
|
Inert until the backing package is installed:
|
|
6085
6085
|
ipk add esbuild-wasm
|
|
6086
6086
|
Then \`esbuild --version\` and the bundle/transform commands above.
|
|
6087
|
-
`,
|
|
6088
|
-
`,exitCode:2};let r;try{r=await
|
|
6089
|
-
`,exitCode:2};let r=e.entries.map(e=>t.fs.resolvePath(t.cwd,e));for(let e of r)if(!await t.fs.exists(e))return{stdout:``,stderr:`esbuild: ${e}: no such file\n`,exitCode:1};let i={entryPoints:r,bundle:!0,write:!1,plugins:[
|
|
6090
|
-
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=dn(n);for(let e=1;e<o.length;e++){let n=o[e],i=pn(r,mn(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await
|
|
6087
|
+
`,OP=new Set([`iife`,`cjs`,`esm`]),kP=new Set([`linked`,`inline`,`external`,`both`]),AP={"-h":`showHelp`,"--help":`showHelp`,"-v":`showVersion`,"--version":`showVersion`,"--bundle":`bundle`,"--transform":`transform`,"--minify":`minify`};function jP(e){if(e.startsWith(`--`)){let t=e.indexOf(`=`);if(t>0)return{key:e.slice(0,t),inlineValue:e.slice(t+1)}}return{key:e,inlineValue:null}}function MP(e,t,n){if(e.inlineValue!==null)return{value:e.inlineValue,advance:0};let r=t[n+1];if(typeof r!=`string`||r.startsWith(`-`))throw Error(`esbuild: ${e.key} requires a value`);return{value:r,advance:1}}function NP(e,t,n,r){if(t.inlineValue!==null){if(!kP.has(t.inlineValue))throw Error(`esbuild: --sourcemap value must be one of linked|inline|external|both (got "${t.inlineValue}")`);return e.sourcemap=t.inlineValue,0}let i=n[r+1];return typeof i==`string`&&kP.has(i)?(e.sourcemap=i,1):(e.sourcemap=!0,0)}function PP(e,t,n,r){if(t.key===`--outfile`){let{value:i,advance:a}=MP(t,n,r);return e.outfile=i,a}if(t.key===`--format`){let{value:i,advance:a}=MP(t,n,r);if(!OP.has(i))throw Error(`esbuild: --format must be one of iife|cjs|esm (got "${i}")`);return e.format=i,a}if(t.key===`--target`){let{value:i,advance:a}=MP(t,n,r);return e.target=i.split(`,`).map(e=>e.trim()).filter(Boolean),a}if(t.key===`--loader`){let{value:i,advance:a}=MP(t,n,r);return e.loader=i,a}return-1}function FP(e){let t={entries:[],bundle:!1,transform:!1,outfile:null,format:null,minify:!1,sourcemap:null,target:null,loader:null,showHelp:!1,showVersion:!1};for(let n=0;n<e.length;n++){let r=e[n],i=AP[r];if(i){t[i]=!0;continue}let a=jP(r);if(a.key===`--sourcemap`){n+=NP(t,a,e,n);continue}let o=PP(t,a,e,n);if(o>=0){n+=o;continue}if(r.startsWith(`-`))throw Error(`esbuild: unknown option: ${r}`);t.entries.push(r)}return t}function IP(e,t,n){return{name:`slicc-vfs`,setup(r){r.onResolve({filter:/.*/},async r=>{if(/^[a-z]+:/.test(r.path)&&!r.path.startsWith(`file:`))return{path:r.path,external:!0};if(r.path.startsWith(`./`)||r.path.startsWith(`../`)||r.path.startsWith(`/`)){let n=r.importer?.startsWith(`/`)?dn(r.importer):t;return{path:await RP(e,e.resolvePath(n,r.path))}}let i=r.importer?.startsWith(`/`)?dn(r.importer):n.fromDir;try{let e=await tn(r.path,i,n.reader);return e.type===`file`?{path:e.path}:{path:r.path,external:!0}}catch(e){return{errors:[{text:e instanceof Error?e.message:String(e)}]}}}),r.onLoad({filter:/.*/},async t=>t.namespace&&t.namespace!==`file`?null:{contents:await e.readFile(t.path),loader:LP(t.path),resolveDir:dn(t.path)})}}}function LP(e){let t=mn(e).toLowerCase(),n=t.lastIndexOf(`.`);if(n<0)return`js`;switch(t.slice(n+1)){case`ts`:return`ts`;case`tsx`:return`tsx`;case`jsx`:return`jsx`;case`mjs`:case`cjs`:case`js`:return`js`;case`json`:return`json`;case`css`:return`css`;case`txt`:return`text`;default:return`js`}}async function RP(e,t){if(await e.exists(t))try{if(!(await e.stat(t)).isDirectory)return t}catch{return t}let n=[`.ts`,`.tsx`,`.jsx`,`.mjs`,`.cjs`,`.js`,`.json`];for(let r of n){let n=`${t}${r}`;if(await e.exists(n))return n}for(let r of n){let n=pn(t,`index${r}`);if(await e.exists(n))return n}return t}async function zP(e,t,n){let r=[];if(n.length>0){let t=await e(n,{kind:`warning`,color:!1});r.push(t.join(``))}if(t.length>0){let n=await e(t,{kind:`error`,color:!1});r.push(n.join(``))}return r.join(``)}function BP(){return G(`esbuild`,async(e,t)=>{let n;try{n=FP(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}if(n.showHelp||e.length===0&&!t.stdin)return{stdout:DP,stderr:``,exitCode:0};if(!n.transform&&!n.bundle&&n.entries.length>1)return{stdout:``,stderr:`esbuild: multiple entry points require --bundle (transform mode accepts at most one entry)
|
|
6088
|
+
`,exitCode:2};let r;try{r=await SE({ipk:EP(t)})}catch(e){return{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return n.showVersion?{stdout:`${r.version}\n`,stderr:``,exitCode:0}:n.transform||!n.bundle&&n.entries.length<=1?VP(n,t,r):HP(n,t,r)})}async function VP(e,t,n){let r,i=`<stdin>`;if(e.entries.length===1){let n=t.fs.resolvePath(t.cwd,e.entries[0]);if(!await t.fs.exists(n))return{stdout:``,stderr:`esbuild: ${e.entries[0]}: no such file\n`,exitCode:1};r=await t.fs.readFile(n),i=n}else if(r=Pk(t.stdin),!r)return{stdout:DP,stderr:``,exitCode:0};let a={loader:e.loader??LP(i),sourcefile:i,...e.format?{format:e.format}:{},...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{}};try{let i=await n.transform(r,a),o=await zP(n.formatMessages,[],i.warnings);if(e.outfile){let n=t.fs.resolvePath(t.cwd,e.outfile);return await t.fs.writeFile(n,i.code),i.map&&e.sourcemap&&e.sourcemap!==`inline`&&await t.fs.writeFile(`${n}.map`,i.map),{stdout:``,stderr:o,exitCode:0}}return{stdout:i.code,stderr:o,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await zP(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function HP(e,t,n){if(e.entries.length===0)return{stdout:``,stderr:`esbuild: --bundle requires at least one entry point
|
|
6089
|
+
`,exitCode:2};let r=e.entries.map(e=>t.fs.resolvePath(t.cwd,e));for(let e of r)if(!await t.fs.exists(e))return{stdout:``,stderr:`esbuild: ${e}: no such file\n`,exitCode:1};let i={entryPoints:r,bundle:!0,write:!1,plugins:[IP(t.fs,t.cwd,EP(t))],format:e.format??`esm`,...e.minify?{minify:!0}:{},...e.sourcemap?{sourcemap:e.sourcemap}:{},...e.target?{target:e.target}:{}};try{let r=await n.build(i),a=await zP(n.formatMessages,r.errors,r.warnings),o=r.outputFiles??[];if(e.outfile){if(o.length===0)return{stdout:``,stderr:`esbuild: build produced no output
|
|
6090
|
+
`,exitCode:1};let n=t.fs.resolvePath(t.cwd,e.outfile);await t.fs.writeFile(n,o[0].text);let r=dn(n);for(let e=1;e<o.length;e++){let n=o[e],i=pn(r,mn(n.path));await t.fs.writeFile(i,n.text)}return{stdout:``,stderr:a,exitCode:0}}return{stdout:o.map(e=>e.text).join(``),stderr:a,exitCode:0}}catch(e){let t=e;return Array.isArray(t.errors)?{stdout:``,stderr:await zP(n.formatMessages,t.errors,t.warnings??[]),exitCode:1}:{stdout:``,stderr:`esbuild: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function UP(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var WP=class{ops(){return import(`./esptool-operations-C0DUkD34.js`)}registry(){if(!jD())throw Error(`Web Serial is unavailable in this browser`);return PD()}async chipInfo(e,t,n){return(await this.ops()).esptoolChipInfo(this.registry(),e,t,n)}async readMac(e,t,n){return(await this.ops()).esptoolReadMac(this.registry(),e,t,n)}async eraseFlash(e,t,n){await(await this.ops()).esptoolEraseFlash(this.registry(),e,t,n)}async flash(e,t,n,r,i){await(await this.ops()).esptoolFlash(this.registry(),e,t,n,r,i)}async readFlash(e,t,n,r,i){return(await this.ops()).esptoolReadFlash(this.registry(),e,t,n,r,i)}async readReg(e,t,n,r){return(await this.ops()).esptoolReadReg(this.registry(),e,t,n,r)}async flashId(e,t,n){return(await this.ops()).esptoolFlashId(this.registry(),e,t,n)}async eraseRegion(e,t,n,r,i){await(await this.ops()).esptoolEraseRegion(this.registry(),e,t,n,r,i)}async run(e,t,n){await(await this.ops()).esptoolRun(this.registry(),e,t,n)}},GP=class e{rpc;constructor(e){this.rpc=e}static INFO_TIMEOUT_MS=12e4;static ERASE_TIMEOUT_MS=3e5;static FLASH_TIMEOUT_MS=6e5;async withProgress(e,t,n){let r=this.rpc.onEvent(`esptool-progress`,n=>{let r=n;!r||r.handle!==e||t(r.line)});try{return await n()}finally{r()}}async chipInfo(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-chip-info`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async readMac(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-read-mac`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseFlash(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-erase-flash`,{handle:t,baudRate:n},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async flash(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-flash`,{handle:t,baudRate:n,eraseAll:r,segments:i.map(e=>({address:e.address,bytes:UP(e.data)}))},{timeoutMs:e.FLASH_TIMEOUT_MS}))}async readFlash(t,n,r,i,a){let{bytes:o}=await this.withProgress(t,a,()=>this.rpc.call(`esptool-read-flash`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.FLASH_TIMEOUT_MS}));return new Uint8Array(o)}async readReg(t,n,r,i){return this.withProgress(t,i,()=>this.rpc.call(`esptool-read-reg`,{handle:t,baudRate:n,address:r},{timeoutMs:e.INFO_TIMEOUT_MS}))}async flashId(t,n,r){return this.withProgress(t,r,()=>this.rpc.call(`esptool-flash-id`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}async eraseRegion(t,n,r,i,a){await this.withProgress(t,a,()=>this.rpc.call(`esptool-erase-region`,{handle:t,baudRate:n,address:r,size:i},{timeoutMs:e.ERASE_TIMEOUT_MS}))}async run(t,n,r){await this.withProgress(t,r,()=>this.rpc.call(`esptool-run`,{handle:t,baudRate:n},{timeoutMs:e.INFO_TIMEOUT_MS}))}};function KP(e,t){return e&&jD()?new WP:t?new GP(t):null}const qP=new Set([`--vid`,`--pid`,`--baud`,`--data-bits`,`--stop-bits`,`--parity`,`--flow-control`,`--buffer-size`,`--bytes`,`--until`,`--timeout-ms`,`--dtr`,`--rts`,`--break`,`--__resolved`]);function JP(e){return wm(e,qP)}function YP(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 XP(e){let t=e.replace(/0x/gi,``).replace(/[\s:,]/g,``);if(t.length===0)return new Uint8Array;if(t.length%2!=0||/[^0-9a-f]/i.test(t))throw Error(`invalid hex string: '${e}'`);let n=new Uint8Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}function ZP(e){let t={};return e.has(`--vid`)&&(t.usbVendorId=YP(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.usbProductId=YP(e.get(`--pid`),`pid`)),Object.keys(t).length>0?[t]:[]}const QP=new Set([`none`,`even`,`odd`]),$P=new Set([`none`,`hardware`]);function eF(e){let t={baudRate:e.has(`--baud`)?YP(e.get(`--baud`),`baud`):9600};if(e.has(`--data-bits`)&&(t.dataBits=YP(e.get(`--data-bits`),`data-bits`)),e.has(`--stop-bits`)&&(t.stopBits=YP(e.get(`--stop-bits`),`stop-bits`)),e.has(`--parity`)){let n=e.get(`--parity`);if(!QP.has(n))throw Error(`invalid --parity: '${n}'`);t.parity=n}if(e.has(`--flow-control`)){let n=e.get(`--flow-control`);if(!$P.has(n))throw Error(`invalid --flow-control: '${n}'`);t.flowControl=n}return e.has(`--buffer-size`)&&(t.bufferSize=YP(e.get(`--buffer-size`),`buffer-size`)),t}function tF(e){let t={};return e.has(`--bytes`)&&(t.maxBytes=YP(e.get(`--bytes`),`bytes`)),e.has(`--until`)&&(t.until=XP(e.get(`--until`))),e.has(`--timeout-ms`)&&(t.timeoutMs=YP(e.get(`--timeout-ms`),`timeout-ms`)),t}function nF(e,t){let n=e.toLowerCase();if(n===`on`||n===`true`||n===`1`)return!0;if(n===`off`||n===`false`||n===`0`)return!1;throw Error(`invalid ${t}: '${e}' (use on/off)`)}function rF(e){let t={};return e.has(`--dtr`)&&(t.dataTerminalReady=nF(e.get(`--dtr`),`dtr`)),e.has(`--rts`)&&(t.requestToSend=nF(e.get(`--rts`),`rts`)),e.has(`--break`)&&(t.break=nF(e.get(`--break`),`break`)),t}function iF(e){let t=Fk(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function aF(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function oF(e){return`0x${e.toString(16).padStart(4,`0`)}`}function sF(e){let t=e.usbVendorId!==void 0||e.usbProductId!==void 0?`${oF(e.usbVendorId??0)}:${oF(e.usbProductId??0)}`:`(native serial)`,n=e.opened?` [open]`:``;return`${e.handle}\t${t}${n}`}function cF(e){return`cts=${+!!e.clearToSend} dcd=${+!!e.dataCarrierDetect} dsr=${+!!e.dataSetReady} ri=${+!!e.ringIndicator}\n`}function lF(e){return{stdout:e,stderr:``,exitCode:0}}function uF(e){return{stdout:``,stderr:`serial: ${e}\n`,exitCode:1}}const dF=`serial - access serial ports via Web Serial
|
|
6091
6091
|
|
|
6092
6092
|
Usage: serial <subcommand> [options]
|
|
6093
6093
|
|
|
@@ -6106,7 +6106,7 @@ Open flags:
|
|
|
6106
6106
|
--parity none|even|odd --flow-control none|hardware --buffer-size N
|
|
6107
6107
|
|
|
6108
6108
|
Read flags:
|
|
6109
|
-
--bytes N Stop after N bytes (default: ${
|
|
6109
|
+
--bytes N Stop after N bytes (default: ${FD} cap)
|
|
6110
6110
|
--until <hex> Stop once this byte sequence is seen
|
|
6111
6111
|
--timeout-ms N Stop after N ms (default 1000)
|
|
6112
6112
|
--hex Hex-dump the bytes instead of emitting raw
|
|
@@ -6117,10 +6117,10 @@ Signal flags (set):
|
|
|
6117
6117
|
Options:
|
|
6118
6118
|
-h, --help
|
|
6119
6119
|
|
|
6120
|
-
Reads/writes are capped at ${
|
|
6121
|
-
`;function
|
|
6122
|
-
`):
|
|
6123
|
-
`)}\n`)}async function
|
|
6120
|
+
Reads/writes are capped at ${FD} bytes (4 MiB).
|
|
6121
|
+
`;function fF(e,t){if(t)return lF(e.length?`${aF(e)}\n`:``);let n=``;for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return lF(n)}async function pF(e){let t=await e.list();return t.length===0?lF(`no granted serial ports
|
|
6122
|
+
`):lF(`${t.map(sF).join(`
|
|
6123
|
+
`)}\n`)}async function mF(e,t){let n=e.get(`--__resolved`);if(n)return lF(`${sF(await t.info(n))}\n`);let r=ZP(e),i=re();if(i){let e=await I(`serial-port`,r,i);if(e.handle)return lF(`${sF(await t.info(e.handle))}\n`);let n=e.info,a=jD();if(!a)return uF(`request: Web Serial unavailable for port re-acquire`);let o=(await a.getPorts()).find(e=>{let t=typeof e.getInfo==`function`?e.getInfo():{};return(n.usbVendorId===void 0||t.usbVendorId===n.usbVendorId)&&(n.usbProductId===void 0||t.usbProductId===n.usbProductId)});if(!o)return uF(`request: granted port could not be re-acquired`);let s=PD(),c=s.register(o),l=s.get(c);return l?lF(`${sF(ID(c,l))}\n`):uF(`request: failed to register granted port`)}return lF(`${sF(await t.request(r))}\n`)}async function hF(e,t,n){let r=e[1];return r?(await n.open(r,eF(t)),lF(``)):uF(`open: handle required`)}async function gF(e,t){let n=e[1];return n?(await t.close(n),lF(``)):uF(`close: handle required`)}async function _F(e,t,n,r){let i=e[1];if(!i)return uF(`read: handle required`);let a=tF(t);return a.maxBytes!==void 0&&a.maxBytes>4194304?uF(`read --bytes exceeds 4 MiB limit`):fF(await r.read(i,a),n.has(`--hex`))}async function vF(e,t,n){let r=e[1];if(!r)return uF(`write: handle required`);let i=iF(t);return i.length>4194304?uF(`write payload exceeds 4 MiB limit`):lF(`${await n.write(r,i)} bytes written\n`)}async function yF(e,t,n){let[,r,i]=e;return!r||!i?uF(`signals: handle and get|set required`):i===`get`?lF(cF(await n.getSignals(r))):i===`set`?(await n.setSignals(r,rF(t)),lF(``)):uF(`signals: unknown action '${i}' (use get|set)`)}async function bF(e,t,n){let{positionals:r,flags:i,bools:a}=JP(e),o=r[0];switch(o){case`list`:return pF(n);case`request`:return mF(i,n);case`open`:return hF(r,i,n);case`close`:return gF(r,n);case`read`:return _F(r,i,a,n);case`write`:return vF(r,t,n);case`signals`:return yF(r,i,n);default:return uF(`unknown subcommand '${o??``}'. Try 'serial --help'.`)}}function xF(){return G(`serial`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return lF(dF);let n=rO(Ue(),He());if(!n)return uF(`Web Serial is unavailable in this environment`);try{return await bF(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No port selected/i.test(t)?uF(`user cancelled or no port selected`):uF(t)}})}const SF=new Set([`--port`,`--baud`,`--vid`,`--pid`]),CF=115200;function wF(e){return wm(e,SF)}function TF(e){let t=e.replace(/-/g,`_`);return t===`chip_info`||t===`id`?`chip_id`:t}function EF(e){return{stdout:e,stderr:``,exitCode:0}}function DF(e){return{stdout:``,stderr:`esptool: ${e}\n`,exitCode:1}}const OF=`esptool - flash ESP32 / ESP8266 chips via esptool-js
|
|
6124
6124
|
|
|
6125
6125
|
Usage: esptool [--port H] [--baud N] <subcommand> [args]
|
|
6126
6126
|
|
|
@@ -6137,27 +6137,27 @@ Subcommands:
|
|
|
6137
6137
|
|
|
6138
6138
|
Options:
|
|
6139
6139
|
--port H Use an existing serial handle from 'serial request'
|
|
6140
|
-
--baud N Flash baud rate (default ${
|
|
6140
|
+
--baud N Flash baud rate (default ${CF})
|
|
6141
6141
|
--vid 0x.. Picker filter when --port is omitted
|
|
6142
6142
|
--pid 0x.. Picker filter when --port is omitted
|
|
6143
6143
|
--erase write_flash: erase the whole chip before writing
|
|
6144
6144
|
-h, --help
|
|
6145
6145
|
|
|
6146
6146
|
Without --port, the Web Serial picker opens (needs a user gesture).
|
|
6147
|
-
`;async function
|
|
6148
|
-
`)}\n`)}case`read_mac`:{let e=await
|
|
6149
|
-
`)}\n`)}case`erase_flash`:{let e=await
|
|
6147
|
+
`;async function kF(e,t){return e.get(`--port`)||(await t.request(ZP(e))).handle}async function AF(e,t){let n=e.slice(1);if(n.length===0||n.length%2!=0)throw Error(`write_flash expects <addr> <file> pairs`);let r=[];for(let e=0;e<n.length;e+=2){let i=YP(n[e],`address`),a=t.fs.resolvePath(t.cwd,n[e+1]),o=await t.fs.readFileBuffer(a);r.push({address:i,data:o})}return r}async function jF(e,t,n,r){let{positionals:i,flags:a,bools:o}=wF(e),s=TF(i[0]??``),c=a.has(`--baud`)?YP(a.get(`--baud`),`baud`):CF,l=[],u=e=>l.push(e);switch(s){case`chip_id`:{let e=await kF(a,r),t=await n.chipInfo(e,c,u);return l.push(`Chip type: ${t.chip}`),l.push(`Chip description: ${t.description}`),l.push(`Features: ${t.features.join(`, `)}`),l.push(`Crystal: ${t.crystalMHz}MHz`),l.push(`MAC: ${t.mac}`),EF(`${l.join(`
|
|
6148
|
+
`)}\n`)}case`read_mac`:{let e=await kF(a,r),{mac:t}=await n.readMac(e,c,u);return l.push(`MAC: ${t}`),EF(`${l.join(`
|
|
6149
|
+
`)}\n`)}case`erase_flash`:{let e=await kF(a,r);return await n.eraseFlash(e,c,u),EF(l.length?`${l.join(`
|
|
6150
6150
|
`)}\n`:`flash erased
|
|
6151
|
-
`)}case`write_flash`:{let e=await
|
|
6151
|
+
`)}case`write_flash`:{let e=await AF(i,t),s=await kF(a,r);return await n.flash(s,c,o.has(`--erase`),e,u),EF(l.length?`${l.join(`
|
|
6152
6152
|
`)}\n`:`flash written
|
|
6153
|
-
`)}case`read_flash`:{if(i.length<4)return
|
|
6154
|
-
`)}\n`)}case`read_reg`:{if(i.length<2)return
|
|
6155
|
-
`)}\n`)}case`flash_id`:{let e=await
|
|
6156
|
-
`)}\n`)}case`erase_region`:{if(i.length<3)return
|
|
6153
|
+
`)}case`read_flash`:{if(i.length<4)return DF(`read_flash expects <addr> <size> <outfile>`);let e=YP(i[1],`address`),o=YP(i[2],`size`),s=t.fs.resolvePath(t.cwd,i[3]),d=await kF(a,r),f=await n.readFlash(d,c,e,o,u);return await t.fs.writeFile(s,f),l.push(`Wrote ${f.byteLength} bytes to ${s}`),EF(`${l.join(`
|
|
6154
|
+
`)}\n`)}case`read_reg`:{if(i.length<2)return DF(`read_reg expects <addr>`);let e=YP(i[1],`address`),t=await kF(a,r),{value:o}=await n.readReg(t,c,e,u);return l.push(`0x${e.toString(16)} = 0x${(o>>>0).toString(16).padStart(8,`0`)}`),EF(`${l.join(`
|
|
6155
|
+
`)}\n`)}case`flash_id`:{let e=await kF(a,r),t=await n.flashId(e,c,u);return l.push(`Manufacturer: 0x${t.manufacturer.toString(16).padStart(2,`0`)}`),l.push(`Device: 0x${t.device.toString(16).padStart(4,`0`)}`),l.push(`Detected flash size: ${t.flashSize??`unknown`}`),EF(`${l.join(`
|
|
6156
|
+
`)}\n`)}case`erase_region`:{if(i.length<3)return DF(`erase_region expects <addr> <size>`);let e=YP(i[1],`address`),t=YP(i[2],`size`),o=await kF(a,r);return await n.eraseRegion(o,c,e,t,u),EF(l.length?`${l.join(`
|
|
6157
6157
|
`)}\n`:`region erased
|
|
6158
|
-
`)}case`run`:{let e=await
|
|
6158
|
+
`)}case`run`:{let e=await kF(a,r);return await n.run(e,c,u),EF(l.length?`${l.join(`
|
|
6159
6159
|
`)}\n`:`running app
|
|
6160
|
-
`)}default:return
|
|
6160
|
+
`)}default:return DF(`unknown subcommand '${i[0]??``}'. Try 'esptool --help'.`)}}function MF(){return G(`esptool`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return EF(OF);let n=Ue(),r=He(),i=KP(n,r),a=rO(n,r);if(!i||!a)return DF(`Web Serial is unavailable in this environment`);try{return await jF(e,t,i,a)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No port selected/i.test(t)?DF(`user cancelled or no port selected`):DF(t)}})}function NF(){return ue()}function PF(e){return{bytes:RF(e.bytesBase64),mimeType:e.mimeType??`application/octet-stream`,width:e.width??0,height:e.height??0,...typeof e.durationMs==`number`?{durationMs:e.durationMs}:{}}}async function FF(e,t={}){if(!ue())throw Error(`media capture popup requires the extension runtime`);let n=t.timeoutMs??5*6e4,r=IF(),i=LF(JSON.stringify({...e,requestId:r})),a=chrome.runtime.getURL(`capture-popup.html?req=${i}`);return await new Promise((e,t)=>{let i=!1,o=()=>{if(!i){i=!0,clearTimeout(c);try{chrome.runtime.onMessage.removeListener(s)}catch{}}},s=n=>{let i=n;if(!(i?.source!==`capture-popup`||i.requestId!==r))if(o(),i.ok&&i.bytesBase64!==void 0)try{e(PF(i))}catch(e){t(e instanceof Error?e:Error(String(e)))}else t(Error(i.error||`media capture failed`))},c=setTimeout(()=>{try{chrome.runtime.sendMessage({target:`capture-popup`,type:`capture-abort`,requestId:r})}catch{}o(),t(Error(`media capture timed out waiting for the capture window`))},n);chrome.runtime.onMessage.addListener(s);try{chrome.runtime.sendMessage({type:`capture-open-window`,url:a,requestId:r})}catch(e){o(),t(e instanceof Error?e:Error(String(e)))}})}function IF(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cap-${crypto.randomUUID()}`:`cap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function LF(e){let t=new TextEncoder().encode(e),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function RF(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 zF;(function(e){e.LOAD=`LOAD`,e.EXEC=`EXEC`,e.FFPROBE=`FFPROBE`,e.WRITE_FILE=`WRITE_FILE`,e.READ_FILE=`READ_FILE`,e.DELETE_FILE=`DELETE_FILE`,e.RENAME=`RENAME`,e.CREATE_DIR=`CREATE_DIR`,e.LIST_DIR=`LIST_DIR`,e.DELETE_DIR=`DELETE_DIR`,e.ERROR=`ERROR`,e.DOWNLOAD=`DOWNLOAD`,e.PROGRESS=`PROGRESS`,e.LOG=`LOG`,e.MOUNT=`MOUNT`,e.UNMOUNT=`UNMOUNT`})(zF||={});const BF=(()=>{let e=0;return()=>e++})(),VF=Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),HF=Error(`called FFmpeg.terminate()`);var UF=class{#e=null;#t={};#n={};#r=[];#i=[];loaded=!1;#a=()=>{this.#e&&(this.#e.onmessage=({data:{id:e,type:t,data:n}})=>{switch(t){case zF.LOAD:this.loaded=!0,this.#t[e](n);break;case zF.MOUNT:case zF.UNMOUNT:case zF.EXEC:case zF.FFPROBE:case zF.WRITE_FILE:case zF.READ_FILE:case zF.DELETE_FILE:case zF.RENAME:case zF.CREATE_DIR:case zF.LIST_DIR:case zF.DELETE_DIR:this.#t[e](n);break;case zF.LOG:this.#r.forEach(e=>e(n));break;case zF.PROGRESS:this.#i.forEach(e=>e(n));break;case zF.ERROR:this.#n[e](n);break}delete this.#t[e],delete this.#n[e]})};#o=({type:e,data:t},n=[],r)=>this.#e?new Promise((i,a)=>{let o=BF();this.#e&&this.#e.postMessage({id:o,type:e,data:t},n),this.#t[o]=i,this.#n[o]=a,r?.addEventListener(`abort`,()=>{a(new DOMException(`Message # ${o} was aborted`,`AbortError`))},{once:!0})}):Promise.reject(VF);on(e,t){e===`log`?this.#r.push(t):e===`progress`&&this.#i.push(t)}off(e,t){e===`log`?this.#r=this.#r.filter(e=>e!==t):e===`progress`&&(this.#i=this.#i.filter(e=>e!==t))}load=({classWorkerURL:e,...t}={},{signal:n}={})=>(this.#e||(this.#e=e?new Worker(new URL(e,import.meta.url),{type:`module`}):new Worker(new URL(`/assets/worker-D1KsWRGg.js`,``+import.meta.url),{type:`module`}),this.#a()),this.#o({type:zF.LOAD,data:t},void 0,n));exec=(e,t=-1,{signal:n}={})=>this.#o({type:zF.EXEC,data:{args:e,timeout:t}},void 0,n);ffprobe=(e,t=-1,{signal:n}={})=>this.#o({type:zF.FFPROBE,data:{args:e,timeout:t}},void 0,n);terminate=()=>{let e=Object.keys(this.#n);for(let t of e)this.#n[t](HF),delete this.#n[t],delete this.#t[t];this.#e&&(this.#e.terminate(),this.#e=null,this.loaded=!1)};writeFile=(e,t,{signal:n}={})=>{let r=[];return t instanceof Uint8Array&&r.push(t.buffer),this.#o({type:zF.WRITE_FILE,data:{path:e,data:t}},r,n)};mount=(e,t,n)=>this.#o({type:zF.MOUNT,data:{fsType:e,options:t,mountPoint:n}},[]);unmount=e=>this.#o({type:zF.UNMOUNT,data:{mountPoint:e}},[]);readFile=(e,t=`binary`,{signal:n}={})=>this.#o({type:zF.READ_FILE,data:{path:e,encoding:t}},void 0,n);deleteFile=(e,{signal:t}={})=>this.#o({type:zF.DELETE_FILE,data:{path:e}},void 0,t);rename=(e,t,{signal:n}={})=>this.#o({type:zF.RENAME,data:{oldPath:e,newPath:t}},void 0,n);createDir=(e,{signal:t}={})=>this.#o({type:zF.CREATE_DIR,data:{path:e}},void 0,t);listDir=(e,{signal:t}={})=>this.#o({type:zF.LIST_DIR,data:{path:e}},void 0,t);deleteDir=(e,{signal:t}={})=>this.#o({type:zF.DELETE_DIR,data:{path:e}},void 0,t)},WF;(function(e){e.MEMFS=`MEMFS`,e.NODEFS=`NODEFS`,e.NODERAWFS=`NODERAWFS`,e.IDBFS=`IDBFS`,e.WORKERFS=`WORKERFS`,e.PROXYFS=`PROXYFS`})(WF||={});const GF="@ffmpeg/core is not installed in node_modules: run `ipk add @ffmpeg/core@0.12.10` (no network fallback)";let KF=null;async function qF(e={}){return KF||=JF(e.onProgress,e.ipk).catch(e=>{throw KF=null,e}),KF}async function JF(e,t){let n=e??(()=>{}),r=new UF,i=await XF(t,n);return n(`initializing ffmpeg-core...`),await r.load({coreURL:i.coreURL,wasmURL:i.wasmURL,...i.classWorkerURL?{classWorkerURL:i.classWorkerURL}:{}}),n(`ffmpeg ready`),r}async function YF(e){let t;try{t=await tn(`@ffmpeg/core/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=nt(t.path).dir,r=`${n}/dist/esm/ffmpeg-core.js`,i=`${n}/dist/esm/ffmpeg-core.wasm`;if(!await e.reader.exists(r)||!await e.reader.exists(i))return null;try{return{coreSource:await e.reader.readFile(r),wasmBytes:await e.readBytes(i)}}catch{return null}}async function XF(e,t){if(cn())throw Error(`ffmpeg-wasm is not available in Node runtime`);if(!e)throw Error(GF);let n=await YF(e);if(!n)throw Error(GF);t(`ffmpeg-core loaded from ipk node_modules (js: ${n.coreSource.length} chars, wasm: ${n.wasmBytes.byteLength} bytes)`);let r=ZF(n.wasmBytes,`application/wasm`);return{coreURL:QF(n.coreSource,`text/javascript`),wasmURL:r}}function ZF(e,t){let n=new ArrayBuffer(e.byteLength);return new Uint8Array(n).set(e),URL.createObjectURL(new Blob([n],{type:t}))}function QF(e,t){return URL.createObjectURL(new Blob([e],{type:t}))}function $F(){return{stdout:`ffmpeg - WASM build, downloaded on demand
|
|
6161
6161
|
|
|
6162
6162
|
Usage:
|
|
6163
6163
|
ffmpeg [global-opts] -i input [input-opts] ... output [output-opts]
|
|
@@ -6194,14 +6194,14 @@ Notes:
|
|
|
6194
6194
|
- The browser will prompt for camera/mic permission on first capture.
|
|
6195
6195
|
- Numeric -i values index into the per-kind enumerateDevices() list,
|
|
6196
6196
|
matching ffmpeg's native avfoundation device numbering on macOS.
|
|
6197
|
-
`,stderr:``,exitCode:0}}async function
|
|
6198
|
-
`,stderr:``,exitCode:0}:{stdout:``,stderr:`ffmpeg: ${
|
|
6199
|
-
`,exitCode:1}:
|
|
6200
|
-
`,exitCode:1}})}async function
|
|
6201
|
-
`)}\n`,exitCode:0}}async function
|
|
6202
|
-
`,exitCode:1}}}catch(e){return{error:{stdout:``,stderr:
|
|
6197
|
+
`,stderr:``,exitCode:0}}async function eI(e){return await YF(mI(e))?{stdout:`ffmpeg (wasm via @ffmpeg/ffmpeg)
|
|
6198
|
+
`,stderr:``,exitCode:0}:{stdout:``,stderr:`ffmpeg: ${GF}\n`,exitCode:1}}function tI(e){if(!e.includes(`:`))return{video:e};let t=e.indexOf(`:`),n=e.slice(0,t),r=e.slice(t+1);return{...n?{video:n}:{},...r?{audio:r}:{}}}const nI=new Set(`-f.-i.-c.-c:v.-c:a.-vf.-af.-filter:v.-filter:a.-filter_complex.-r.-b:v.-b:a.-s.-t.-ss.-to.-pix_fmt.-vcodec.-acodec.-ar.-ac.-frames:v.-frames:a.-q:v.-q:a.-crf.-preset.-tune.-movflags.-map.-metadata.-loglevel.-threads.-video_size.-framerate.-pixel_format.-update.-list_devices.-warmup`.split(`.`));function rI(){return{inputs:[],outputOpts:[],outputPath:null,listDevices:!1,exactSize:!1,pendingOpts:[]}}function iI(e,t,n){let r=e[t+1];if(typeof r!=`string`)throw Error(`ffmpeg: ${n} requires a value`);return r}function aI(e,t,n){let r=iI(t,n,`-i`);return e.inputs.push({path:r,format:e.pendingFormat,videoSize:e.pendingVideoSize,frameRate:e.pendingFrameRate,raw:[...e.pendingOpts,`-i`,r]}),e.pendingFormat=void 0,e.pendingVideoSize=void 0,e.pendingFrameRate=void 0,e.pendingOpts=[],n+2}function oI(e,t,n){let r=iI(t,n,`-video_size`),i=/^(\d+)x(\d+)$/.exec(r);return i&&(e.pendingVideoSize={width:parseInt(i[1],10),height:parseInt(i[2],10)}),e.pendingOpts.push(`-video_size`,r),n+2}function sI(e,t,n){let r=iI(t,n,`-framerate`),i=parseFloat(r);return Number.isNaN(i)||(e.pendingFrameRate=i),e.pendingOpts.push(`-framerate`,r),n+2}function cI(e,t,n){let r=iI(t,n,`-list_devices`);return/^(true|1|yes)$/i.test(r)&&(e.listDevices=!0),e.pendingOpts.push(`-list_devices`,r),n+2}function lI(e,t,n){let r=iI(t,n,`-warmup`),i=parseInt(r,10);return!Number.isNaN(i)&&i>=0&&(e.warmupMs=i),n+2}function uI(e,t,n,r){if(nI.has(r)){let i=iI(t,n,r);return e.pendingOpts.push(r,i),n+2}return e.pendingOpts.push(r),n+1}function dI(e,t,n){return e.outputPath=t,e.outputOpts=e.pendingOpts,e.pendingOpts=[],n+1}function fI(e){let t=rI(),n=0;for(;n<e.length;){let r=e[n];if(r===`-i`){n=aI(t,e,n);continue}if(r===`-f`){let r=iI(e,n,`-f`);t.pendingFormat=r,t.pendingOpts.push(`-f`,r),n+=2;continue}if(r===`-video_size`){n=oI(t,e,n);continue}if(r===`-framerate`){n=sI(t,e,n);continue}if(r===`-list_devices`){n=cI(t,e,n);continue}if(r===`-warmup`){n=lI(t,e,n);continue}if(r===`-exact_size`){t.exactSize=!0,n+=1;continue}if(r.startsWith(`-`)){n=uI(t,e,n,r);continue}n=dI(t,r,n)}return{inputs:t.inputs,outputOpts:t.outputOpts,outputPath:t.outputPath,listDevices:t.listDevices,...t.warmupMs===void 0?{}:{warmupMs:t.warmupMs},exactSize:t.exactSize}}function pI(e){return e.inputs.some(e=>e.format===`avfoundation`)}function mI(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},readBytes:t=>e.fs.readFileBuffer(t),fromDir:e.cwd}}function hI(e){let t=[];return(e.mode===`photo`||e.captureVideo!==!1)&&t.push(`camera`),e.mode===`video`&&e.captureAudio&&t.push(`microphone`),t}function gI(e){return e.length===0?`media devices`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`}function _I(e){for(let t of e){let e=t.stream;if(e)for(let t of e.getTracks())t.stop()}}async function vI(e,t){if(typeof window>`u`)return null;try{let{getLeaderPermissionsSurface:n}=await import(`./wc-permissions-registry-C7PhTX3c.js`).then(e=>e.n),r=n();if(!r)return null;let i=await r.prompt({kinds:e,description:t});if(_I(i.grants),i.status===`granted`)return{ok:!0};let a=i.message?`: ${i.message}`:``;return{ok:!1,message:`${i.reason??i.status}${a}`}}catch{return null}}async function yI(e){if(e.length===0)return{ok:!0};let t=`ffmpeg is requesting access to your ${gI(e)}.`,n=await vI(e,t);if(n)return n;let r=He();if(r)try{return await r.call(`permission-request`,{kinds:e,description:t},{timeoutMs:5*6e4}),{ok:!0}}catch(e){let t=e instanceof Error?e.message:String(e);return/permission surface unavailable/i.test(t)?{ok:!0}:{ok:!1,message:t}}return{ok:!0}}function bI(e){let t=e.inputs.find(e=>e.format===`avfoundation`);if(!t)throw Error(`ffmpeg: no avfoundation input found`);if(!e.outputPath)throw Error(`ffmpeg: output path is required`);let n=e.outputOpts.indexOf(`-frames:v`),r=n>=0&&e.outputOpts[n+1]===`1`,i=e.outputOpts.indexOf(`-update`),a=i>=0&&e.outputOpts[i+1]===`1`,o=e.outputOpts.indexOf(`-t`),s=o>=0?parseFloat(e.outputOpts[o+1]):NaN,c=tI(t.path),l=SI(e.outputPath),u=/^image\//.test(l),d=!c.video&&!!c.audio;if(!d&&(r||a||u)){let n=u&&/^image\/(jpeg|png|webp)$/.test(l)?l:`image/jpeg`;return{outputPath:e.outputPath,captureMime:n,needsTranscode:xI(e.outputOpts,`photo`)||n!==l,request:{mode:`photo`,deviceId:c.video,width:t.videoSize?.width,height:t.videoSize?.height,frameRate:t.frameRate,exactSize:e.exactSize,mimeType:n,quality:.92,...e.warmupMs===void 0?{}:{warmupMs:e.warmupMs}}}}let f=d||!!c.audio,p=`video/webm`;return{outputPath:e.outputPath,captureMime:p,needsTranscode:xI(e.outputOpts,`video`)||p!==l,request:{mode:`video`,deviceId:c.video,captureVideo:!d,...f?{captureAudio:!0}:{},...c.audio?{audioDeviceId:c.audio}:{},width:t.videoSize?.width,height:t.videoSize?.height,frameRate:t.frameRate,exactSize:e.exactSize,mimeType:p,durationMs:Number.isFinite(s)?s*1e3:void 0}}}function xI(e,t){let n=t===`photo`?new Set([`-vf`,`-filter:v`,`-filter_complex`,`-pix_fmt`,`-q:v`,`-vcodec`,`-c:v`]):new Set([`-c`,`-c:v`,`-c:a`,`-vcodec`,`-acodec`,`-vf`,`-af`,`-filter:v`,`-filter:a`,`-filter_complex`,`-pix_fmt`,`-pixel_format`,`-crf`,`-preset`,`-tune`,`-b:v`,`-b:a`,`-ar`,`-ac`,`-q:v`,`-q:a`,`-movflags`,`-r`]);return e.some(e=>n.has(e))}function SI(e){let t=e.toLowerCase();return t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.webp`)?`image/webp`:t.endsWith(`.gif`)?`image/gif`:t.endsWith(`.webm`)?`video/webm`:t.endsWith(`.mp4`)?`video/mp4`:t.endsWith(`.mov`)?`video/quicktime`:t.endsWith(`.mkv`)?`video/x-matroska`:t.endsWith(`.m4a`)?`audio/mp4`:t.endsWith(`.mp3`)?`audio/mpeg`:t.endsWith(`.wav`)?`audio/wav`:t.endsWith(`.ogg`)?`audio/ogg`:`application/octet-stream`}function CI(e){return e===`image/jpeg`?`jpg`:e===`image/png`?`png`:e===`image/webp`?`webp`:e===`video/webm`?`webm`:e===`video/mp4`?`mp4`:e===`audio/webm`?`webm`:`bin`}function wI(e,t){let n=e.path.lastIndexOf(`/`),r=n>=0?e.path.slice(n+1):e.path;return r?`__in${t}_${r}`:`__in${t}.bin`}function TI(){return G(`ffmpeg`,async(e,t)=>{if(e.length===0||e.includes(`--help`))return $F();if(e.includes(`-version`)||e.includes(`--version`))return eI(t);let n;try{n=fI(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return n.listDevices&&pI(n)?EI():n.outputPath?n.inputs.length===0?{stdout:``,stderr:`ffmpeg: at least one input file must be specified
|
|
6199
|
+
`,exitCode:1}:pI(n)?MI(n,t):RI(n,t):{stdout:``,stderr:`ffmpeg: at least one output file must be specified
|
|
6200
|
+
`,exitCode:1}})}async function EI(){let e;try{e=await DI()}catch(e){return{stdout:``,stderr:`ffmpeg: failed to enumerate devices: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let t=[];return t.push(`[AVFoundation indev @ 0x0] AVFoundation video devices:`),e.videoinputs.length===0?t.push(`[AVFoundation indev @ 0x0] (none)`):e.videoinputs.forEach((e,n)=>{t.push(`[AVFoundation indev @ 0x0] [${n}] ${e.label||`Camera ${n}`}`)}),t.push(`[AVFoundation indev @ 0x0] AVFoundation audio devices:`),e.audioinputs.length===0?t.push(`[AVFoundation indev @ 0x0] (none)`):e.audioinputs.forEach((e,n)=>{t.push(`[AVFoundation indev @ 0x0] [${n}] ${e.label||`Microphone ${n}`}`)}),{stdout:``,stderr:`${t.join(`
|
|
6201
|
+
`)}\n`,exitCode:0}}async function DI(){if(Ue()&&typeof navigator<`u`&&navigator.mediaDevices?.enumerateDevices){let e=await navigator.mediaDevices.enumerateDevices(),t=e=>({deviceId:e.deviceId,label:e.label||``,...e.groupId?{groupId:e.groupId}:{}});return{videoinputs:e.filter(e=>e.kind===`videoinput`).map(t),audioinputs:e.filter(e=>e.kind===`audioinput`).map(t)}}let e=He();if(!e)throw Error(`device enumeration requires a browser context`);return e.call(`enumerate-media-devices`,void 0,{timeoutMs:1e4})}async function OI(e){let t=await FF({kind:`camera`,...e.request}),n=new ArrayBuffer(t.bytes.byteLength);return new Uint8Array(n).set(t.bytes),{bytes:n,mimeType:t.mimeType,width:t.width,height:t.height,...t.durationMs===void 0?{}:{durationMs:t.durationMs}}}async function kI(e){let t=He();if(!t)return null;let n=await t.call(`capture-camera`,e.request,{timeoutMs:5*6e4});return{bytes:n.bytes,mimeType:n.mimeType,width:n.width,height:n.height,durationMs:n.durationMs}}async function AI(e){try{if(NF())return{result:await OI(e)};let t=await kI(e);return t?{result:t}:{error:{stdout:``,stderr:`ffmpeg: camera capture requires a browser context — not available in this runtime
|
|
6202
|
+
`,exitCode:1}}}catch(e){return{error:{stdout:``,stderr:jI(e),exitCode:1}}}}function jI(e){let t=e instanceof Error?e.message:String(e);return/NotAllowedError|Permission denied/i.test(t)?`ffmpeg: camera permission denied
|
|
6203
6203
|
`:/NotFoundError/i.test(t)?`ffmpeg: no camera device found
|
|
6204
|
-
`:`ffmpeg: ${t}\n`}async function
|
|
6204
|
+
`:`ffmpeg: ${t}\n`}async function MI(e,t){let n;try{n=bI(e)}catch(e){return{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let r=await yI(hI(n.request));if(!r.ok)return{stdout:``,stderr:`ffmpeg: camera permission denied (${r.message})\n`,exitCode:1};let i=await AI(n);if(`error`in i)return i.error;let a=i.result,o=Math.round(a.bytes.byteLength/1024),s=`${a.width}x${a.height}`,c=n.request.mode===`video`&&a.durationMs?`${s}, ${Math.round(a.durationMs)}ms`:s,l=new Uint8Array(a.bytes),u=``;if(n.needsTranscode)try{let r=await NI({bytes:l,captureMime:n.captureMime,outputName:n.outputPath,outputOpts:e.outputOpts,ipk:mI(t),onLog:e=>{u+=`${e}\n`}});l=new Uint8Array(r.byteLength),l.set(r)}catch(e){let t=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`${u}ffmpeg: captured ${c} (${o} KB) but transcode failed: ${t}\n`,exitCode:1}}let d=t.fs.resolvePath(t.cwd,n.outputPath);try{await t.fs.writeFile(d,l)}catch(e){return{stdout:``,stderr:`ffmpeg: failed to write ${n.outputPath}: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let f=Math.round(l.byteLength/1024),p=n.needsTranscode?`${o} KB → ${f} KB`:`${o} KB`;return{stdout:``,stderr:`${u}ffmpeg: captured ${c} (${p}) to ${n.outputPath}\n`,exitCode:0}}async function NI(e){let t=`__capture.${CI(e.captureMime)}`,n=`__out_${e.outputName.split(`/`).pop()||`out.bin`}`;e.onLog(`transcoding captured stream...`);let r=await qF({onProgress:e.onLog,ipk:e.ipk}),i=t=>{e.onLog(t.message)};r.on(`log`,i);try{await r.writeFile(t,e.bytes);let i=[`-i`,t,...e.outputOpts,n],a=await r.exec(i);if(a!==0)throw Error(`ffmpeg-core exited with code ${a}`);let o=await r.readFile(n);if(o instanceof Uint8Array)return o;if(typeof o==`string`)return new TextEncoder().encode(o);throw Error(`ffmpeg-core returned an unknown payload type`)}finally{try{r.off(`log`,i)}catch{}try{await r.deleteFile(t)}catch{}try{await r.deleteFile(n)}catch{}}}function PI(e){return e.format===`lavfi`}async function FI(e,t){let n=[];for(let[r,i]of e.inputs.entries()){if(PI(i)){n.push({ffmpegName:i.path,bytes:null,virtual:!0});continue}let e=t.fs.resolvePath(t.cwd,i.path);if(!await t.fs.exists(e))return{error:{stdout:``,stderr:`ffmpeg: input file not found: ${i.path}\n`,exitCode:1}};let a=await t.fs.readFileBuffer(e);n.push({ffmpegName:wI(i,r),bytes:a,virtual:!1})}return{inputs:n}}function II(e,t,n){let r=[];for(let[n,i]of e.inputs.entries()){let e=t[n],a=i.raw;for(let t=0;t<a.length;t++){if(a[t]===`-i`){r.push(`-i`,e.virtual?a[t+1]:e.ffmpegName),t+=1;continue}r.push(a[t])}}return r.push(...e.outputOpts),r.push(n),r}async function LI(e,t,n){for(let n of t)if(n.bytes!==null)try{await e.deleteFile(n.ffmpegName)}catch{}try{await e.deleteFile(n)}catch{}}async function RI(e,t){let n=await FI(e,t);if(`error`in n)return n.error;let r=n.inputs,i=e.outputPath,a=`__out_${i.split(`/`).pop()||`out.bin`}`,o=``,s;try{s=await qF({onProgress:e=>{o+=`${e}\n`},ipk:mI(t)})}catch(e){return{stdout:``,stderr:`${o}ffmpeg: failed to load wasm: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let c=e=>{o+=`${e.message}\n`};s.on(`log`,c);try{for(let e of r)e.bytes!==null&&await s.writeFile(e.ffmpegName,e.bytes);let n=II(e,r,a),c=await s.exec(n);if(c!==0)return{stdout:``,stderr:o||`ffmpeg: exited with code ${c}\n`,exitCode:c||1};let l;try{l=await s.readFile(a)}catch{return{stdout:``,stderr:o||`ffmpeg: produced no output file for ${i}\n`,exitCode:1}}let u=l instanceof Uint8Array?l:new TextEncoder().encode(typeof l==`string`?l:``);if(u.byteLength===0)return{stdout:``,stderr:o||`ffmpeg: produced an empty output file for ${i}\n`,exitCode:1};let d=t.fs.resolvePath(t.cwd,i);return await t.fs.writeFile(d,u),{stdout:``,stderr:o,exitCode:0}}catch(e){return{stdout:``,stderr:`${o}ffmpeg: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}finally{try{s.off(`log`,c)}catch{}await LI(s,r,a)}}const zI=new Map;let BI=0;function VI(){return G(`fswatch`,async e=>{let t=e[0];if(!t||t===`--help`)return{stdout:`usage: fswatch <command> [options]
|
|
6205
6205
|
|
|
6206
6206
|
Commands:
|
|
6207
6207
|
create --path <path> --pattern <glob> [--scoop <name>] [--name <name>] Watch for file changes
|
|
@@ -6213,11 +6213,11 @@ Options:
|
|
|
6213
6213
|
--pattern <glob> File pattern to match, e.g. "*.md", "*.bsh" (required)
|
|
6214
6214
|
--scoop <name> Route change events to this scoop as lick events
|
|
6215
6215
|
--name <name> Human-readable name for the watcher
|
|
6216
|
-
`,stderr:``,exitCode:0};if(t===`list`){if(
|
|
6217
|
-
`,stderr:``,exitCode:0};let e=``;for(let[,t]of
|
|
6218
|
-
`,exitCode:1};let n=
|
|
6216
|
+
`,stderr:``,exitCode:0};if(t===`list`){if(zI.size===0)return{stdout:`No active file watchers.
|
|
6217
|
+
`,stderr:``,exitCode:0};let e=``;for(let[,t]of zI)e+=`ID: ${t.id}\n`,e+=` Name: ${t.name}\n`,e+=` Path: ${t.basePath}\n`,e+=` Pattern: ${t.pattern}\n`,t.scoop&&(e+=` Scoop: ${t.scoop}\n`),e+=` Created: ${t.createdAt}\n\n`;return{stdout:e,stderr:``,exitCode:0}}if(t===`delete`){let t=e[1];if(!t)return{stdout:``,stderr:`fswatch: delete requires an ID
|
|
6218
|
+
`,exitCode:1};let n=zI.get(t);return n?(n.unsubscribe(),zI.delete(t),{stdout:`Deleted watcher "${n.name}" (${t})\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`fswatch: watcher not found: ${t}\n`,exitCode:1}}if(t===`create`){let t=``,n=``,r=``,i=``;for(let a=1;a<e.length;a++)e[a]===`--path`&&e[a+1]?t=e[++a]:e[a]===`--pattern`&&e[a+1]?n=e[++a]:e[a]===`--scoop`&&e[a+1]?r=e[++a]:e[a]===`--name`&&e[a+1]&&(i=e[++a]);if(!t||!n)return{stdout:``,stderr:`fswatch: --path and --pattern are required
|
|
6219
6219
|
`,exitCode:1};let a=RegExp(`^`+n.replace(/\./g,`\\.`).replace(/\*/g,`.*`)+`$`),o=e=>{let t=e.split(`/`).pop()??``;return a.test(t)},s=globalThis.__slicc_fs_watcher;if(!s)return{stdout:``,stderr:`fswatch: file system watcher not available
|
|
6220
|
-
`,exitCode:1};let c=`fsw-${++
|
|
6220
|
+
`,exitCode:1};let c=`fsw-${++BI}`;i||=`${n} in ${t}`;let l=globalThis.__slicc_lick_handler,u=s.watch(t,o,e=>{l&&l({type:`fswatch`,fswatchId:c,fswatchName:i,targetScoop:r,timestamp:new Date().toISOString(),changes:e.map(e=>({type:e.type,path:e.path})),body:{changes:e.map(e=>({type:e.type,path:e.path}))}})});zI.set(c,{id:c,name:i,basePath:t,pattern:n,scoop:r,unsubscribe:u,createdAt:new Date().toISOString()});let d=`Created file watcher "${i}"\n`;return d+=`ID: ${c}\n`,d+=`Path: ${t}\n`,d+=`Pattern: ${n}\n`,r&&(d+=`Scoop: ${r}\n`),{stdout:d,stderr:``,exitCode:0}}return{stdout:``,stderr:`fswatch: unknown command: ${t}\n`,exitCode:1}})}function HI(){return{stdout:`usage: hear [-i file] [-l lang] [-T seconds] [-d deviceId] [--engine name]
|
|
6221
6221
|
hear --devices | --status | --warmup
|
|
6222
6222
|
|
|
6223
6223
|
Speech recognition: listens on the microphone until you pause, then
|
|
@@ -6235,15 +6235,15 @@ Options:
|
|
|
6235
6235
|
--devices List audio input devices
|
|
6236
6236
|
--status Show the enhanced model state (downloading/ready + ETA)
|
|
6237
6237
|
--warmup Start the enhanced model download in the background
|
|
6238
|
-
`,stderr:``,exitCode:0}}const
|
|
6238
|
+
`,stderr:``,exitCode:0}}const UI={"--devices":`devices`,"--status":`status`,"--warmup":`warmup`},WI={"-i":`a file path`,"-l":`a language tag`,"-T":`a timeout in seconds`,"-d":`a device id`,"--engine":`an engine name`};function GI(e,t,n){switch(t){case`-i`:return e.inputFile=n,null;case`-l`:return e.lang=n,null;case`-d`:return e.deviceId=n,null;case`-T`:{let t=Number.parseFloat(n);return Number.isNaN(t)||t<=0||t>600?`-T requires a timeout between 0 and 600 seconds`:(e.timeoutSeconds=t,null)}case`--engine`:return n!==`builtin`&&n!==`enhanced`?`--engine must be builtin or enhanced`:(e.engine=n,null);default:return`unknown option: ${t}`}}function KI(e){let t={inputFile:null,lang:void 0,timeoutSeconds:30,deviceId:void 0,engine:`auto`,devices:!1,status:!1,warmup:!1};for(let n=0;n<e.length;n++){let r=e[n],i=UI[r];if(i){t[i]=!0;continue}if(!(r in WI))return JI(`unknown option: ${r}`);let a=n+1<e.length?e[++n]:null;if(a==null)return JI(`${r} requires ${WI[r]}`);let o=GI(t,r,a);if(o)return JI(o)}return t}function qI(e){switch(e.state){case`ready`:return`enhanced engine: ready
|
|
6239
6239
|
`;case`failed`:return`enhanced engine: failed (re-run hear --warmup to retry)
|
|
6240
6240
|
`;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
|
|
6241
|
-
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`enhanced engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function
|
|
6241
|
+
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`enhanced engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function JI(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function YI(e){return e instanceof Error?e.message:String(e)}function XI(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
|
|
6242
6242
|
`)+(t.length?`
|
|
6243
|
-
`:``)}async function
|
|
6244
|
-
`,stderr:``,exitCode:0}}catch(e){return
|
|
6243
|
+
`:``)}async function ZI(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:XI((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:JI(`device enumeration unavailable`):{stdout:XI((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return JI(YI(e))}}async function QI(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-D7srqY_7.js`);return{stdout:qI(t?n():e()),stderr:``,exitCode:0}}return{stdout:qI(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return JI(YI(e))}}async function $I(e,t,n){let r=t.inputFile,i=n.fs.resolvePath(n.cwd,r),a;try{a=new Uint8Array(await n.fs.readFileBuffer(i))}catch{return JI(`cannot open ${r}: No such file`)}let o=_n(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return JI(`${r} is not an audio file`);let s=new ArrayBuffer(a.byteLength);new Uint8Array(s).set(a);try{return{stdout:(e.local?await(await import(`./hear-D7srqY_7.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
|
|
6244
|
+
`,stderr:``,exitCode:0}}catch(e){return JI(`transcription failed: ${YI(e)}`)}}async function eL(e,t){let n=Math.round(t.timeoutSeconds*1e3);try{let r={lang:t.lang,timeoutMs:n,deviceId:t.deviceId,engine:t.engine},i=e.local?await(await import(`./hear-D7srqY_7.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
|
|
6245
6245
|
`,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
|
|
6246
|
-
`,exitCode:1}}catch(e){return
|
|
6246
|
+
`,exitCode:1}}catch(e){return JI(YI(e))}}function tL(){return G(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return HI();let n=KI(e);if(`exitCode`in n)return n;let r={local:Ue(),panelRpc:He()};return!r.local&&!r.panelRpc?JI(`speech recognition unavailable in this environment`):n.devices?ZI(r):n.status||n.warmup?QI(r,n.warmup):n.inputFile?$I(r,n,t):eL(r,n)})}const nL=[`playwright-cli`,`playwright`,`puppeteer`],rL=new WeakMap;function iL(e,t){let n=rL.get(e);n||(n=new WeakMap,rL.set(e,n));let r=n.get(t);return r||(r={snapshots:new Map,appTabId:null,harRecorder:null,sessionDirsCreated:!1,teleportWatchers:new Map,consoleMessages:new Map,consoleCleanup:new Map,networkRequests:new Map,networkRequestIndex:new Map,networkCleanup:new Map,routes:new Map,routeCleanup:new Map,lastMousePosition:new Map},n.set(t,r)),r}function aL(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const oL=d,sL=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`,`drop`]);function cL(e){return e.toISOString().replace(/:/g,`-`)}function lL(e){return e instanceof L||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const uL=`function(text) {
|
|
6247
6247
|
const el = this;
|
|
6248
6248
|
const tag = el.tagName;
|
|
6249
6249
|
const proto = tag === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
|
|
@@ -6255,11 +6255,11 @@ Options:
|
|
|
6255
6255
|
}
|
|
6256
6256
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6257
6257
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6258
|
-
}`,
|
|
6258
|
+
}`,dL=`function() {
|
|
6259
6259
|
const el = this;
|
|
6260
6260
|
if (el.isContentEditable) return el.textContent || '';
|
|
6261
6261
|
return el.value ?? '';
|
|
6262
|
-
}`,
|
|
6262
|
+
}`,fL=`function() {
|
|
6263
6263
|
const el = this;
|
|
6264
6264
|
if (!(el instanceof HTMLElement)) return false;
|
|
6265
6265
|
el.focus();
|
|
@@ -6283,19 +6283,19 @@ Options:
|
|
|
6283
6283
|
return true;
|
|
6284
6284
|
}
|
|
6285
6285
|
return false;
|
|
6286
|
-
}`;async function
|
|
6287
|
-
`}}const
|
|
6286
|
+
}`;async function pL(e){let t=await e.evaluate(`JSON.stringify({ href: location.href, hostname: location.hostname, pathname: location.pathname })`);return JSON.parse(t)}const mL={string:[`tab`,`filename`,`max-width`,`runtime`,`timeout`,`filter`,`output`,`start`,`return`,`teleport-start`,`teleport-return`,`teleport-runtime`,`domain`,`path`,`expires`,`method`,`depth`,`modifiers`,`sameSite`,`data`,`status`,`body`,`content-type`,`header`,`style`],boolean:[`boxes`,`clear`,`discover`,`foreground`,`fg`,`full-page`,`fullPage`,`hide`,`httpOnly`,`list`,`off`,`secure`,`static`,`submit`],alias:{foreground:`fg`,"full-page":`fullPage`}};function hL(e){let t=Am(e.map(e=>e===`--no-iframes`||e.startsWith(`--no-iframes=`)?e.replace(`--no-iframes`,`--_noiframes`):e),mL),n={};for(let[e,r]of Object.entries(t.flags)){let t=e===`_noiframes`?`no-iframes`:e;if(r===!0)n[t]=`true`;else if(r===!1)continue;else r!==void 0&&(n[t]=String(r))}return{positional:t.positionals,flags:n}}function Q(e){let t=e.tab;return t?{targetId:t}:{error:`Error: --tab <targetId> is required. Run 'playwright-cli tab-list' to get tab IDs.
|
|
6287
|
+
`}}const gL=[`debug`,`log`,`info`,`warning`,`error`],_L=1e3,vL={assert:`error`,trace:`debug`,dir:`log`,dirxml:`log`,table:`log`,count:`info`,timeEnd:`info`,clear:`log`,startGroup:`log`,startGroupCollapsed:`log`,endGroup:`log`,profile:`debug`,profileEnd:`debug`};function yL(e,t,n,r){if(e.consoleCleanup.has(n))return;e.consoleMessages.set(n,[]);let i=t=>{if(t.sessionId!==r)return;let i=t.type??`log`,a=vL[i]??i,o=(t.args??[]).map(e=>String(e.value??e.description??``)).join(` `),s=e.consoleMessages.get(n);s&&(s.push({level:a,text:o,timestamp:Date.now()}),s.length>_L&&s.splice(0,s.length-_L))};t.on(`Runtime.consoleAPICalled`,i),e.consoleCleanup.set(n,()=>{t.off(`Runtime.consoleAPICalled`,i)})}const bL=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0]??`log`,o=r.clear===`true`,s=gL.indexOf(a);if(s===-1)return{stdout:``,stderr:`Invalid level "${a}". Valid: ${gL.join(`, `)}\n`,exitCode:1};t.consoleCleanup.has(i.targetId)||await e.withTab(i.targetId,async n=>{let r=e.getTransport();await r.send(`Runtime.enable`,{},n),yL(t,r,i.targetId,n)});let c=(t.consoleMessages.get(i.targetId)??[]).filter(e=>gL.indexOf(e.level)>=s);return o&&t.consoleMessages.set(i.targetId,[]),c.length===0?{stdout:`No console messages
|
|
6288
6288
|
`,stderr:``,exitCode:0}:{stdout:c.map(e=>`[${e.level}] ${e.text}`).join(`
|
|
6289
6289
|
`)+`
|
|
6290
|
-
`,stderr:``,exitCode:0}},
|
|
6290
|
+
`,stderr:``,exitCode:0}},xL=async({browser:e,flags:t})=>{let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};let r=t.domain,i=t.path;return{stdout:await e.withTab(n.targetId,async()=>{let t=(await e.sendCDP(`Network.getCookies`)).cookies??[],n=r||i?t.filter(e=>(!r||String(e.domain??``).includes(r))&&(!i||String(e.path??``).startsWith(i))):t;return n.length===0?`No cookies`:n.map(e=>`${e.name}=${e.value}\tDomain=${e.domain}\tPath=${e.path}\tSecure=${e.secure}\tHttpOnly=${e.httpOnly}\tExpires=${e.expires}`).join(`
|
|
6291
6291
|
`)})+`
|
|
6292
|
-
`,stderr:``,exitCode:0}},
|
|
6292
|
+
`,stderr:``,exitCode:0}},SL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`cookie-get requires a cookie name
|
|
6293
6293
|
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return{stdout:await e.withTab(r.targetId,async()=>{let t=((await e.sendCDP(`Network.getCookies`)).cookies??[]).filter(e=>e.name===i);if(t.length===0)throw Error(`Cookie "${i}" not found`);return t.map(e=>`${e.name}=${e.value}\tDomain=${e.domain}\tPath=${e.path}\tSecure=${e.secure}\tHttpOnly=${e.httpOnly}\tExpires=${e.expires}`).join(`
|
|
6294
6294
|
`)})+`
|
|
6295
|
-
`,stderr:``,exitCode:0}},
|
|
6296
|
-
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r=await
|
|
6297
|
-
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r={name:t[0]};n.domain&&(r.domain=n.domain),n.path&&(r.path=n.path),!r.domain&&!r.path&&(r.url=(await
|
|
6298
|
-
`,stderr:``,exitCode:0})},
|
|
6295
|
+
`,stderr:``,exitCode:0}},CL=async({browser:e,positional:t,flags:n})=>{if(t.length<2)return{stdout:``,stderr:`cookie-set requires <name> <value>
|
|
6296
|
+
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r=await pL(e),i={name:t[0],value:t[1]};n.domain&&(i.domain=n.domain),n.path&&(i.path=n.path),n.secure===`true`&&(i.secure=!0),n.httpOnly===`true`&&(i.httpOnly=!0),n.expires&&(i.expires=parseFloat(n.expires)),n.sameSite&&(i.sameSite=n.sameSite),!i.domain&&!i.path&&(i.url=r.href),await e.sendCDP(`Network.setCookie`,i)}),{stdout:`Cookie "${t[0]}" set\n`,stderr:``,exitCode:0})},wL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`cookie-delete requires a cookie name
|
|
6297
|
+
`,exitCode:1};let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{let r={name:t[0]};n.domain&&(r.domain=n.domain),n.path&&(r.path=n.path),!r.domain&&!r.path&&(r.url=(await pL(e)).href),await e.sendCDP(`Network.deleteCookies`,r)}),{stdout:`Cookie "${t[0]}" deleted\n`,stderr:``,exitCode:0})},TL=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{await e.sendCDP(`Network.clearBrowserCookies`)}),{stdout:`All cookies cleared
|
|
6298
|
+
`,stderr:``,exitCode:0})},EL=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`generate-locator requires a ref (e.g. e5)
|
|
6299
6299
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=t.snapshots.get(i.targetId);if(!o)return{stdout:``,stderr:`No snapshot available. Run "snapshot" first.
|
|
6300
6300
|
`,exitCode:1};let s=o.refToBackendNodeId.get(a);if(!s){let e=o.refToSelector.get(a);return e?{stdout:`page.locator(${JSON.stringify(e.split(`,`)[0].trim())})\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Unknown ref "${a}"\n`,exitCode:1}}let c=``;return await e.withTab(i.targetId,async t=>{let n=e.getTransport();await n.send(`DOM.enable`,{},t);let r=(await n.send(`DOM.resolveNode`,{backendNodeId:s},t)).object;if(!r?.objectId){let e=o.refToSelector.get(a)?.split(`,`)[0].trim()??``;c=`page.locator(${JSON.stringify(e)})`;return}let i=await n.send(`Runtime.callFunctionOn`,{objectId:r.objectId,functionDeclaration:`function() {
|
|
6301
6301
|
const el = this;
|
|
@@ -6307,7 +6307,7 @@ Options:
|
|
|
6307
6307
|
const id = el.id;
|
|
6308
6308
|
return JSON.stringify({ testId, label, placeholder, id });
|
|
6309
6309
|
}`,returnByValue:!0},t),l=JSON.parse(i.result?.value??`{}`);if(l.testId)c=`page.getByTestId(${JSON.stringify(l.testId)})`;else if(l.label)c=`page.getByLabel(${JSON.stringify(l.label)})`;else if(l.placeholder)c=`page.getByPlaceholder(${JSON.stringify(l.placeholder)})`;else if(l.id)c=`page.locator(${JSON.stringify(`#${l.id}`)})`;else{let e=o.refToSelector.get(a)?.split(`,`)[0].trim()??``;c=`page.locator(${JSON.stringify(e)})`}}),{stdout:c+`
|
|
6310
|
-
`,stderr:``,exitCode:0}},
|
|
6310
|
+
`,stderr:``,exitCode:0}},DL=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=r.hide===`true`,o=r.style??`outline: 3px solid #ff4444; background: rgba(255, 68, 68, 0.1);`;if(a&&!n[0])return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Runtime.evaluate`,{expression:`document.querySelectorAll('[data-slicc-highlight]').forEach(el => {
|
|
6311
6311
|
el.style.outline = '';
|
|
6312
6312
|
el.style.background = '';
|
|
6313
6313
|
el.removeAttribute('data-slicc-highlight');
|
|
@@ -6335,35 +6335,35 @@ Options:
|
|
|
6335
6335
|
el.style.cssText += '; ' + styleVal;
|
|
6336
6336
|
el.setAttribute('data-slicc-highlight','1');
|
|
6337
6337
|
}
|
|
6338
|
-
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}}),{stdout:a?`Highlight removed from ${s}\n`:`Highlighted ${s}\n`,stderr:``,exitCode:0}},
|
|
6339
|
-
`,stderr:``,exitCode:0})};function
|
|
6340
|
-
`,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
|
|
6341
|
-
`,stderr:``,exitCode:0}},
|
|
6342
|
-
`,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
|
|
6343
|
-
`,stderr:``,exitCode:0}};function
|
|
6344
|
-
`,exitCode:1};let r=t[0],{browseShWarning:i,...a}=await
|
|
6345
|
-
`,stderr:i?`${i}\n`:``,exitCode:+!!a.error}};function
|
|
6338
|
+
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}}),{stdout:a?`Highlight removed from ${s}\n`:`Highlighted ${s}\n`,stderr:``,exitCode:0}},OL=async({browser:e,positional:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.length>0?t.join(` `):void 0;return await e.withTab(r.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Page.enable`,{},n),await t.send(`Page.handleJavaScriptDialog`,{accept:!0,...i===void 0?{}:{promptText:i}},n)}),{stdout:`Accepted dialog${i?` with "${i}"`:``}\n`,stderr:``,exitCode:0}},kL=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Page.enable`,{},n),await t.send(`Page.handleJavaScriptDialog`,{accept:!1},n)}),{stdout:`Dismissed dialog
|
|
6339
|
+
`,stderr:``,exitCode:0})};function AL(e){let t=e instanceof Error?e.message:String(e);return/SyntaxError/.test(t)}function jL(e){return/\bawait\b/.test(e)||/\breturn\b/.test(e)}async function ML(e,t){try{return await e.evaluate(t)}catch(n){if(!AL(n)||!jL(t))throw n;try{return await e.evaluate(`(async () => (\n${t}\n))()`)}catch(r){if(!AL(r))throw r;try{return await e.evaluate(`(async () => {\n${t}\n})()`)}catch(e){throw AL(e)?n:e}}}}const NL=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`eval requires an expression
|
|
6340
|
+
`,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 ML(e,a);return typeof t==`string`?t:JSON.stringify(t,null,2)});return r.filename?(await t.writeFile(r.filename,o??`null`),{stdout:`Result saved to ${r.filename}\n`,stderr:``,exitCode:0}):{stdout:(o??`undefined`)+`
|
|
6341
|
+
`,stderr:``,exitCode:0}},PL=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`eval-file requires a file path
|
|
6342
|
+
`,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 ML(e,s);return typeof t==`string`?t:JSON.stringify(t,null,2)});if(o){let e=c??`null`;return await t.writeFile(o,e),{stdout:`Result saved to ${o} (${Math.round(new TextEncoder().encode(e).length/1024)} KB)\n`,stderr:``,exitCode:0}}return{stdout:(c??`undefined`)+`
|
|
6343
|
+
`,stderr:``,exitCode:0}};function FL(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.toString():t.url,i=h(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 IL(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 LL(e,t,n){let r=``;try{r=new URL(e).hostname}catch{return{}}let i=r?LA(r):``;if(!i)return{};let a;try{a=await BA(n)}catch(e){return{warning:`playwright-cli: warning: browse.sh catalog unavailable: ${e instanceof Error?e.message:String(e)}`}}let o=await IL(t),s=[];for(let e of a){if(!e.hostname||LA(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 RL(e,t={}){let n=t.fetchImpl??l(),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=Je(i,e),o=Qe(a),s={url:e,status:r.status,links:a,handoff:o};if(t.discover&&a.length>0){let e=await bP(a,{fetchImpl:FL(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 LL(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 zL=async({fs:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`fetch requires a URL
|
|
6344
|
+
`,exitCode:1};let r=t[0],{browseShWarning:i,...a}=await RL(r,{discover:n.discover===`true`,method:n.method??`GET`,fs:e});return{stdout:JSON.stringify(a,null,2)+`
|
|
6345
|
+
`,stderr:i?`${i}\n`:``,exitCode:+!!a.error}};function BL(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 VL(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 HL(e,t,n){let r=e.getTransport(),i=e.getSessionId();((await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:dL,returnByValue:!0},i)).result?.value??``)!==n&&await r.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:uL,arguments:[{value:n}],returnByValue:!0},i)}async function UL(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:fL,returnByValue:!0},i),await e.insertText(n),a?.objectId&&await HL(e,a.objectId,n)}async function WL(e,t,n){await e.click(t),await e.evaluate(`(function() {
|
|
6346
6346
|
const el = document.querySelector(${JSON.stringify(t)});
|
|
6347
|
-
if (el) { return (${
|
|
6347
|
+
if (el) { return (${fL}).call(el); }
|
|
6348
6348
|
return false;
|
|
6349
6349
|
})()`),await e.insertText(n);let r=t.split(`,`)[0].trim();await e.evaluate(`(function() {
|
|
6350
6350
|
const el = document.querySelector(${JSON.stringify(r)});
|
|
6351
6351
|
if (!el) return '';
|
|
6352
|
-
return (${
|
|
6352
|
+
return (${dL}).call(el);
|
|
6353
6353
|
})()`)!==n&&await e.evaluate(`(function() {
|
|
6354
6354
|
const el = document.querySelector(${JSON.stringify(r)});
|
|
6355
6355
|
if (!el) return;
|
|
6356
|
-
(${
|
|
6357
|
-
})()`)}const
|
|
6358
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=
|
|
6356
|
+
(${uL}).call(el, ${JSON.stringify(n)});
|
|
6357
|
+
})()`)}const GL=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`click requires a ref (e.g. e5)
|
|
6358
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=BL(r.modifiers);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),s=n.refToFrameId?.get(a);if(r&&s){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let o=r.split(`,`)[0].trim();return await e.evaluateInFrame(s,`(function() {
|
|
6359
6359
|
var el = document.querySelector(${JSON.stringify(o)});
|
|
6360
6360
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6361
6361
|
el.scrollIntoView({ block: 'center' });
|
|
6362
6362
|
el.click();
|
|
6363
6363
|
})()`),t.snapshots.delete(i.targetId),`Clicked ${a} (in iframe)`}let c=n.refToBackendNodeId.get(a);if(c)return await e.clickByBackendNodeId(c,o),t.snapshots.delete(i.targetId),`Clicked ${a}`;let l=n.refToSelector.get(a);if(!l)throw Error(`Unknown ref "${a}". Available: ${[...n.refToSelector.keys()].slice(0,10).join(`, `)}...`);return await e.click(l,o),t.snapshots.delete(i.targetId),`Clicked ${a}`})+`
|
|
6364
|
-
`,stderr:``,exitCode:0}},
|
|
6365
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.join(` `);return await e.withTab(r.targetId,async t=>{await e.type(i),n.submit===`true`&&await
|
|
6366
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async n=>{let s=t.snapshots.get(i.targetId);if(!s)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:c}=
|
|
6364
|
+
`,stderr:``,exitCode:0}},KL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`type requires text
|
|
6365
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t.join(` `);return await e.withTab(r.targetId,async t=>{await e.type(i),n.submit===`true`&&await VL(e,t)}),{stdout:`Typed: ${i}\n`,stderr:``,exitCode:0}},qL=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`fill requires <ref> <text>
|
|
6366
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async n=>{let s=t.snapshots.get(i.targetId);if(!s)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:c}=aL(a),l=s.refToFrameId?.get(a);if(c&&l){let c=s.refToSelector.get(a);if(!c)throw Error(`Unknown ref "${a}" in iframe`);let u=c.split(`,`)[0].trim();return await e.evaluateInFrame(l,`(function() {
|
|
6367
6367
|
var el = document.querySelector(${JSON.stringify(u)});
|
|
6368
6368
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6369
6369
|
el.scrollIntoView({ block: 'center' });
|
|
@@ -6372,33 +6372,33 @@ Options:
|
|
|
6372
6372
|
el.value = ${JSON.stringify(o)};
|
|
6373
6373
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6374
6374
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6375
|
-
})()`),t.snapshots.delete(i.targetId),r.submit===`true`&&await
|
|
6376
|
-
`,stderr:``,exitCode:0}},
|
|
6377
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t),await n.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Pressed ${i}\n`,stderr:``,exitCode:0}},
|
|
6378
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t)}),{stdout:`Key ${i} down\n`,stderr:``,exitCode:0}},
|
|
6379
|
-
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Key ${i} up\n`,stderr:``,exitCode:0}},
|
|
6380
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1]||`left`,s=
|
|
6375
|
+
})()`),t.snapshots.delete(i.targetId),r.submit===`true`&&await VL(e,n),`Filled ${a} with: ${o} (in iframe)`}let u=s.refToBackendNodeId.get(a);if(u)return await UL(e,u,o),t.snapshots.delete(i.targetId),r.submit===`true`&&await VL(e,n),`Filled ${a} with: ${o}`;let d=s.refToSelector.get(a);if(!d)throw Error(`Unknown ref "${a}"`);return await WL(e,d,o),t.snapshots.delete(i.targetId),r.submit===`true`&&await VL(e,n),`Filled ${a} with: ${o}`})+`
|
|
6376
|
+
`,stderr:``,exitCode:0}},JL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`press requires a key name
|
|
6377
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t),await n.send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Pressed ${i}\n`,stderr:``,exitCode:0}},YL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`keydown requires a key name
|
|
6378
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyDown`,key:i},t)}),{stdout:`Key ${i} down\n`,stderr:``,exitCode:0}},XL=async({browser:e,positional:t,flags:n})=>{if(t.length===0)return{stdout:``,stderr:`keyup requires a key name
|
|
6379
|
+
`,exitCode:1};let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];return await e.withTab(r.targetId,async t=>{await e.getTransport().send(`Input.dispatchKeyEvent`,{type:`keyUp`,key:i},t)}),{stdout:`Key ${i} up\n`,stderr:``,exitCode:0}},ZL=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`dblclick requires a ref (e.g. e5)
|
|
6380
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1]||`left`,s=BL(r.modifiers);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),c=n.refToFrameId?.get(a);if(r&&c){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let o=r.split(`,`)[0].trim();return await e.evaluateInFrame(c,`(function() {
|
|
6381
6381
|
var el = document.querySelector(${JSON.stringify(o)});
|
|
6382
6382
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6383
6383
|
el.scrollIntoView({ block: 'center' });
|
|
6384
6384
|
el.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
|
|
6385
6385
|
})()`),t.snapshots.delete(i.targetId),`Double-clicked ${a} (in iframe)`}let l=n.refToBackendNodeId.get(a);if(!l)throw Error(`Unknown ref "${a}"`);return await e.dblclickByBackendNodeId(l,o,s),t.snapshots.delete(i.targetId),`Double-clicked ${a}`})+`
|
|
6386
|
-
`,stderr:``,exitCode:0}},
|
|
6387
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6386
|
+
`,stderr:``,exitCode:0}},QL=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`hover requires a ref (e.g. e5)
|
|
6387
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),o=n.refToFrameId?.get(a);if(r&&o){let t=n.refToSelector.get(a);if(!t)throw Error(`Unknown ref "${a}" in iframe`);let r=t.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6388
6388
|
var el = document.querySelector(${JSON.stringify(r)});
|
|
6389
6389
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6390
6390
|
el.scrollIntoView({ block: 'center' });
|
|
6391
6391
|
el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
|
|
6392
6392
|
})()`),`Hovered ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);return await e.hoverByBackendNodeId(s),`Hovered ${a}`})+`
|
|
6393
|
-
`,stderr:``,exitCode:0}}
|
|
6394
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6393
|
+
`,stderr:``,exitCode:0}},$L=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`select requires <ref> <value>
|
|
6394
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n.slice(1).join(` `);return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),s=n.refToFrameId?.get(a);if(r&&s){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let c=r.split(`,`)[0].trim();return await e.evaluateInFrame(s,`(function() {
|
|
6395
6395
|
var el = document.querySelector(${JSON.stringify(c)});
|
|
6396
6396
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6397
6397
|
el.value = ${JSON.stringify(o)};
|
|
6398
6398
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6399
6399
|
})()`),t.snapshots.delete(i.targetId),`Selected "${o}" on ${a} (in iframe)`}let c=n.refToBackendNodeId.get(a);if(!c)throw Error(`Unknown ref "${a}"`);return await e.selectByBackendNodeId(c,o),t.snapshots.delete(i.targetId),`Selected "${o}" on ${a}`})+`
|
|
6400
|
-
`,stderr:``,exitCode:0}},
|
|
6401
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6400
|
+
`,stderr:``,exitCode:0}},eR=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`check requires a ref (e.g. e5)
|
|
6401
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),o=n.refToFrameId?.get(a);if(r&&o){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let s=r.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6402
6402
|
var el = document.querySelector(${JSON.stringify(s)});
|
|
6403
6403
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6404
6404
|
if (!el.checked) {
|
|
@@ -6407,8 +6407,8 @@ Options:
|
|
|
6407
6407
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
6408
6408
|
}
|
|
6409
6409
|
})()`),t.snapshots.delete(i.targetId),`Checked ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);let c=await e.setCheckedByBackendNodeId(s,!0);return c===`toggled`&&t.snapshots.delete(i.targetId),c===`already`?`${a} already checked`:`Checked ${a}`})+`
|
|
6410
|
-
`,stderr:``,exitCode:0}},
|
|
6411
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=
|
|
6410
|
+
`,stderr:``,exitCode:0}},tR=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`uncheck requires a ref (e.g. e5)
|
|
6411
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let{isIframe:r}=aL(a),o=n.refToFrameId?.get(a);if(r&&o){let r=n.refToSelector.get(a);if(!r)throw Error(`Unknown ref "${a}" in iframe`);let s=r.split(`,`)[0].trim();return await e.evaluateInFrame(o,`(function() {
|
|
6412
6412
|
var el = document.querySelector(${JSON.stringify(s)});
|
|
6413
6413
|
if (!el) throw new Error('Element not found in iframe for ref ${a}');
|
|
6414
6414
|
if (el.checked) {
|
|
@@ -6417,14 +6417,14 @@ Options:
|
|
|
6417
6417
|
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
|
6418
6418
|
}
|
|
6419
6419
|
})()`),t.snapshots.delete(i.targetId),`Unchecked ${a} (in iframe)`}let s=n.refToBackendNodeId.get(a);if(!s)throw Error(`Unknown ref "${a}"`);let c=await e.setCheckedByBackendNodeId(s,!1);return c===`toggled`&&t.snapshots.delete(i.targetId),c===`already`?`${a} already unchecked`:`Unchecked ${a}`})+`
|
|
6420
|
-
`,stderr:``,exitCode:0}},
|
|
6420
|
+
`,stderr:``,exitCode:0}},nR=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`drag requires <startRef> <endRef>
|
|
6421
6421
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o=n[1];return{stdout:await e.withTab(i.targetId,async()=>{let n=t.snapshots.get(i.targetId);if(!n)throw Error(`No snapshot available. Run "snapshot" first.`);let r=n.refToBackendNodeId.get(a),s=n.refToBackendNodeId.get(o);if(!r)throw Error(`Unknown ref "${a}"`);if(!s)throw Error(`Unknown ref "${o}"`);return await e.dragByBackendNodeIds(r,s),t.snapshots.delete(i.targetId),`Dragged ${a} to ${o}`})+`
|
|
6422
|
-
`,stderr:``,exitCode:0}};function
|
|
6422
|
+
`,stderr:``,exitCode:0}};function rR(e){return e===void 0?`left`:e===`left`||e===`right`||e===`middle`?e:{error:`Invalid button "${e}". Must be left, right, or middle.\n`}}function iR(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const aR={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,pdf:`application/pdf`,txt:`text/plain`,json:`application/json`,csv:`text/csv`,html:`text/html`,htm:`text/html`,xml:`application/xml`,zip:`application/zip`,mp4:`video/mp4`,mp3:`audio/mpeg`};function oR(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return aR[t]??`application/octet-stream`}const sR=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`mousemove requires <x> <y>
|
|
6423
6423
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseFloat(n[0]),o=parseFloat(n[1]);return isNaN(a)||isNaN(o)?{stdout:``,stderr:`x and y must be numbers
|
|
6424
|
-
`,exitCode:1}:(await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:a,y:o,button:`none`,modifiers:0},t)}),t.lastMousePosition.set(i.targetId,{x:a,y:o}),{stdout:`Mouse moved to (${a}, ${o})\n`,stderr:``,exitCode:0})},
|
|
6424
|
+
`,exitCode:1}:(await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:a,y:o,button:`none`,modifiers:0},t)}),t.lastMousePosition.set(i.targetId,{x:a,y:o}),{stdout:`Mouse moved to (${a}, ${o})\n`,stderr:``,exitCode:0})},cR=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=rR(n[0]);if(typeof a==`object`)return{stdout:``,stderr:a.error,exitCode:1};let o=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mousePressed`,button:a,clickCount:1,x:o.x,y:o.y,modifiers:0},t)}),{stdout:`Mouse button ${a} pressed\n`,stderr:``,exitCode:0}},lR=async({browser:e,state:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=rR(n[0]);if(typeof a==`object`)return{stdout:``,stderr:a.error,exitCode:1};let o=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,button:a,clickCount:1,x:o.x,y:o.y,modifiers:0},t)}),{stdout:`Mouse button ${a} released\n`,stderr:``,exitCode:0}},uR=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`mousewheel requires <dx> <dy>
|
|
6425
6425
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseFloat(n[0]),o=parseFloat(n[1]);if(isNaN(a)||isNaN(o))return{stdout:``,stderr:`dx and dy must be numbers
|
|
6426
|
-
`,exitCode:1};let s=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseWheel`,deltaX:a,deltaY:o,x:s.x,y:s.y,modifiers:0},t)}),{stdout:`Mouse wheel scrolled (dx=${a}, dy=${o})\n`,stderr:``,exitCode:0}},
|
|
6427
|
-
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=r[0],s=i.path,c=i.data,l=[];if(s){let e=await t.readFile(s),n=s.split(`/`).pop()??s,r=
|
|
6426
|
+
`,exitCode:1};let s=t.lastMousePosition.get(i.targetId)??{x:0,y:0};return await e.withTab(i.targetId,async t=>{await e.getTransport().send(`Input.dispatchMouseEvent`,{type:`mouseWheel`,deltaX:a,deltaY:o,x:s.x,y:s.y,modifiers:0},t)}),{stdout:`Mouse wheel scrolled (dx=${a}, dy=${o})\n`,stderr:``,exitCode:0}},dR=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`drop requires a ref (e.g. e5)
|
|
6427
|
+
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=r[0],s=i.path,c=i.data,l=[];if(s){let e=await t.readFile(s),n=s.split(`/`).pop()??s,r=oR(n),i=typeof e==`string`?new TextEncoder().encode(e):e;l.push({name:n,type:r,base64:iR(i)})}let u=[];if(c){let e=c.indexOf(`=`);if(e===-1)return{stdout:``,stderr:`--data format must be "mime/type=value"
|
|
6428
6428
|
`,exitCode:1};u.push({mimeType:c.slice(0,e),value:c.slice(e+1)})}return{stdout:await e.withTab(a.targetId,async t=>{let r=n.snapshots.get(a.targetId);if(!r)throw Error(`No snapshot available. Run "snapshot" first.`);let i=e.getTransport(),s=r.refToBackendNodeId.get(o);if(s){await i.send(`DOM.enable`,{},t);let e=await i.send(`DOM.resolveNode`,{backendNodeId:s},t),r=await i.send(`Runtime.callFunctionOn`,{objectId:e.object.objectId,functionDeclaration:`function(filesData, dataItems) {
|
|
6429
6429
|
var dt = new DataTransfer();
|
|
6430
6430
|
for (var i = 0; i < filesData.length; i++) {
|
|
@@ -6439,7 +6439,7 @@ Options:
|
|
|
6439
6439
|
this.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6440
6440
|
this.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6441
6441
|
return this.tagName;
|
|
6442
|
-
}`,arguments:[{value:l},{value:u}],returnByValue:!0},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`}let{isIframe:c}=
|
|
6442
|
+
}`,arguments:[{value:l},{value:u}],returnByValue:!0},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`}let{isIframe:c}=aL(o),d=r.refToFrameId?.get(o),f;if(c&&d){let e=r.refToSelector.get(o);if(!e)throw Error(`Unknown ref "${o}" in iframe`);f=e.split(`,`)[0].trim()}else{let e=r.refToSelector.get(o);if(!e)throw Error(`Unknown ref "${o}". Available: ${[...r.refToSelector.keys()].slice(0,10).join(`, `)}...`);f=e.split(`,`)[0].trim()}let p=JSON.stringify(l),m=JSON.stringify(u),h=`(function() {
|
|
6443
6443
|
var el = document.querySelector(${JSON.stringify(f)});
|
|
6444
6444
|
if (!el) throw new Error('Element not found for ref ${o}: ' + ${JSON.stringify(f)});
|
|
6445
6445
|
var dt = new DataTransfer();
|
|
@@ -6459,7 +6459,7 @@ Options:
|
|
|
6459
6459
|
el.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: dt }));
|
|
6460
6460
|
return true;
|
|
6461
6461
|
})()`,g=await i.send(`Runtime.evaluate`,{expression:h,returnByValue:!0,awaitPromise:!1},t);if(g.exceptionDetails){let e=g.exceptionDetails.exception?.description??g.exceptionDetails.text??`Drop failed`;throw Error(e)}return n.snapshots.delete(a.targetId),`Dropped onto ${o}`})+`
|
|
6462
|
-
`,stderr:``,exitCode:0}},
|
|
6462
|
+
`,stderr:``,exitCode:0}},fR=n(`playwright-teleport`),pR={origin:``,localStorage:{},sessionStorage:{}};function mR(e){let t=new Map;for(let n of e){let e=n.domain??`unknown`;t.set(e,(t.get(e)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]).map(([e,t])=>`${t} ${e}`).join(`, `)}function hR(e){return Object.keys(e.localStorage).length+Object.keys(e.sessionStorage).length}function gR(e){if(!e)return null;try{return new URL(e).origin}catch{return null}}function _R(e){try{return new URL(`/favicon.ico`,e).toString()}catch{return e}}function vR(e,t,n){let r=gR(t);if(t&&r===e)return t;let i=gR(n);return n&&i===e?n:e||(t??n)}async function yR(e,t){let n=await e.evaluate(`(() => {
|
|
6463
6463
|
const collect = (storage) => {
|
|
6464
6464
|
const items = {};
|
|
6465
6465
|
for (let i = 0; i < storage.length; i++) {
|
|
@@ -6473,7 +6473,7 @@ Options:
|
|
|
6473
6473
|
localStorage: collect(window.localStorage),
|
|
6474
6474
|
sessionStorage: collect(window.sessionStorage),
|
|
6475
6475
|
});
|
|
6476
|
-
})()`);if(typeof n!=`string`||n.length===0)return
|
|
6476
|
+
})()`);if(typeof n!=`string`||n.length===0)return fR.warn(`Teleport storage capture returned non-string result`,{label:t,type:typeof n}),pR;try{let e=JSON.parse(n);return{origin:typeof e.origin==`string`?e.origin:``,localStorage:e.localStorage??{},sessionStorage:e.sessionStorage??{}}}catch(e){return fR.warn(`Could not parse teleport storage snapshot`,{label:t,error:String(e)}),pR}}function bR(e){return`(() => {
|
|
6477
6477
|
const snapshot = ${JSON.stringify(e)};
|
|
6478
6478
|
if (!snapshot.origin || window.location.origin !== snapshot.origin) return;
|
|
6479
6479
|
const markerKey = '__slicc_teleport_storage_applied__:' + snapshot.origin;
|
|
@@ -6489,7 +6489,7 @@ Options:
|
|
|
6489
6489
|
apply(window.localStorage, snapshot.localStorage || {});
|
|
6490
6490
|
apply(window.sessionStorage, snapshot.sessionStorage || {});
|
|
6491
6491
|
try { window.sessionStorage.setItem(markerKey, '1'); } catch {}
|
|
6492
|
-
})();`}function
|
|
6492
|
+
})();`}function xR(e){return`(() => {
|
|
6493
6493
|
const snapshot = ${JSON.stringify(e)};
|
|
6494
6494
|
if (!snapshot.origin || globalThis.location.origin !== snapshot.origin) {
|
|
6495
6495
|
throw new Error('Teleport storage origin mismatch');
|
|
@@ -6507,88 +6507,88 @@ Options:
|
|
|
6507
6507
|
localStorageCount: Object.keys(snapshot.localStorage || {}).length,
|
|
6508
6508
|
sessionStorageCount: Object.keys(snapshot.sessionStorage || {}).length,
|
|
6509
6509
|
});
|
|
6510
|
-
})();`}async function
|
|
6510
|
+
})();`}async function SR(e,t,n){let r=hR(t);if(r===0)return;let i=await e.evaluate(xR(t));fR.info(`Applied teleport storage snapshot on current page`,{target:n,totalEntries:r,resultType:typeof i}),fR.debug(`Applied teleport storage snapshot details`,{target:n,origin:t.origin||`(unknown)`,totalEntries:r,resultType:typeof i})}async function CR(e,t,n,r){let i=hR(t);if(i===0)return null;let a=await e.sendCDP(`Page.addScriptToEvaluateOnNewDocument`,{source:bR(t)}),o=typeof a.identifier==`string`?a.identifier:null;return fR.info(`Installed teleport storage init script`,{target:r,totalEntries:i,hasIdentifier:!!o}),fR.debug(`Installed teleport storage init script details`,{target:r,origin:t.origin||`(unknown)`,localStorageCount:Object.keys(t.localStorage).length,sessionStorageCount:Object.keys(t.sessionStorage).length,hasIdentifier:!!o}),o?async()=>{try{await e.attachToPage(n),await e.sendCDP(`Page.removeScriptToEvaluateOnNewDocument`,{identifier:o})}catch(e){fR.warn(`Failed to remove teleport storage init script`,{target:r,error:String(e)})}}:null}async function wR(e){let t=await e.evaluate(`(() => JSON.stringify({
|
|
6511
6511
|
url: window.location.href,
|
|
6512
6512
|
title: document.title || '',
|
|
6513
6513
|
bodySnippet: document.body?.innerText?.replace(/\\s+/g, ' ').trim().slice(0, 500) || '(empty)',
|
|
6514
|
-
}))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function sR(e){return/callback|authorize\/resume|error/i.test(e)}async function cR(e,t,n){try{let r=await oR(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,JL.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){JL.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function lR(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),JL.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){JL.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}const $=n(`playwright-teleport`);function uR(){return null}async function dR(e,t){if($.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),$.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await cR(e,t,`timeout`)}catch(e){$.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await lR(t,`timeout`)}if(fR(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){$.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function fR(e){$.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function pR(e,t,n,r,i,a,o,s){if(a===`preview`)throw Error(`cannot teleport to a preview target (no Network.*)`);$.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),$.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);$.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&($.info(`Teleport start pattern matched on leader`),$.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),mR(e,t,c,a))}catch(e){$.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function mR(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,$.info(`Teleport triggered`),$.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=YL;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],$.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){$.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await tR(e,`leader`),$.info(`Captured leader storage for follower`,{totalEntries:ZL(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o)throw Error(`No follower selection available — not connected to a tray`);$.info(`Selected follower for teleport`),$.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,$.info(`Opened follower tab for teleport`),$.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),$.info(`Attached to follower tab for teleport`),$.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),$.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){$.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await aR(e,a,c,`follower`),$.info(`Navigating follower to intercepted auth URL`),$.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),$.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&dR(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,$.info(`Teleport waiting for follower auth redirect`),$.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,$.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,$.info(`Follower reached auth provider; waiting for return pattern`),$.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):$.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}$.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),sR(i)&&await cR(e,n,`waiting-for-return`),n.returnPattern.test(i)&&($.info(`Follower return pattern matched after auth`),$.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),yR(e,t,n,o))}catch(e){$.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){$.error(`Teleport trigger failed`,{error:String(e)}),await lR(n,`trigger-error`),n.phase=`done`,fR(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function hR(e,t){$.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(t.followerTargetId);let n;try{let t=await e.evaluate(`window.location.href`);n=typeof t==`string`?t:String(t),$.debug(`Captured final URL from follower`,{finalUrl:n})}catch(e){$.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);$.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){$.warn(`Could not read follower page content`,{error:String(e)})}let r=(await e.sendCDP(`Network.getCookies`)).cookies??[],i=r.length>0?XL(r):`none`;$.info(`Captured cookies from follower`,{count:r.length}),$.debug(`Captured cookies from follower details`,{count:r.length,domains:i});let a=YL;try{a=await tR(e,`follower`),$.info(`Captured follower storage for leader`,{totalEntries:ZL(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured follower storage for leader details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture follower storage`,{error:String(e)})}await cR(e,t,`capture`),await lR(t,`capture`);try{await e.closePage(t.followerTargetId),$.info(`Closed follower tab after teleport`),$.debug(`Closed follower tab after teleport details`,{followerTargetId:t.followerTargetId})}catch(e){$.warn(`Failed to close follower tab`,{error:String(e)})}return{cookies:r,followerStorage:a,finalUrl:n}}async function gR(e,t,n,r,i){try{await e.navigate(r),await iR(e,n,`leader`),i&&i!==r&&await e.navigate(i)}catch(a){$.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(a)}),$.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:r,landingUrl:i,error:String(a)});let o=await aR(e,n,t,`leader`);try{i&&await e.navigate(i)}finally{await o?.()}}}async function _R(e,t,n,r,i){let a=t.leaderTargetId,o=await aR(e,n,a,`leader`);try{r&&($.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:ZL(n)}),$.debug(`Navigating leader after auth-state injection details`,{landingUrl:r,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:n.origin||`(unknown)`,storageEntries:ZL(n)}),await e.navigate(r))}finally{await o?.()}}async function vR(e,t,n,r,i){let a=t.leaderTargetId,o=r.origin||``,s=eR(o,t.originalLeaderUrl,i),c=QL(t.originalLeaderUrl),l=!!o&&c!==o,u=l?$L(o):null;return a?(await e.attachToPage(a),n.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:n}),$.info(`Injected cookies into leader tab`,{count:n.length}),$.debug(`Injected cookies into leader tab details`,{count:n.length,leaderTargetId:a})),l&&u?($.info(`Hydrating leader storage origin before landing`,{storageEntries:ZL(r)}),$.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:u,landingUrl:s,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:o,storageEntries:ZL(r)}),await gR(e,a,r,u,s)):await _R(e,t,r,s,i),s):($.warn(`No leader tab available for auth-state injection`),s)}async function yR(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,$.info(`Capturing auth state from follower`),$.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{let{cookies:t,followerStorage:i,finalUrl:a}=await hR(e,n),o=ZL(i),s=await vR(e,n,t,i,a);n.phase=`done`,fR(n);let c=t.length>0?` (${XL(t)})`:``,l=o>0?` + ${o} storage entr${o===1?`y`:`ies`}`:``,u=s?` (navigated to ${s})`:``,d=`Teleported ${t.length} cookie(s)${c}${l} from ${r}${u}`;$.info(`Teleport completed successfully`,{cookieCount:t.length,storageEntries:o,landed:!!s}),$.debug(`Teleport completed successfully details`,{result:d}),n.resolveBlock?.(d)}catch(e){$.error(`Teleport auth-state capture failed`,{error:String(e)}),await lR(n,`capture-error`),n.phase=`done`,fR(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}const bR=n(`playwright`),xR=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`goto requires a URL
|
|
6515
|
-
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};await e.withTab(a.targetId,async()=>(await e.navigate(r[0]),!0)),n.snapshots.delete(a.targetId);let o=i[`teleport-start`],s=i[`teleport-return`];if(o&&s){
|
|
6516
|
-
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Navigated to ${r[0]}\n`,stderr:``,exitCode:0}},
|
|
6517
|
-
`,stderr:``,exitCode:0})},
|
|
6518
|
-
`,stderr:``,exitCode:0})},
|
|
6519
|
-
`,stderr:``,exitCode:0})},
|
|
6520
|
-
`,exitCode:1}:(await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Network.enable`,{},t),await n.send(`Network.emulateNetworkConditions`,{offline:i===`offline`,latency:0,downloadThroughput:-1,uploadThroughput:-1},t)}),{stdout:`Network set to ${i}\n`,stderr:``,exitCode:0})},
|
|
6514
|
+
}))()`);if(typeof t!=`string`||t.length===0)return{url:``,title:``,bodySnippet:`(unavailable)`};try{let e=JSON.parse(t);return{url:typeof e.url==`string`?e.url:``,title:typeof e.title==`string`?e.title:``,bodySnippet:typeof e.bodySnippet==`string`&&e.bodySnippet.length>0?e.bodySnippet:`(empty)`}}catch{return{url:``,title:``,bodySnippet:`(unparseable)`}}}function TR(e){return/callback|authorize\/resume|error/i.test(e)}async function ER(e,t,n){try{let r=await wR(e),i=`${n}:${r.url}:${r.title}`;if(t.lastFollowerDiagnosticKey===i)return;t.lastFollowerDiagnosticKey=i,fR.debug(`Teleport follower diagnostics`,{reason:n,url:r.url,title:r.title,bodySnippet:r.bodySnippet})}catch(e){fR.warn(`Could not capture teleport follower diagnostics`,{reason:n,error:String(e)})}}async function DR(e,t){let n=e.removeFollowerStorageScript;if(n){e.removeFollowerStorageScript=null;try{await n(),fR.info(`Removed follower teleport storage init script`,{reason:t})}catch(e){fR.warn(`Failed to remove follower teleport storage init script`,{reason:t,error:String(e)})}}}const $=n(`playwright-teleport`);function OR(){return null}async function kR(e,t){if($.warn(`Teleport timed out`,{timeoutMs:t.timeoutMs,phase:t.phase}),$.debug(`Teleport timeout details`,{timeoutMs:t.timeoutMs,phase:t.phase,followerTargetId:t.followerTargetId}),t.phase=`timedOut`,t.followerTargetId){try{await e.attachToPage(t.followerTargetId),await ER(e,t,`timeout`)}catch(e){$.warn(`Could not attach to follower for timeout diagnostics`,{error:String(e)})}await DR(t,`timeout`)}if(AR(t),t.followerTargetId)try{await e.closePage(t.followerTargetId)}catch(e){$.warn(`Failed to close follower tab after timeout`,{error:String(e)})}t.rejectBlock?.(Error(`Teleport timed out after ${Math.round(t.timeoutMs/1e3)}s — human did not complete auth`))}function AR(e){$.info(`Cleaning up teleport watcher`,{phase:e.phase,hadPoll:!!e.pollInterval,hadTimeout:!!e.timeoutTimer,hadListener:!!e.cleanupListener}),e.pollInterval&&=(clearInterval(e.pollInterval),void 0),e.timeoutTimer&&=(clearTimeout(e.timeoutTimer),void 0),e.cleanupListener&&=(e.cleanupListener(),void 0)}function jR(e,t,n,r,i,a,o,s){if(a===`preview`)throw Error(`cannot teleport to a preview target (no Network.*)`);$.info(`Arming teleport watcher`,{timeoutMs:i,runtimeSelection:a?`explicit`:`auto`}),$.debug(`Arming teleport watcher details`,{startPattern:n.source,returnPattern:r.source,timeoutMs:i,runtimeId:a??`auto`,originalUrl:o});let c={startPattern:n,returnPattern:r,timeoutMs:i,runtimeId:a,phase:`armed`,leaderTargetId:s,originalLeaderUrl:o};return c.completionPromise=new Promise((e,t)=>{c.resolveBlock=e,c.rejectBlock=t}),c.completionPromise.catch(()=>{}),c.pollInterval=setInterval(async()=>{if(c.phase!==`armed`)return;let r=c.leaderTargetId;if(r)try{await e.attachToPage(r);let i=await e.evaluate(`window.location.href`),a=typeof i==`string`?i:String(i);$.debug(`Polling leader tab URL`,{targetId:r,href:a,startPattern:n.source}),n.test(a)&&($.info(`Teleport start pattern matched on leader`),$.debug(`Teleport start pattern matched on leader details`,{targetId:r,href:a,startPattern:n.source}),MR(e,t,c,a))}catch(e){$.warn(`Error polling leader tab URL`,{targetId:r,error:String(e)})}},1e3),s&&t.teleportWatchers.set(s,c),c}async function MR(e,t,n,r){if(n.phase===`armed`){n.phase=`teleporting`,$.info(`Teleport triggered`),$.debug(`Teleport trigger details`,{triggerUrl:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0);try{let i=[],a=pR;try{i=(await e.sendCDP(`Network.getCookies`,{})).cookies??[],$.info(`Captured leader cookies for follower`,{count:i.length})}catch(e){$.warn(`Could not capture leader cookies`,{error:String(e)})}try{a=await yR(e,`leader`),$.info(`Captured leader storage for follower`,{totalEntries:hR(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured leader storage for follower details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture leader storage`,{error:String(e)})}let o=n.runtimeId;if(!o)throw Error(`No follower selection available — not connected to a tray`);$.info(`Selected follower for teleport`),$.debug(`Selected follower for teleport details`,{runtimeId:o});let s=await e.createRemotePage(o,`about:blank`),c=s.includes(`:`)?s:`${o}:${s}`;if(n.followerTargetId=c,$.info(`Opened follower tab for teleport`),$.debug(`Opened follower tab for teleport details`,{followerTargetId:c}),await e.attachToPage(c),$.info(`Attached to follower tab for teleport`),$.debug(`Attached to follower tab for teleport details`,{followerTargetId:c}),await e.sendCDP(`Page.enable`),i.length>0)try{await e.sendCDP(`Network.setCookies`,{cookies:i}),$.info(`Injected leader cookies into follower`,{count:i.length})}catch(e){$.warn(`Could not inject leader cookies into follower`,{error:String(e)})}let l=r;n.removeFollowerStorageScript=await CR(e,a,c,`follower`),$.info(`Navigating follower to intercepted auth URL`),$.debug(`Navigating follower to intercepted auth URL details`,{url:l,originalLeaderUrl:n.originalLeaderUrl,triggerUrl:r,storageOrigin:a.origin||`(unknown)`}),await e.sendCDP(`Page.navigate`,{url:l}),$.info(`Starting teleport timeout timer`,{timeoutMs:n.timeoutMs}),n.timeoutTimer=setTimeout(()=>{(n.phase===`teleporting`||n.phase===`waitingForAuth`||n.phase===`waitingForReturn`)&&kR(e,n)},n.timeoutMs),n.phase=`waitingForAuth`,$.info(`Teleport waiting for follower auth redirect`),$.debug(`Teleport waiting for follower auth redirect details`,{startPattern:n.startPattern.source}),n.pollInterval=setInterval(async()=>{if(!(n.phase!==`waitingForAuth`&&n.phase!==`waitingForReturn`))try{await e.attachToPage(c);let r=await e.evaluate(`window.location.href`),i=typeof r==`string`?r:String(r);if(!i)return;if(n.lastFollowerUrl!==i&&(n.lastFollowerUrl=i,$.debug(`Follower teleport navigation`,{href:i,phase:n.phase})),n.phase===`waitingForAuth`){n.startPattern.test(i)?(n.phase=`waitingForReturn`,$.info(`Follower reached auth provider; waiting for return pattern`),$.debug(`Follower reached auth provider details`,{href:i,startPattern:n.startPattern.source})):$.debug(`Waiting for auth redirect on follower`,{href:i,startPattern:n.startPattern.source});return}$.debug(`Polling follower tab URL for return`,{href:i,returnPattern:n.returnPattern.source}),TR(i)&&await ER(e,n,`waiting-for-return`),n.returnPattern.test(i)&&($.info(`Follower return pattern matched after auth`),$.debug(`Follower return pattern matched after auth details`,{href:i,returnPattern:n.returnPattern.source}),LR(e,t,n,o))}catch(e){$.warn(`Error polling follower tab URL`,{error:String(e)})}},1e3)}catch(e){$.error(`Teleport trigger failed`,{error:String(e)}),await DR(n,`trigger-error`),n.phase=`done`,AR(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}async function NR(e,t){$.info(`Waiting for redirect chain to settle (2s)`),await new Promise(e=>setTimeout(e,2e3)),await e.attachToPage(t.followerTargetId);let n;try{let t=await e.evaluate(`window.location.href`);n=typeof t==`string`?t:String(t),$.debug(`Captured final URL from follower`,{finalUrl:n})}catch(e){$.warn(`Could not read follower URL (may be mid-navigation)`,{error:String(e)})}try{let t=await e.evaluate(`document.body?.innerText?.substring(0, 500) || "(empty)"`);$.debug(`Follower page content at capture time`,{bodyText:t})}catch(e){$.warn(`Could not read follower page content`,{error:String(e)})}let r=(await e.sendCDP(`Network.getCookies`)).cookies??[],i=r.length>0?mR(r):`none`;$.info(`Captured cookies from follower`,{count:r.length}),$.debug(`Captured cookies from follower details`,{count:r.length,domains:i});let a=pR;try{a=await yR(e,`follower`),$.info(`Captured follower storage for leader`,{totalEntries:hR(a),localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length}),$.debug(`Captured follower storage for leader details`,{origin:a.origin||`(unknown)`,localStorageCount:Object.keys(a.localStorage).length,sessionStorageCount:Object.keys(a.sessionStorage).length})}catch(e){$.warn(`Could not capture follower storage`,{error:String(e)})}await ER(e,t,`capture`),await DR(t,`capture`);try{await e.closePage(t.followerTargetId),$.info(`Closed follower tab after teleport`),$.debug(`Closed follower tab after teleport details`,{followerTargetId:t.followerTargetId})}catch(e){$.warn(`Failed to close follower tab`,{error:String(e)})}return{cookies:r,followerStorage:a,finalUrl:n}}async function PR(e,t,n,r,i){try{await e.navigate(r),await SR(e,n,`leader`),i&&i!==r&&await e.navigate(i)}catch(a){$.warn(`Direct leader origin hydration failed, falling back to init-script replay`,{error:String(a)}),$.debug(`Direct leader origin hydration fallback details`,{hydrationUrl:r,landingUrl:i,error:String(a)});let o=await CR(e,n,t,`leader`);try{i&&await e.navigate(i)}finally{await o?.()}}}async function FR(e,t,n,r,i){let a=t.leaderTargetId,o=await CR(e,n,a,`leader`);try{r&&($.info(`Navigating leader after auth-state injection`,{hasLandingUrl:!0,storageEntries:hR(n)}),$.debug(`Navigating leader after auth-state injection details`,{landingUrl:r,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:n.origin||`(unknown)`,storageEntries:hR(n)}),await e.navigate(r))}finally{await o?.()}}async function IR(e,t,n,r,i){let a=t.leaderTargetId,o=r.origin||``,s=vR(o,t.originalLeaderUrl,i),c=gR(t.originalLeaderUrl),l=!!o&&c!==o,u=l?_R(o):null;return a?(await e.attachToPage(a),n.length>0&&(await e.sendCDP(`Network.setCookies`,{cookies:n}),$.info(`Injected cookies into leader tab`,{count:n.length}),$.debug(`Injected cookies into leader tab details`,{count:n.length,leaderTargetId:a})),l&&u?($.info(`Hydrating leader storage origin before landing`,{storageEntries:hR(r)}),$.debug(`Hydrating leader storage origin before landing details`,{hydrationUrl:u,landingUrl:s,originalLeaderUrl:t.originalLeaderUrl,finalUrl:i,leaderTargetId:a,storageOrigin:o,storageEntries:hR(r)}),await PR(e,a,r,u,s)):await FR(e,t,r,s,i),s):($.warn(`No leader tab available for auth-state injection`),s)}async function LR(e,t,n,r){if(!(n.phase!==`teleporting`&&n.phase!==`waitingForReturn`)){n.phase=`capturing`,$.info(`Capturing auth state from follower`),$.debug(`Capturing auth state from follower details`,{followerTargetId:n.followerTargetId,runtimeId:r}),n.pollInterval&&=(clearInterval(n.pollInterval),void 0),n.timeoutTimer&&=(clearTimeout(n.timeoutTimer),void 0);try{let{cookies:t,followerStorage:i,finalUrl:a}=await NR(e,n),o=hR(i),s=await IR(e,n,t,i,a);n.phase=`done`,AR(n);let c=t.length>0?` (${mR(t)})`:``,l=o>0?` + ${o} storage entr${o===1?`y`:`ies`}`:``,u=s?` (navigated to ${s})`:``,d=`Teleported ${t.length} cookie(s)${c}${l} from ${r}${u}`;$.info(`Teleport completed successfully`,{cookieCount:t.length,storageEntries:o,landed:!!s}),$.debug(`Teleport completed successfully details`,{result:d}),n.resolveBlock?.(d)}catch(e){$.error(`Teleport auth-state capture failed`,{error:String(e)}),await DR(n,`capture-error`),n.phase=`done`,AR(n),n.rejectBlock?.(e instanceof Error?e:Error(String(e)))}}}const RR=n(`playwright`),zR=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`goto requires a URL
|
|
6515
|
+
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};await e.withTab(a.targetId,async()=>(await e.navigate(r[0]),!0)),n.snapshots.delete(a.targetId);let o=i[`teleport-start`],s=i[`teleport-return`];if(o&&s){RR.info(`Arming teleport via goto/navigate flags`),RR.debug(`Arming teleport via goto/navigate flags details`,{targetId:a.targetId,startPattern:o,returnPattern:s});let t,c;try{t=new RegExp(o)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-start: ${o}\n`,exitCode:1}}try{c=new RegExp(s)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-return: ${s}\n`,exitCode:1}}let l=i.timeout?parseInt(i.timeout,10):300,u=n.teleportWatchers.get(a.targetId);u&&(AR(u),n.teleportWatchers.delete(a.targetId)),jR(e,n,t,c,l*1e3,i[`teleport-runtime`],r[0],a.targetId)}if(i.discover===`true`){let{browseShWarning:e,...n}=await RL(r[0],{discover:!0,fs:t}),i={action:`navigate`,targetId:a.targetId,source:`auxiliary-fetch`,...n};return{stdout:JSON.stringify(i,null,2)+`
|
|
6516
|
+
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Navigated to ${r[0]}\n`,stderr:``,exitCode:0}},BR=async({browser:e,state:t,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`history.back()`)}),t.snapshots.delete(r.targetId),{stdout:`Navigated back
|
|
6517
|
+
`,stderr:``,exitCode:0})},VR=async({browser:e,state:t,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`history.forward()`)}),t.snapshots.delete(r.targetId),{stdout:`Navigated forward
|
|
6518
|
+
`,stderr:``,exitCode:0})},HR=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:(await e.withTab(n.targetId,async()=>{await e.sendCDP(`Page.reload`)}),{stdout:`Reloaded
|
|
6519
|
+
`,stderr:``,exitCode:0})},UR=async({browser:e,flags:t,positional:n})=>{let r=Q(t);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n[0];return i!==`online`&&i!==`offline`?{stdout:``,stderr:`network-state-set requires "online" or "offline"
|
|
6520
|
+
`,exitCode:1}:(await e.withTab(r.targetId,async t=>{let n=e.getTransport();await n.send(`Network.enable`,{},t),await n.send(`Network.emulateNetworkConditions`,{offline:i===`offline`,latency:0,downloadThroughput:-1,uploadThroughput:-1},t)}),{stdout:`Network set to ${i}\n`,stderr:``,exitCode:0})},WR=[`image/`,`font/`,`text/css`,`application/javascript`,`text/javascript`];function GR(e,t){if(e&&WR.some(t=>e.startsWith(t)))return!0;try{let e=new URL(t).pathname;return/\.(png|jpe?g|gif|webp|svg|ico|woff2?|ttf|eot|otf|css|js|mjs)$/i.test(e)}catch{return!1}}function KR(e,t,n,r){if(e.networkCleanup.has(n))return;e.networkRequests.set(n,[]),e.networkRequestIndex.set(n,new Map);let i=1,a=t=>{if(t.sessionId!==r)return;let a=t.requestId,o=t.request;if(!o)return;let s=e.networkRequests.get(n),c=e.networkRequestIndex.get(n);if(!s||!c)return;let l=o.url??``,u={index:i++,requestId:a,method:o.method??`GET`,url:l,requestHeaders:o.headers??{},requestBody:o.postData==null?null:String(o.postData),status:null,responseHeaders:null,responseBody:null,mimeType:null,isStatic:GR(null,l),timestamp:Date.now()};if(s.push(u),c.set(a,u),s.length>500){let e=s.splice(0,s.length-500);for(let t of e)c.delete(t.requestId)}},o=t=>{if(t.sessionId!==r)return;let i=t.requestId,a=t.response;if(!a)return;let o=e.networkRequestIndex.get(n)?.get(i);o&&(o.status=a.status??null,o.responseHeaders=a.headers??null,o.mimeType=a.mimeType??null,o.isStatic=GR(o.mimeType,o.url))},s=i=>{if(i.sessionId!==r)return;let a=i.requestId,o=e.networkRequestIndex.get(n)?.get(a);!o||o.isStatic||o.responseBody!==null||t.send(`Network.getResponseBody`,{requestId:a},r).then(e=>{let t=e;t&&(o.responseBody=t.body??null)}).catch(()=>{})};t.on(`Network.requestWillBeSent`,a),t.on(`Network.responseReceived`,o),t.on(`Network.loadingFinished`,s),e.networkCleanup.set(n,()=>{t.off(`Network.requestWillBeSent`,a),t.off(`Network.responseReceived`,o),t.off(`Network.loadingFinished`,s)})}function qR(e,t,n){let r=parseInt(n,10);return!Number.isFinite(r)||r<1?null:(e.networkRequests.get(t)??[]).find(e=>e.index===r)??null}const JR=async({browser:e,state:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};t.networkCleanup.has(r.targetId)||await e.withTab(r.targetId,async n=>{let i=e.getTransport();await i.send(`Network.enable`,{},n),KR(t,i,r.targetId,n)});let i=n.static===`true`,a=n.filter,o=n.clear===`true`,s=t.networkRequests.get(r.targetId)??[];if(i||(s=s.filter(e=>!e.isStatic)),a){let e;try{e=new RegExp(a)}catch{return{stdout:``,stderr:`Invalid filter regex: ${a}\n`,exitCode:1}}s=s.filter(t=>e.test(t.url))}return o&&(t.networkRequests.set(r.targetId,[]),t.networkRequestIndex.set(r.targetId,new Map)),s.length===0?{stdout:`No requests
|
|
6521
6521
|
`,stderr:``,exitCode:0}:{stdout:s.map(e=>`${e.index} ${e.method} ${e.url} → ${e.status??`pending`}`).join(`
|
|
6522
6522
|
`)+`
|
|
6523
|
-
`,stderr:``,exitCode:0}},
|
|
6523
|
+
`,stderr:``,exitCode:0}},YR=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),KR(t,r,a.targetId,n)});let o=n[0]??``,s=qR(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};let c=[`Method: ${s.method}`,`URL: ${s.url}`,`Status: ${s.status??`pending`}`,``,`Request Headers:`,...Object.entries(s.requestHeaders).map(([e,t])=>` ${e}: ${t}`)];if(s.requestBody!==null&&c.push(``,`Request Body: ${s.requestBody}`),s.responseHeaders!==null&&(c.push(``,`Response Headers:`),c.push(...Object.entries(s.responseHeaders).map(([e,t])=>` ${e}: ${t}`))),s.responseBody!==null){let e=s.responseBody,t=e.length>4096?e.slice(0,4096)+`
|
|
6524
6524
|
... (truncated)`:e;c.push(``,`Response Body:\n${t}`)}let l=c.join(`
|
|
6525
6525
|
`)+`
|
|
6526
|
-
`,u=r.filename;return u?(await i.writeFile(u,l),{stdout:`Saved to ${u}\n`,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}},
|
|
6526
|
+
`,u=r.filename;return u?(await i.writeFile(u,l),{stdout:`Saved to ${u}\n`,stderr:``,exitCode:0}):{stdout:l,stderr:``,exitCode:0}},XR=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),KR(t,r,a.targetId,n)});let o=n[0]??``,s=qR(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};let c=Object.entries(s.requestHeaders).map(([e,t])=>`${e}: ${t}`).join(`
|
|
6527
6527
|
`)+`
|
|
6528
|
-
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},
|
|
6528
|
+
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},ZR=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),KR(t,r,a.targetId,n)});let o=n[0]??``,s=qR(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.requestBody===null)return{stdout:`(no request body)
|
|
6529
6529
|
`,stderr:``,exitCode:0};let c=r.filename;return c?(await i.writeFile(c,s.requestBody),{stdout:`Saved to ${c}\n`,stderr:``,exitCode:0}):{stdout:s.requestBody+`
|
|
6530
|
-
`,stderr:``,exitCode:0}},
|
|
6530
|
+
`,stderr:``,exitCode:0}},QR=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),KR(t,r,a.targetId,n)});let o=n[0]??``,s=qR(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.responseHeaders===null)return{stdout:`(response not yet received)
|
|
6531
6531
|
`,stderr:``,exitCode:0};let c=Object.entries(s.responseHeaders).map(([e,t])=>`${e}: ${t}`).join(`
|
|
6532
6532
|
`)+`
|
|
6533
|
-
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}}
|
|
6533
|
+
`,l=r.filename;return l?(await i.writeFile(l,c),{stdout:`Saved to ${l}\n`,stderr:``,exitCode:0}):{stdout:c,stderr:``,exitCode:0}},$R=async({browser:e,state:t,positional:n,flags:r,fs:i})=>{let a=Q(r);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};t.networkCleanup.has(a.targetId)||await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`Network.enable`,{},n),KR(t,r,a.targetId,n)});let o=n[0]??``,s=qR(t,a.targetId,o);if(!s)return{stdout:``,stderr:`No request at index ${o}\n`,exitCode:1};if(s.responseBody===null)return{stdout:`(response body not yet available)
|
|
6534
6534
|
`,stderr:``,exitCode:0};let c=r.filename,l=s.mimeType!==null&&!s.mimeType.startsWith(`text/`)&&!s.mimeType.includes(`json`)&&!s.mimeType.includes(`javascript`)&&!s.mimeType.includes(`xml`);if(c){if(l)try{let e=atob(s.responseBody),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);await i.writeFile(c,t)}catch{await i.writeFile(c,s.responseBody)}else await i.writeFile(c,s.responseBody);return{stdout:`Saved to ${c}\n`,stderr:``,exitCode:0}}if(l)try{return{stdout:`[binary body, ${atob(s.responseBody).length} bytes]\n`,stderr:``,exitCode:0}}catch{}let u=s.responseBody;return{stdout:(u.length>4096?u.slice(0,4096)+`
|
|
6535
6535
|
... (truncated)`:u)+`
|
|
6536
|
-
`,stderr:``,exitCode:0}},
|
|
6537
|
-
`)){c.push(u);let t=u.match(/^(\s*)- iframe\s/);if(!t)continue;let d=u.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=
|
|
6538
|
-
`)}catch{return t}}async function
|
|
6539
|
-
`);return t?.noIframes||(l=await
|
|
6540
|
-
`)}}const
|
|
6541
|
-
`,exitCode:1};let n=t[0];return e.harRecorder?{stdout:`Recording stopped. HAR files saved to ${await e.harRecorder.stopRecording(n)}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Recording not found: ${n}\n`,exitCode:1}},
|
|
6542
|
-
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o={pattern:a,regex:
|
|
6536
|
+
`,stderr:``,exitCode:0}},ez=n(`har-recorder`);var tz=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}`),ez.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=>{ez.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 nz(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return ez.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 ez.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)),ez.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 ez.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 nz(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){ez.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return ez.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}const rz=n(`playwright`);function iz(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`)}function az(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}const oz=[`none`,`presentation`,`generic`,`rootwebarea`],sz=[`textbox`,`button`,`link`,`checkbox`,`radio`];function cz(e,t){return oz.includes(e)?!1:!!t||sz.includes(e)}function lz(e,t){let n=az(t);return e===`button`&&t?[`button[aria-label="${n}"]`,`button[title="${n}"]`,`[role="button"][aria-label="${n}"]`,`[role="button"][title="${n}"]`,`input[type="button"][value="${n}"]`,`input[type="submit"][value="${n}"]`,`input[type="reset"][value="${n}"]`].join(`, `):e===`link`&&t?`a[aria-label="${n}"], a[title="${n}"], [role="link"][aria-label="${n}"], [role="link"][title="${n}"]`:e===`textbox`?t?`input[aria-label="${n}"], textarea[aria-label="${n}"], [contenteditable][aria-label="${n}"], input[placeholder="${n}"], textarea[placeholder="${n}"], [contenteditable][placeholder="${n}"], input[title="${n}"], textarea[title="${n}"], [contenteditable][title="${n}"]`:`input, textarea, [contenteditable]`:e===`checkbox`?`input[type="checkbox"]`:e===`radio`?`input[type="radio"]`:t?`[aria-label="${n}"], [title="${n}"]`:`[role="${e}"]`}function uz(e,t,n,r,i=``,a=``){let o=[],s=_r(e.role,`unknown`).toLowerCase(),c=_r(e.name),l=_r(e.value),u=``;cz(s,c)&&(u=a+`e${++r.value}`,e.backendNodeId&&n.set(u,e.backendNodeId),t.set(u,lz(s,c)));let d=`${i}- ${s}`;if(c&&(d+=` "${iz(c)}"`),u&&(d+=` [ref=${u}]`),l&&(d+=`: "${iz(l)}"`),o.push(d),e.children)for(let s of e.children)o.push(...uz(s,t,n,r,i+` `,a));return o}async function dz(e,t){if(t.appTabId)return;let n=await e.listPages(),r=await fz(),i=n.find(e=>e.url.startsWith(r)&&!e.url.includes(`/preview/`));i&&(t.appTabId=i.targetId)}async function fz(){if(typeof window<`u`)return window.location.origin;let e=He();if(e)try{let t=await e.call(`page-info`,void 0,{timeoutMs:2e3});if(t.origin)return t.origin}catch{}return`http://localhost:5710`}function pz(e,t){return t===e.appTabId}function mz(e){let t=e.url.trim(),n=e.title.trim();return n===`Omnibox Popup`||t.startsWith(`chrome://`)||t.startsWith(`chrome-search://`)||t.startsWith(`chrome-untrusted://`)||t.startsWith(`devtools://`)||t.length===0&&/popup$/i.test(n)}function hz(e,t){return!pz(e,t.targetId)&&!mz(t)}function gz(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function _z(e,t){await dz(e,t);let n;if(typeof e.listAllTargets==`function`){n=await e.listAllTargets();let t=gz()?He():null;if(t)try{let{targets:e}=await t.call(`list-remote-targets`,void 0,{timeoutMs:3e3}),r=new Set(n.map(e=>e.targetId));for(let t of e)r.has(t.targetId)||(r.add(t.targetId),n.push({targetId:t.targetId,title:t.title,url:t.url}))}catch(e){rz.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}}else n=await e.listPages();return n.filter(e=>hz(t,e))}function vz(e,t){try{let n=new URL(e,t);return n.origin+n.pathname.replace(/\/$/,``)+n.search}catch{return null}}function yz(e,t,n,r){let i=vz(t,n);return e.find(e=>{if(r.has(e.frameId))return!1;let n=vz(e.url);return n!==null&&i!==null?n===i:e.url===t})}async function bz(e,t,n,r,i,a,o){try{let s=await e.getAccessibilityTreeForFrame(t),c=new Map,l=new Map,u=uz(s,c,l,{value:0},n,r);for(let[e,n]of c)i.set(e,n),o.set(e,t);for(let[e,n]of l)a.set(e,n),o.set(e,t);return u}catch{return[]}}async function xz(e,t,n,r,i,a){if(typeof e.getFrameTree!=`function`)return t;try{let o=(await e.getFrameTree()).filter(e=>e.parentFrameId);if(o.length===0)return t;let s=0,c=[],l=new Set;for(let u of t.split(`
|
|
6537
|
+
`)){c.push(u);let t=u.match(/^(\s*)- iframe\s/);if(!t)continue;let d=u.match(/:\s*"([^"]+)"\s*$/);if(!d)continue;let f=yz(o,d[1],n,l);f&&(l.add(f.frameId),s++,c.push(...await bz(e,f.frameId,t[1]+` `,`f${s}`,r,i,a)))}return c.join(`
|
|
6538
|
+
`)}catch{return t}}async function Sz(e,t){let n=await e.evaluate(`JSON.stringify({ url: location.href, title: document.title })`),{url:r,title:i}=JSON.parse(n),a=await e.getAccessibilityTree(),o=new Map,s=new Map,c=new Map,l=uz(a,o,s,{value:0}).join(`
|
|
6539
|
+
`);return t?.noIframes||(l=await xz(e,l,r,o,s,c)),{url:r,title:i,text:l,refToSelector:o,refToBackendNodeId:s,refToFrameId:c}}async function Cz(e,t,n,r){await e.attachToPage(n);let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:l}=await Sz(e,r),u={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:l,content:o,timestamp:Date.now()};return t.snapshots.set(n,u),{snapshot:u,output:[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
6540
|
+
`)}}const wz=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=r[0]||`about:blank`,o=i.filter;await dz(e,n);let s=await e.createPage(a),c=e.getTransport(),l=(await c.send(`Target.attachToTarget`,{targetId:s,flatten:!0})).sessionId;n.harRecorder||=new tz(c,t);let u=await n.harRecorder.startRecording(s,l,o);return{stdout:`Recording started (targetId: ${s}, recordingId: ${u}) at ${a}\nHAR saved to /recordings/${u}/\n`,stderr:``,exitCode:0}},Tz=async({state:e,positional:t})=>{if(t.length===0)return{stdout:``,stderr:`stop-recording requires a recordingId
|
|
6541
|
+
`,exitCode:1};let n=t[0];return e.harRecorder?{stdout:`Recording stopped. HAR files saved to ${await e.harRecorder.stopRecording(n)}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`Recording not found: ${n}\n`,exitCode:1}},Ez=n(`playwright-route`);function Dz(e){let t=new TextEncoder().encode(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function Oz(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*\*/g,`@@`).replace(/\*/g,`[^/]*`).replace(/@@/g,`.*`);return RegExp(`^${t}$`)}async function kz(e,t,n){await e.withTab(n,async r=>{let i=e.getTransport();await i.send(`Fetch.enable`,{patterns:[{urlPattern:`*`,requestStage:`Request`}]},r);let a=async e=>{if(e.sessionId!==r)return;let{requestId:a,request:o}=e,s=(t.routes.get(n)??[]).find(e=>e.regex.test(o.url));if(!s){await i.send(`Fetch.continueRequest`,{requestId:a},r).catch(e=>{Ez.warn(`Fetch.continueRequest failed — intercepted request may hang`,{requestId:a,err:e})});return}let c=[{name:`Content-Type`,value:s.contentType},...Object.entries(s.headers).map(([e,t])=>({name:e,value:t}))];await i.send(`Fetch.fulfillRequest`,{requestId:a,responseCode:s.status,responseHeaders:c,body:s.body?Dz(s.body):void 0},r).catch(e=>{Ez.warn(`Fetch.fulfillRequest failed`,{requestId:a,url:o.url,err:e})})};t.routeCleanup.set(n,()=>{i.off(`Fetch.requestPaused`,a),i.send(`Fetch.disable`,{},r).catch(()=>void 0)}),i.on(`Fetch.requestPaused`,a)})}const Az=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`route requires a URL pattern
|
|
6542
|
+
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o={pattern:a,regex:Oz(a),status:r.status?parseInt(r.status,10):200,body:r.body??``,contentType:r[`content-type`]??`text/plain`,headers:{}};if(r.header){r.header.includes(`,`)&&Ez.warn(`--header value contains comma — only last segment used. Use separate route calls for multiple headers.`);for(let e of r.header.split(`,`)){let t=e.indexOf(`:`);if(t>0){let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();o.headers[n]=r}}}t.routeCleanup.has(i.targetId)||(t.routes.has(i.targetId)||t.routes.set(i.targetId,[]),await kz(e,t,i.targetId));let s=t.routes.get(i.targetId)??[];return s.unshift(o),t.routes.set(i.targetId,s),{stdout:`Route added: ${a}\n`,stderr:``,exitCode:0}},jz=async({state:e,flags:t})=>{let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};let r=e.routes.get(n.targetId)??[];return r.length===0?{stdout:`No active routes
|
|
6543
6543
|
`,stderr:``,exitCode:0}:{stdout:r.map((e,t)=>`${t+1}. ${e.pattern} → ${e.status} ${e.contentType}`).join(`
|
|
6544
6544
|
`)+`
|
|
6545
|
-
`,stderr:``,exitCode:0}},
|
|
6546
|
-
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function
|
|
6547
|
-
`),f=`/.playwright/snapshots/page-${
|
|
6545
|
+
`,stderr:``,exitCode:0}},Mz=async({state:e,positional:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=t[0];if(!i){e.routes.set(r.targetId,[]);let t=e.routeCleanup.get(r.targetId);return t&&(t(),e.routeCleanup.delete(r.targetId)),{stdout:`All routes removed
|
|
6546
|
+
`,stderr:``,exitCode:0}}let a=e.routes.get(r.targetId)??[],o=a.length,s=a.filter(e=>e.pattern!==i);if(e.routes.set(r.targetId,s),s.length===0){let t=e.routeCleanup.get(r.targetId);t&&(t(),e.routeCleanup.delete(r.targetId))}return{stdout:`Removed ${o-s.length} route(s) matching "${i}"\n`,stderr:``,exitCode:0}};async function Nz(e,t){if(!t.sessionDirsCreated){for(let t of[`/.playwright`,`/.playwright/snapshots`,`/.playwright/screenshots`])try{await e.mkdir(t,{recursive:!0})}catch(e){if(!lL(e))throw e}t.sessionDirsCreated=!0}}async function Pz(e,t,n,r){try{return await e.withTab(n,async()=>{let{url:i,title:a,text:o,refToSelector:s,refToBackendNodeId:c,refToFrameId:l}=await Sz(e),u={url:i,title:a,refToSelector:s,refToBackendNodeId:c,refToFrameId:l,content:o,timestamp:Date.now()};r.snapshots.set(n,u);let d=[`Page URL: ${i}`,`Page Title: ${a}`,``,o].join(`
|
|
6547
|
+
`),f=`/.playwright/snapshots/page-${cL(new Date)}.yml`;return await t.writeFile(f,d),f})}catch{return null}}async function Fz(e,t,n){await Nz(e,t);let r=new Date().toISOString(),i=`playwright-cli ${n.command}${n.args.length?` `+n.args.join(` `):``}`,a=n.result.exitCode===0?n.result.stdout.trim()||`OK`:`Error: ${n.result.stderr.trim()}`,o=[`### ${i}`,`- **Time**: ${r}`];if(n.tabUrl||n.targetId){let e=n.tabUrl?`${n.tabUrl}${n.targetId?` (targetId: ${n.targetId})`:``}`:`targetId: ${n.targetId}`;o.push(`- **Tab**: ${e}`)}o.push(`- **Result**: ${a}`),n.snapshotPath&&o.push(``,`[Snapshot](${n.snapshotPath})`),o.push(`---`,``);let s=o.join(`
|
|
6548
6548
|
`)+`
|
|
6549
|
-
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}async function
|
|
6549
|
+
`,c=`/.playwright/session.md`,l=``;try{let t=await e.readFile(c);l=typeof t==`string`?t:new TextDecoder().decode(t)}catch{}await e.writeFile(c,l+s)}async function Iz(e,t){let n=e.getTransport(),r=e.getSessionId();await n.send(`DOM.enable`,{},r),await n.send(`Runtime.enable`,{},r);let i=(await n.send(`DOM.resolveNode`,{backendNodeId:t},r)).object;if(i?.objectId)return(await n.send(`Runtime.callFunctionOn`,{objectId:i.objectId,functionDeclaration:`function() {
|
|
6550
6550
|
this.scrollIntoView({ block: 'center' });
|
|
6551
6551
|
const r = this.getBoundingClientRect();
|
|
6552
6552
|
return { x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height };
|
|
6553
|
-
}`,returnByValue:!0},r)).result?.value}async function
|
|
6553
|
+
}`,returnByValue:!0},r)).result?.value}async function Lz(e,t){let n=await e.evaluate(`(function() {
|
|
6554
6554
|
const el = document.querySelector(${JSON.stringify(t.split(`,`)[0].trim())});
|
|
6555
6555
|
if (!el) return null;
|
|
6556
6556
|
el.scrollIntoView({ block: 'center' });
|
|
6557
6557
|
const r = el.getBoundingClientRect();
|
|
6558
6558
|
return JSON.stringify({ x: r.x + window.scrollX, y: r.y + window.scrollY, width: r.width, height: r.height });
|
|
6559
|
-
})()`);return n?JSON.parse(n):void 0}async function
|
|
6560
|
-
`,stderr:``,exitCode:0}},
|
|
6559
|
+
})()`);return n?JSON.parse(n):void 0}async function Rz(e,t,n){let r=t.refToBackendNodeId.get(n);if(r)return Iz(e,r);let i=t.refToSelector.get(n);if(!i)throw Error(`Unknown ref "${n}"`);return Lz(e,i)}const zz=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};r[0];let o=i[`no-iframes`]===`true`;i.depth&&parseInt(i.depth,10),i.boxes;let{output:s}=await e.withTab(a.targetId,async()=>await Cz(e,n,a.targetId,{noIframes:o}));return i.filename?(await t.writeFile(i.filename,s),{stdout:`Snapshot saved to ${i.filename}\n`,stderr:``,exitCode:0}):{stdout:s+`
|
|
6560
|
+
`,stderr:``,exitCode:0}},Bz=async({browser:e,flags:t})=>{let n=Q(t);return`error`in n?{stdout:``,stderr:n.error,exitCode:1}:{stdout:await e.withTab(n.targetId,async()=>`Frames in current tab:\n${(await e.getFrameTree()).map(e=>{let t=e.parentFrameId?`child`:`main`,n=e.parentFrameId?` (parent: ${e.parentFrameId})`:``;return` [${t}] ${e.frameId}${n} - ${e.url}`}).join(`
|
|
6561
6561
|
`)}`)+`
|
|
6562
|
-
`,stderr:``,exitCode:0}},
|
|
6563
|
-
`,exitCode:1}:{stdout:``,stderr:`pdf: ${t}\n`,exitCode:1}}return{stdout:`Saved PDF to ${i}\n`,stderr:``,exitCode:0}},
|
|
6564
|
-
`,stderr:o,exitCode:0}},
|
|
6562
|
+
`,stderr:``,exitCode:0}},Vz=async({browser:e,fs:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n.filename||`/tmp/page-${cL(new Date)}.pdf`;try{await e.withTab(r.targetId,async n=>{let r=(await e.getTransport().send(`Page.printToPDF`,{},n)).data,a=oL(r);await t.writeFile(i,a)})}catch(e){let t=e instanceof Error?e.message:String(e);return ue()?{stdout:``,stderr:`pdf: not available in extension mode — use screenshot --full-page
|
|
6563
|
+
`,exitCode:1}:{stdout:``,stderr:`pdf: ${t}\n`,exitCode:1}}return{stdout:`Saved PDF to ${i}\n`,stderr:``,exitCode:0}},Hz=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=``;return{stdout:await e.withTab(a.targetId,async()=>{let s;if(r[0]?.startsWith(`e`)){let t=n.snapshots.get(a.targetId);if(!t)throw Error(`No snapshot available. Run "snapshot" first.`);s=await Rz(e,t,r[0]),s||(o+=`Warning: could not clip to element ${r[0]}, capturing full viewport\n`)}let c=i[`max-width`]?parseInt(i[`max-width`],10):void 0,l=await e.screenshot({fullPage:i.fullPage===`true`||i[`full-page`]===`true`,...s?{clip:s}:{},...c?{maxWidth:c}:{}}),u=i.filename||`/tmp/screenshot-${Date.now()}.png`,d=oL(l);await t.writeFile(u,d);try{await Nz(t,n);let e=`/.playwright/screenshots/screenshot-${cL(new Date)}.png`;await t.writeFile(e,d)}catch{}return`Screenshot saved to ${u} (${Math.round(d.length/1024)} KB)`})+`
|
|
6564
|
+
`,stderr:o,exitCode:0}},Uz=async({browser:e,fs:t,positional:n,flags:r})=>{let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=r.filename??n[0]??`/.playwright/storage-state.json`,o=[],s=[],c=``;o=(await e.sendCDP(`Network.getCookies`)).cookies??[],await e.withTab(i.targetId,async t=>{let n=e.getTransport();c=(await n.send(`Runtime.evaluate`,{expression:`location.origin`,returnByValue:!0},t)).result.value??``;let r=(await n.send(`Runtime.evaluate`,{expression:`JSON.stringify(Object.entries(localStorage).map(([name,value])=>({name,value})))`,returnByValue:!0},t)).result.value??`[]`;s=JSON.parse(r)});let l=JSON.stringify({cookies:o,origins:c?[{origin:c,localStorage:s}]:[]},null,2);return await t.writeFile(a,l),{stdout:`Saved storage state to ${a}\n`,stderr:``,exitCode:0}},Wz=async({browser:e,fs:t,positional:n,flags:r})=>{if(n.length===0)return{stdout:``,stderr:`state-load requires a filename
|
|
6565
6565
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=n[0],o;try{let e=await t.readTextFile(a);o=JSON.parse(e)}catch{return{stdout:``,stderr:`Failed to read storage state from ${a}\n`,exitCode:1}}o.cookies?.length&&await e.sendCDP(`Network.setCookies`,{cookies:o.cookies});let s=[];o.origins?.length&&await e.withTab(i.targetId,async t=>{let n=e.getTransport(),r=(await n.send(`Runtime.evaluate`,{expression:`location.origin`,returnByValue:!0},t)).result.value??``,i=o.origins.filter(e=>e.origin===r);s=o.origins.filter(e=>e.origin!==r);for(let{localStorage:e}of i){let r=`(function() {
|
|
6566
6566
|
var items = ${JSON.stringify(e)};
|
|
6567
6567
|
for (var i = 0; i < items.length; i++) {
|
|
6568
6568
|
localStorage.setItem(items[i].name, items[i].value);
|
|
6569
6569
|
}
|
|
6570
|
-
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}});let c=``;return s.length>0&&(c=`Skipped localStorage for non-matching origins: ${s.map(e=>e.origin).join(`, `)}\n`),{stdout:`Loaded storage state from ${a}\n`,stderr:c,exitCode:0}};function
|
|
6570
|
+
})()`;await n.send(`Runtime.evaluate`,{expression:r,returnByValue:!0},t)}});let c=``;return s.length>0&&(c=`Skipped localStorage for non-matching origins: ${s.map(e=>e.origin).join(`, `)}\n`),{stdout:`Loaded storage state from ${a}\n`,stderr:c,exitCode:0}};function Gz(e,t){return{list:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:{stdout:await e.withTab(r.targetId,async()=>{let n=await e.evaluate(`JSON.stringify(Object.entries(${t}))`),r=JSON.parse(n);return r.length===0?`No ${t} entries`:r.map(([e,t])=>`${e}=${t}`).join(`
|
|
6571
6571
|
`)})+`
|
|
6572
6572
|
`,stderr:``,exitCode:0}},get:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-get requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:{stdout:await n.withTab(a.targetId,async()=>{let e=await n.evaluate(`${t}.getItem(${JSON.stringify(r[0])})`);if(e===null)throw Error(`Key "${r[0]}" not found in ${t}`);return e})+`
|
|
6573
|
-
`,stderr:``,exitCode:0}},set:async({browser:n,positional:r,flags:i})=>{if(r.length<2)return{stdout:``,stderr:`${e}-set requires <key> <value>\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.setItem(${JSON.stringify(r[0])}, ${JSON.stringify(r.slice(1).join(` `))})`)}),{stdout:`${t} "${r[0]}" set\n`,stderr:``,exitCode:0})},del:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-delete requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.removeItem(${JSON.stringify(r[0])})`)}),{stdout:`${t} "${r[0]}" deleted\n`,stderr:``,exitCode:0})},clear:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`${t}.clear()`)}),{stdout:`${t} cleared\n`,stderr:``,exitCode:0})}}}const
|
|
6574
|
-
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Opened ${a} in new tab [targetId: ${s}]\n`,stderr:``,exitCode:0}},
|
|
6573
|
+
`,stderr:``,exitCode:0}},set:async({browser:n,positional:r,flags:i})=>{if(r.length<2)return{stdout:``,stderr:`${e}-set requires <key> <value>\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.setItem(${JSON.stringify(r[0])}, ${JSON.stringify(r.slice(1).join(` `))})`)}),{stdout:`${t} "${r[0]}" set\n`,stderr:``,exitCode:0})},del:async({browser:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`${e}-delete requires a key\n`,exitCode:1};let a=Q(i);return`error`in a?{stdout:``,stderr:a.error,exitCode:1}:(await n.withTab(a.targetId,async()=>{await n.evaluate(`${t}.removeItem(${JSON.stringify(r[0])})`)}),{stdout:`${t} "${r[0]}" deleted\n`,stderr:``,exitCode:0})},clear:async({browser:e,flags:n})=>{let r=Q(n);return`error`in r?{stdout:``,stderr:r.error,exitCode:1}:(await e.withTab(r.targetId,async()=>{await e.evaluate(`${t}.clear()`)}),{stdout:`${t} cleared\n`,stderr:``,exitCode:0})}}}const Kz=Gz(`localstorage`,`localStorage`),qz=Gz(`sessionstorage`,`sessionStorage`),Jz=n(`playwright`),Yz=async({browser:e,fs:t,state:n,positional:r,flags:i})=>{let a=r[0]||`about:blank`,o=i.runtime;await dz(e,n);let s;if(s=o?await e.createRemotePage(o,a):await e.createPage(a),i.foreground===`true`||i.fg===`true`)try{await e.withTab(s,async t=>{await e.getTransport().send(`Page.bringToFront`,{},t)})}catch(e){Jz.debug(`open/tab-new --foreground bringToFront failed`,{targetId:s,error:e instanceof Error?e.message:String(e)})}let c=i[`teleport-start`],l=i[`teleport-return`];if(c&&l){Jz.info(`Arming teleport via open/tab-new flags`),Jz.debug(`Arming teleport via open/tab-new flags details`,{targetId:s,startPattern:c,returnPattern:l});let t,r;try{t=new RegExp(c)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-start: ${c}\n`,exitCode:1}}try{r=new RegExp(l)}catch{return{stdout:``,stderr:`Invalid regex for --teleport-return: ${l}\n`,exitCode:1}}let o=i.timeout?parseInt(i.timeout,10):300,u=n.teleportWatchers.get(s);u&&(AR(u),n.teleportWatchers.delete(s)),jR(e,n,t,r,o*1e3,i[`teleport-runtime`],a,s)}if(i.discover===`true`){let{browseShWarning:e,...n}=await RL(a,{discover:!0,fs:t}),r={action:`open`,targetId:s,source:`auxiliary-fetch`,...n};return{stdout:JSON.stringify(r,null,2)+`
|
|
6574
|
+
`,stderr:e?`${e}\n`:``,exitCode:0}}return{stdout:`Opened ${a} in new tab [targetId: ${s}]\n`,stderr:``,exitCode:0}},Xz=async({browser:e,state:t})=>{let n=await _z(e,t);return n.length===0?{stdout:`No tabs open
|
|
6575
6575
|
`,stderr:``,exitCode:0}:{stdout:n.map(e=>{let t=!!e.active,n=e.targetId.includes(`:`),r=t?` (active)`:``,i=n?` [remote:${e.targetId.substring(0,e.targetId.indexOf(`:`))}]`:``;return`[${e.targetId}] ${e.url} "${e.title}"${r}${i}`}).join(`
|
|
6576
6576
|
`)+`
|
|
6577
|
-
`,stderr:``,exitCode:0}},
|
|
6577
|
+
`,stderr:``,exitCode:0}},Zz=async({browser:e,state:t,flags:n})=>{let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};await e.closePage(r.targetId),t.snapshots.delete(r.targetId),t.teleportWatchers.delete(r.targetId),t.consoleMessages.delete(r.targetId);let i=t.consoleCleanup.get(r.targetId);i&&(i(),t.consoleCleanup.delete(r.targetId)),t.networkRequests.delete(r.targetId);let a=t.networkCleanup.get(r.targetId);a&&(a(),t.networkCleanup.delete(r.targetId));let o=t.routeCleanup.get(r.targetId);return o&&(o(),t.routeCleanup.delete(r.targetId)),t.routes.delete(r.targetId),t.lastMousePosition.delete(r.targetId),{stdout:`Closed tab ${r.targetId}\n`,stderr:``,exitCode:0}},Qz=async({browser:e,state:t,positional:n})=>{if(n.length===0)return{stdout:``,stderr:`tab-select requires a tab index
|
|
6578
6578
|
`,exitCode:1};let r=n[0];if(!/^[0-9]+$/.test(r))return{stdout:``,stderr:`tab-select index must be a positive integer
|
|
6579
6579
|
`,exitCode:1};let i=parseInt(r,10);if(i<1)return{stdout:``,stderr:`tab-select index must be a positive integer
|
|
6580
|
-
`,exitCode:1};let a=await
|
|
6580
|
+
`,exitCode:1};let a=await _z(e,t);if(i>a.length)return{stdout:``,stderr:`tab-select index ${i} out of range (${a.length} tab${a.length===1?``:`s`} open)\n`,exitCode:1};let o=a[i-1].targetId;return await e.withTab(o,async t=>{await e.getTransport().send(`Page.bringToFront`,{},t)}),{stdout:`Selected tab ${i} [targetId: ${o}]\n`,stderr:``,exitCode:0}},$z=async({browser:e,state:t,positional:n,flags:r})=>{if(n.length<2)return{stdout:``,stderr:`resize requires <width> <height>
|
|
6581
6581
|
`,exitCode:1};let i=Q(r);if(`error`in i)return{stdout:``,stderr:i.error,exitCode:1};let a=parseInt(n[0],10),o=parseInt(n[1],10);return isNaN(a)||isNaN(o)||a<=0||o<=0?{stdout:``,stderr:`resize requires positive integer width and height
|
|
6582
|
-
`,exitCode:1}:(await e.withTab(i.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Emulation.setDeviceMetricsOverride`,{width:a,height:o,deviceScaleFactor:1,mobile:!1},n)}),t.snapshots.delete(i.targetId),{stdout:`Resized viewport to ${a}x${o}\n`,stderr:``,exitCode:0})},
|
|
6582
|
+
`,exitCode:1}:(await e.withTab(i.targetId,async()=>{let t=e.getTransport(),n=e.getSessionId();await t.send(`Emulation.setDeviceMetricsOverride`,{width:a,height:o,deviceScaleFactor:1,mobile:!1},n)}),t.snapshots.delete(i.targetId),{stdout:`Resized viewport to ${a}x${o}\n`,stderr:``,exitCode:0})},eB=n(`playwright-teleport`);function tB(){eB.info(`Listing available follower runtimes`);let e=OR();if(!e)return{stdout:``,stderr:`teleport: not connected to a tray
|
|
6583
6583
|
`,exitCode:1};let t=e();if(t.length===0)return{stdout:`No followers connected to the tray.
|
|
6584
6584
|
`,stderr:``,exitCode:0};let n=[`Available runtimes for teleport:`];for(let e of t){let t=[e.runtimeId];if(e.floatType&&t.push(`[${e.floatType}]`),e.runtime&&t.push(`(${e.runtime})`),e.lastActivity){let n=Math.round((Date.now()-e.lastActivity)/1e3);t.push(`active ${n}s ago`)}n.push(` ${t.join(` `)}`)}return{stdout:n.join(`
|
|
6585
6585
|
`)+`
|
|
6586
|
-
`,stderr:``,exitCode:0}}function
|
|
6587
|
-
`,stderr:``,exitCode:0}}function
|
|
6588
|
-
`,exitCode:1};let o=
|
|
6589
|
-
`,exitCode:1};let c=n.runtime;if(c){let e=
|
|
6586
|
+
`,stderr:``,exitCode:0}}function nB({state:e,flags:t}){let n=Q(t);if(`error`in n)return{stdout:``,stderr:n.error,exitCode:1};eB.info(`Disarming teleport watcher via --off`,{targetId:n.targetId});let r=e.teleportWatchers.get(n.targetId);return r&&(AR(r),e.teleportWatchers.delete(n.targetId)),{stdout:`Teleport watcher disarmed
|
|
6587
|
+
`,stderr:``,exitCode:0}}function rB(e,t){let n,r;try{n=new RegExp(e)}catch{return{error:`Invalid regex for --start: ${e}\n`}}try{r=new RegExp(t)}catch{return{error:`Invalid regex for --return: ${t}\n`}}return{startPattern:n,returnPattern:r}}function iB(e){return(OR()?.()??[]).find(t=>t.runtimeId===e)?.runtime===`slicc-cherry`?`teleport: runtime ${e} is a cherry host and cannot serve a cookie teleport (no Network.* access)\n`:null}async function aB({browser:e,state:t,flags:n}){let r=Q(n);if(`error`in r)return{stdout:``,stderr:r.error,exitCode:1};let i=n.start||n[`teleport-start`],a=n.return||n[`teleport-return`];if(!i||!a)return{stdout:``,stderr:`teleport requires --start <regex> and --return <regex>
|
|
6588
|
+
`,exitCode:1};let o=rB(i,a);if(`error`in o)return{stdout:``,stderr:o.error,exitCode:1};let s=n.timeout?parseInt(n.timeout,10):300;if(isNaN(s)||s<=0)return{stdout:``,stderr:`--timeout must be a positive number
|
|
6589
|
+
`,exitCode:1};let c=n.runtime;if(c){let e=iB(c);if(e)return{stdout:``,stderr:e,exitCode:1}}let l=t.teleportWatchers.get(r.targetId);l&&(eB.info(`Disarming existing teleport watcher before re-arming`,{targetId:r.targetId}),AR(l),t.teleportWatchers.delete(r.targetId));let u;try{await e.attachToPage(r.targetId);let t=await e.evaluate(`window.location.href`);u=typeof t==`string`?t:String(t)}catch{}return eB.info(`Arming teleport via explicit subcommand`,{targetId:r.targetId,timeoutSec:s,runtimeSelection:c?`explicit`:`auto`}),eB.debug(`Arming teleport via explicit subcommand details`,{targetId:r.targetId,startPattern:i,returnPattern:a,timeoutSec:s,runtimeId:c??`auto`,leaderUrl:u}),jR(e,t,o.startPattern,o.returnPattern,s*1e3,c,u,r.targetId),{stdout:`Teleport armed on tab ${r.targetId}. Will trigger when URL matches ${i}\n`,stderr:``,exitCode:0}}const oB=async e=>e.flags.list===`true`?tB():e.flags.off===`true`?nB(e):aB(e),sB={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`,pdf:`application/pdf`,txt:`text/plain`,json:`application/json`,csv:`text/csv`,html:`text/html`,htm:`text/html`,xml:`application/xml`,zip:`application/zip`,mp4:`video/mp4`,mp3:`audio/mpeg`};function cB(e){let t=e.split(`.`).pop()?.toLowerCase()??``;return sB[t]??`application/octet-stream`}function lB(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const uB=new Map([[`teleport`,oB],[`open`,Yz],[`tab-new`,Yz],[`fetch`,zL],[`goto`,zR],[`navigate`,zR],[`snapshot`,zz],[`frames`,Bz],[`screenshot`,Hz],[`click`,GL],[`type`,KL],[`fill`,qL],[`eval`,NL],[`eval-file`,PL],[`press`,JL],[`keydown`,YL],[`keyup`,XL],[`go-back`,BR],[`go-forward`,VR],[`reload`,HR],[`tab-list`,Xz],[`tab-close`,Zz],[`close`,Zz],[`dblclick`,ZL],[`hover`,QL],[`select`,$L],[`check`,eR],[`uncheck`,tR],[`drag`,nR],[`resize`,$z],[`dialog-accept`,OL],[`dialog-dismiss`,kL],[`cookie-list`,xL],[`cookie-get`,SL],[`cookie-set`,CL],[`cookie-delete`,wL],[`cookie-clear`,TL],[`localstorage-list`,Kz.list],[`localstorage-get`,Kz.get],[`localstorage-set`,Kz.set],[`localstorage-delete`,Kz.del],[`localstorage-clear`,Kz.clear],[`sessionstorage-list`,qz.list],[`sessionstorage-get`,qz.get],[`sessionstorage-set`,qz.set],[`sessionstorage-delete`,qz.del],[`sessionstorage-clear`,qz.clear],[`record`,wz],[`stop-recording`,Tz],[`tab-select`,Qz],[`pdf`,Vz],[`network-state-set`,UR],[`upload`,async({browser:e,fs:t,state:n,positional:r,flags:i})=>{if(r.length===0)return{stdout:``,stderr:`upload requires at least one file path
|
|
6590
6590
|
`,exitCode:1};let a=Q(i);if(`error`in a)return{stdout:``,stderr:a.error,exitCode:1};let o=null,s=r,c=n.snapshots.get(a.targetId);if(c&&r.length>0&&c.refToBackendNodeId.has(r[0])&&(o=r[0],s=r.slice(1)),s.length===0)return{stdout:``,stderr:`upload requires at least one file path
|
|
6591
|
-
`,exitCode:1};let l=[];for(let e of s){let n=await t.readFile(e),r=e.split(`/`).pop()??e,i=
|
|
6591
|
+
`,exitCode:1};let l=[];for(let e of s){let n=await t.readFile(e),r=e.split(`/`).pop()??e,i=cB(r),a=lB(typeof n==`string`?new TextEncoder().encode(n):n);l.push({name:r,type:i,base64:a})}if(o){let t=c.refToBackendNodeId.get(o);await e.withTab(a.targetId,async n=>{let r=e.getTransport();await r.send(`DOM.enable`,{},n);let{object:i}=await r.send(`DOM.resolveNode`,{backendNodeId:t},n),a=await r.send(`Runtime.callFunctionOn`,{objectId:i.objectId,functionDeclaration:`function(filesData) {
|
|
6592
6592
|
const el = this;
|
|
6593
6593
|
if (el.tagName !== 'INPUT' || el.type !== 'file') {
|
|
6594
6594
|
throw new Error('Element ' + el.tagName + ' is not a file input');
|
|
@@ -6619,7 +6619,7 @@ Options:
|
|
|
6619
6619
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
6620
6620
|
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
6621
6621
|
return el.files.length;
|
|
6622
|
-
})()`,r=await e.getTransport().send(`Runtime.evaluate`,{expression:n,returnByValue:!0,awaitPromise:!1},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`File upload failed`;throw Error(e)}});let u=s.map(e=>e.split(`/`).pop()??e).join(`, `);return{stdout:`Uploaded ${s.length} file(s): ${u}\n`,stderr:``,exitCode:0}}],[`state-save`,
|
|
6622
|
+
})()`,r=await e.getTransport().send(`Runtime.evaluate`,{expression:n,returnByValue:!0,awaitPromise:!1},t);if(r.exceptionDetails){let e=r.exceptionDetails.exception?.description??r.exceptionDetails.text??`File upload failed`;throw Error(e)}});let u=s.map(e=>e.split(`/`).pop()??e).join(`, `);return{stdout:`Uploaded ${s.length} file(s): ${u}\n`,stderr:``,exitCode:0}}],[`state-save`,Uz],[`state-load`,Wz],[`console`,bL],[`requests`,JR],[`request`,YR],[`request-headers`,XR],[`request-body`,ZR],[`response-headers`,QR],[`response-body`,$R],[`mousemove`,sR],[`mousedown`,cR],[`mouseup`,lR],[`mousewheel`,uR],[`drop`,dR],[`route`,Az],[`route-list`,jz],[`unroute`,Mz],[`generate-locator`,EL],[`highlight`,DL]]);function dB(e){return`Usage: ${e} <command> [args...]
|
|
6623
6623
|
|
|
6624
6624
|
Commands:
|
|
6625
6625
|
open [url|/vfs/path] [--foreground|--fg] [--runtime=<id>] [--discover]
|
|
@@ -6742,11 +6742,11 @@ Commands:
|
|
|
6742
6742
|
Highlight an element with a visual overlay (--hide to remove)
|
|
6743
6743
|
help Show this help message
|
|
6744
6744
|
|
|
6745
|
-
Aliases: ${
|
|
6746
|
-
`,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),c,l;try{({positional:c,flags:l}=
|
|
6747
|
-
`);let a=[];for(let[e,t]of
|
|
6745
|
+
Aliases: ${nL.filter(t=>t!==e).join(`, `)}`}function fB(e,t,n){let r=dB(e),i=t?iL(t,n):null;return G(e,async a=>{if(a.length===0||a[0]===`help`||a[0]===`--help`||a[0]===`-h`)return{stdout:r+`
|
|
6746
|
+
`,stderr:``,exitCode:0};if(!t||!i)return{stdout:``,stderr:`${e}: browser APIs are unavailable in this environment\n`,exitCode:1};let o=a[0],s=a.slice(1),c,l;try{({positional:c,flags:l}=hL(s))}catch(t){return{stdout:``,stderr:`${e} ${o}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}let u,d=uB.get(o);if(!d)u={stdout:``,stderr:`Unknown command: ${o}\nRun "playwright-cli help" for usage.\n`,exitCode:1};else try{u=await d({browser:t,fs:n,state:i,positional:c,flags:l})}catch(e){u={stdout:``,stderr:`Error: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let f=l.tab??null,p=null;sL.has(o)&&u.exitCode===0&&f&&(p=await Pz(t,n,f,i));try{await Fz(n,i,{command:o,args:s,result:u,snapshotPath:p,targetId:f})}catch{}return u})}const pB=new Map([[`File operations`,[`ls`,`cat`,`head`,`tail`,`wc`,`touch`,`mkdir`,`rm`,`cp`,`mv`,`ln`,`chmod`,`stat`,`readlink`,`file`,`rmdir`,`rsync`]],[`Text processing`,[`grep`,`sed`,`awk`,`sort`,`uniq`,`cut`,`tr`,`tee`,`diff`,`column`,`comm`,`egrep`,`fgrep`,`expand`,`unexpand`,`fold`,`join`,`nl`,`od`,`paste`,`rev`,`split`,`strings`,`tac`]],[`Search`,[`find`,`rg`]],[`Navigation & paths`,[`pwd`,`basename`,`dirname`,`tree`,`du`,`cd`]],[`Archives`,[`zip`,`unzip`,`pdftk`,`pdf`,`gunzip`,`gzip`,`zcat`]],[`Media`,[`convert`,`magick`,`ffmpeg`,`screencapture`]],[`Audio`,[`say`,`afplay`,`chime`]],[`Environment & shell`,`echo.printf.env.printenv.export.alias.unalias.history.clear.true.false.bash.sh.commands.which.uname.man.host.oauth-token.secret.nuke.models.local-llm.cost.hostname.whoami.help.sleep.time.timeout.oauth-domain`.split(`.`)],[`Data processing`,[`xargs`,`jq`,`base64`,`date`,`expr`,`seq`]],[`Hashes`,[`md5sum`,`sha1sum`,`sha256sum`]],[`Network`,[`curl`,`wget`,`dig`,`websocat`,`html-to-markdown`]],[`Version control`,[`git`]],[`Languages`,[`node`,`python`,`python3`,`sqlite3`]],[`Build tools`,[`tsc`,`test`,`esbuild`,`biome`]],[`Packages`,[`ipk`,`hf`,`npm`,`i`,`ipx`,`npx`]],[`Skills`,[`skill`,`upskill`]],[`Browser & UI`,[`serve`,`open`,`imgcat`,...nL,`sprinkle`]],[`Clipboard`,[`pbcopy`,`pbpaste`,`xclip`,`xsel`]],[`Filesystem`,[`mount`,`fswatch`]],[`Scoops & agents`,[`agent`,`mcp`,`webhook`,`crontask`]],[`Process`,[`ps`,`kill`]]]);function mB(e,t=[],n=[]){let r=[],i=new Set(e);for(let e of t)i.delete(e);for(let e of n)i.delete(e);r.push(`Available commands:
|
|
6747
|
+
`);let a=[];for(let[e,t]of pB){let n=t.filter(e=>i.has(e));if(n.length>0){r.push(` ${e}:`),r.push(` ${n.join(`, `)}\n`);for(let e of n)i.delete(e)}}for(let e of i)a.push(e);return a.length>0&&(r.push(` Other:`),r.push(` ${a.sort().join(`, `)}\n`)),t.length>0&&(r.push(` User scripts (.jsh):`),r.push(` ${t.sort().join(`, `)}\n`)),n.length>0&&(r.push(` Workflows:`),r.push(` ${n.sort().join(`, `)}\n`)),r.push(`Use '<command> --help' for details on a specific command.`),r.join(`
|
|
6748
6748
|
`)+`
|
|
6749
|
-
`}function
|
|
6749
|
+
`}function hB(e={}){return G(`commands`,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return{stdout:`commands - display available commands
|
|
6750
6750
|
|
|
6751
6751
|
Usage: commands [command]
|
|
6752
6752
|
|
|
@@ -6757,7 +6757,7 @@ If a command name is provided, shows help for that command.
|
|
|
6757
6757
|
Otherwise, lists all available commands.
|
|
6758
6758
|
|
|
6759
6759
|
Note: This is an enhanced version of 'help' that shows all custom commands.
|
|
6760
|
-
`,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout:
|
|
6760
|
+
`,stderr:``,exitCode:0};if(t.length>0&&n.exec){let e=t[0];return n.exec(`${e} --help`,{cwd:n.cwd})}return{stdout:mB(n.getRegisteredCommands?.()??[],await e.getJshCommands?.()??[],await e.getWorkflowCommands?.()??[]),stderr:``,exitCode:0}})}function gB(e){return{stdout:`hf - download model repos from the Hugging Face Hub into the VFS
|
|
6761
6761
|
|
|
6762
6762
|
Usage:
|
|
6763
6763
|
hf download <repo> [files...] [--to <dir>] [--revision <rev>] [--force]
|
|
@@ -6779,8 +6779,8 @@ Notes:
|
|
|
6779
6779
|
unless --force is passed.
|
|
6780
6780
|
- Weights are read by the speech engines via the preview SW from the
|
|
6781
6781
|
target directory; transformers expects <localModelPath>/<repo>/.
|
|
6782
|
-
`,stderr:``,exitCode:e}}function
|
|
6783
|
-
`)}\n`}function
|
|
6782
|
+
`,stderr:``,exitCode:e}}function _B(e){return{stdout:``,stderr:`hf: ${e}\n`,exitCode:1}}const vB=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;function yB(e){let t=null,n=`main`,r=!1,i=[],a=0;for(;a<e.length;){let o=e[a];if(o===`--to`){let n=e[a+1];if(typeof n!=`string`)return{error:`--to requires a value`};t=n,a+=2;continue}if(o===`--revision`||o===`--rev`){let t=e[a+1];if(typeof t!=`string`)return{error:`${o} requires a value`};n=t,a+=2;continue}if(o===`--force`||o===`-f`){r=!0,a+=1;continue}if(o.startsWith(`--`))return{error:`unknown option: ${o}`};i.push(o),a+=1}if(i.length===0)return{error:`download requires <repo>`};let o=i[0];return vB.test(o)?{repo:o,files:i.slice(1),to:t,revision:n,force:r}:{error:`invalid repo '${o}' — expected <owner>/<name>`}}function bB(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}async function xB(e,t,n){let r=yB(e);if(`error`in r)return _B(r.error);let i=Wt(r.repo,r.to,t.cwd),a=``;try{let e=await Rt({fetch:n,fs:t.fs,repo:r.repo,targetDir:i,files:r.files,revision:r.revision,force:r.force,progress:{onListed:({files:e})=>{a+=`hf: ${e.length} file(s) listed in ${r.repo}@${r.revision}\n`},onFile:e=>{a+=e.status===`downloaded`?`hf: downloaded ${e.file} (${bB(e.bytes)})\n`:`hf: skipped ${e.file} (already at ${i})\n`}}}),o=`hf: ${e.downloaded} downloaded, ${e.skipped} skipped, ${bB(e.totalBytes)} total into ${i}\n`;return{stdout:``,stderr:a+o,exitCode:0}}catch(e){return e instanceof Pt?(a+=`hf: failed ${e.file}: ${e.message}\n`,{stdout:``,stderr:a,exitCode:1}):_B(e instanceof Error?e.message:String(e))}}function SB(e){return{name:`hf`,async execute(t,n){if(t.length===0||t[0]===`--help`||t[0]===`-h`)return gB(+(t.length===0));let r=t[0];return r===`download`?xB(t.slice(1),n,e.fetch):_B(`unknown subcommand: ${r}`)}}}const CB=new Set([`--vid`,`--pid`,`--usage-page`,`--usage`,`--__resolved`,`--timeout`]);function wB(e){return wm(e,CB)}function TB(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 EB(e){let t={};return e.has(`--vid`)&&(t.vendorId=TB(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=TB(e.get(`--pid`),`pid`)),e.has(`--usage-page`)&&(t.usagePage=TB(e.get(`--usage-page`),`usage-page`)),e.has(`--usage`)&&(t.usage=TB(e.get(`--usage`),`usage`)),Object.keys(t).length>0?[t]:[]}function DB(e){let t=Fk(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function OB(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function kB(e){return e.toString(16).padStart(2,`0`)}function AB(e){return`0x${e.toString(16).padStart(4,`0`)}`}function jB(e){let t=e.productName||`(unknown)`,n=e.opened?` [open]`:``,r=e.usagePage===void 0?``:`\t${AB(e.usagePage)}:${AB(e.usage??0)}`;return`${e.handle}\t${AB(e.vendorId)}:${AB(e.productId)}${r}\t${t}${n}`}function MB(e,t){let n=t?.usagePage,r=t?.usage;if(n===void 0&&r===void 0)return e;let i=e.findIndex(e=>(n===void 0||e.usagePage===n)&&(r===void 0||e.usage===r));if(i<=0)return e;let a=e.slice(),[o]=a.splice(i,1);return a.unshift(o),a}function NB(e){return`${e.map(jB).join(`
|
|
6783
|
+
`)}\n`}function PB(e){return`${kB(e.reportId)} ${OB(e.bytes)}`.trimEnd()}function FB(e){return{stdout:e,stderr:``,exitCode:0}}function IB(e){return{stdout:``,stderr:`hid: ${e}\n`,exitCode:1}}const LB=`hid - access HID devices via WebHID
|
|
6784
6784
|
|
|
6785
6785
|
Usage: hid <subcommand> [options]
|
|
6786
6786
|
|
|
@@ -6803,19 +6803,19 @@ Options:
|
|
|
6803
6803
|
--timeout <ms> query: wait this long for an input report (default 1000)
|
|
6804
6804
|
-h, --help
|
|
6805
6805
|
|
|
6806
|
-
Report payloads are capped at ${
|
|
6807
|
-
`;function
|
|
6808
|
-
`):
|
|
6809
|
-
`)}\n`)}async function
|
|
6810
|
-
`)}\n`:``)}async function
|
|
6806
|
+
Report payloads are capped at ${rD} bytes (4 MiB).
|
|
6807
|
+
`;function RB(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return FB(t)}return FB(e.length?`${OB(e)}\n`:``)}function zB(e){return!e||e.aborted?Promise.resolve():new Promise(t=>{e.addEventListener(`abort`,()=>t(),{once:!0})})}async function BB(e){let t=await e.list();return t.length===0?FB(`no granted HID devices
|
|
6808
|
+
`):FB(`${t.map(jB).join(`
|
|
6809
|
+
`)}\n`)}async function VB(e,t){let n=e.get(`--__resolved`),r=EB(e),i=r[0];if(n){let e=n.split(`,`).filter(e=>e.length>0);return e.length===0?IB(`request: missing resolved handle`):FB(NB(MB(await Promise.all(e.map(e=>t.info(e))),i)))}let a=re();return a?HB(r,i,a,t):FB(NB(MB(await t.request(r),i)))}async function HB(e,t,n,r){let i=await I(`hid-device`,e,n),a,o;if(i.handle){let e=await r.info(i.handle);a=e.vendorId,o=e.productId}else{let e=i.info,t=ZE();if(!t)return IB(`request: WebHID unavailable for device re-acquire`);let n=await t.getDevices(),r=nD(),s=n.filter(t=>t.vendorId===e.vendorId&&t.productId===e.productId);if(s.length===0)return IB(`request: granted device could not be re-acquired`);for(let e of s)r.register(e);a=e.vendorId,o=e.productId}let s=(await r.list()).filter(e=>e.vendorId===a&&e.productId===o),c=MB(s.length>0?s:[],t);return c.length===0?IB(`request: granted device could not be re-acquired`):FB(NB(c))}async function UB(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):await n.close(r),FB(``)):IB(`${e}: handle required`)}async function WB(e,t,n,r){let[,i,a]=t;if(!i||a===void 0)return IB(`${e}: handle and report-id required`);let o=TB(a,`report-id`),s=DB(n);return s.length>4194304?IB(`${e} payload exceeds 4 MiB limit`):(e===`send`?await r.sendReport(i,o,s):await r.sendFeatureReport(i,o,s),FB(``))}async function GB(e,t,n){let[,r,i]=e;return!r||i===void 0?IB(`feature-get: handle and report-id required`):RB((await t.receiveFeatureReport(r,TB(i,`report-id`))).bytes,n)}async function KB(e,t,n){let r=e[1];if(!r)return IB(`watch: handle required`);let i=[],a=await n.subscribeInputReports(r,e=>{i.push(PB(e))});try{await zB(t.signal)}finally{await a()}return FB(i.length?`${i.join(`
|
|
6810
|
+
`)}\n`:``)}async function qB(e,t,n,r,i){let[,a,o]=e;if(!a||o===void 0)return IB(`query: handle and report-id required`);let s=TB(o,`report-id`),c=DB(t);if(c.length>4194304)return IB(`query payload exceeds 4 MiB limit`);let l=n.has(`--timeout`)?TB(n.get(`--timeout`),`timeout`):1e3,u=()=>{},d=new Promise(e=>{u=e}),f=await r.subscribeInputReports(a,e=>{u(e)}),p;try{await r.sendReport(a,s,c);let e=new Promise(e=>{p=setTimeout(()=>e(`timeout`),l)}),t=await Promise.race([d,e]);return t===`timeout`?IB(`query: no input report within ${l}ms`):i?RB(t.bytes,!0):FB(`${PB(t)}\n`)}finally{p!==void 0&&clearTimeout(p),await f()}}async function JB(e,t,n){let{positionals:r,flags:i,bools:a}=wB(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return BB(n);case`request`:return VB(i,n);case`open`:case`close`:return UB(o,r,n);case`send`:case`feature-send`:return WB(o,r,t,n);case`feature-get`:return GB(r,n,s);case`watch`:return KB(r,t,n);case`query`:return qB(r,t,i,n,s);default:return IB(`unknown subcommand '${o??``}'. Try 'hid --help'.`)}}function YB(){return G(`hid`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return FB(LB);let n=wD(Ue(),He());if(!n)return IB(`WebHID is unavailable in this environment`);try{return await JB(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?IB(`user cancelled or no device selected`):IB(t)}})}function XB(){return{stdout:`imgcat - preview image and video files in the preview tab
|
|
6811
6811
|
|
|
6812
6812
|
Usage: imgcat <path> [path...]
|
|
6813
6813
|
|
|
6814
6814
|
Options:
|
|
6815
6815
|
-h, --help Show this help message
|
|
6816
|
-
`,stderr:``,exitCode:0}}function
|
|
6816
|
+
`,stderr:``,exitCode:0}}function ZB(e={}){return G(`imgcat`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return XB();if(typeof window>`u`||typeof document>`u`)return{stdout:``,stderr:`imgcat: browser APIs are unavailable in this environment
|
|
6817
6817
|
`,exitCode:1};if(!e.onMediaPreview)return{stdout:``,stderr:`imgcat: terminal preview is unavailable
|
|
6818
|
-
`,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let i=fe(t);if(!de(i))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let a=await n.fs.readFileBuffer(t),o=new Uint8Array(a.byteLength);o.set(a),r.push({path:t,mimeType:i,bytes:o})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const
|
|
6818
|
+
`,exitCode:1};let r=[];for(let e of t){let t=n.fs.resolvePath(n.cwd,e);if(!(await n.fs.stat(t)).isFile)return{stdout:``,stderr:`imgcat: not a file: ${e}\n`,exitCode:1};let i=fe(t);if(!de(i))return{stdout:``,stderr:`imgcat: unsupported media type: ${e}\n`,exitCode:1};let a=await n.fs.readFileBuffer(t),o=new Uint8Array(a.byteLength);o.set(a),r.push({path:t,mimeType:i,bytes:o})}try{return await e.onMediaPreview(r),{stdout:``,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`imgcat: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const QB=new Set([`install`,`i`,`add`]);function $B(e){return`${e} - install packages from the npm registry into node_modules
|
|
6819
6819
|
|
|
6820
6820
|
Usage:
|
|
6821
6821
|
${e} install [<pkg>[@<spec>] ...]
|
|
@@ -6841,11 +6841,11 @@ Installed packages are extracted into <cwd>/node_modules and named installs
|
|
|
6841
6841
|
are recorded in <cwd>/package.json under dependencies. Existing fields are
|
|
6842
6842
|
preserved. Idempotent: re-installing an already-satisfied package is a clean
|
|
6843
6843
|
no-op.
|
|
6844
|
-
`}function
|
|
6844
|
+
`}function eV(e){return e.includes(`--help`)||e.includes(`-h`)}function tV(e){return e instanceof Error?e.message:String(e)}async function nV(e,t,n){let r;try{r=await zt({fs:n.fs,fetch:n.fetch,cwd:t.cwd})}catch(t){return t instanceof Ut?{stdout:``,stderr:`${e}: ${t.message}\n`,exitCode:1}:{stdout:``,stderr:`${e}: install failed: ${tV(t)}\n`,exitCode:1}}if(r.empty&&r.errors.length===0)return{stdout:`${e}: nothing to install (package.json declares no dependencies)\n`,stderr:``,exitCode:0};let i=r.results.map(t=>`${e}: installed ${t.name}@${t.version} -> ${t.installPath}`),a=r.errors.map(t=>`${e}: failed to install ${t.spec}: ${tV(t.error)}`);return{stdout:i.length>0?`${i.join(`
|
|
6845
6845
|
`)}\n`:``,stderr:a.length>0?`${a.join(`
|
|
6846
|
-
`)}\n`:``,exitCode:r.errors.length===0?0:1}}async function
|
|
6846
|
+
`)}\n`:``,exitCode:r.errors.length===0?0:1}}async function rV(e,t,n,r){let i=t.filter(e=>!e.startsWith(`-`));if(i.length===0)return nV(e,n,r);let a;try{a=await Vt(i,{fs:r.fs,fetch:r.fetch,cwd:n.cwd})}catch(t){return{stdout:``,stderr:`${e}: install failed: ${tV(t)}\n`,exitCode:1}}let o=a.results.map(t=>`${e}: installed ${t.name}@${t.version} -> ${t.installPath}`),s=a.errors.map(t=>`${e}: failed to install ${t.spec}: ${tV(t.error)}`);return{stdout:o.length>0?`${o.join(`
|
|
6847
6847
|
`)}\n`:``,stderr:s.length>0?`${s.join(`
|
|
6848
|
-
`)}\n`:``,exitCode:a.errors.length===0?0:1}}function
|
|
6848
|
+
`)}\n`:``,exitCode:a.errors.length===0?0:1}}function iV(e,t){let n=e===`i`;return G(e,async(r,i)=>{if(eV(r))return{stdout:$B(e),stderr:``,exitCode:0};if(n)return rV(e,r,i,t);if(r.length===0)return{stdout:$B(e),stderr:`${e}: missing subcommand\n`,exitCode:1};let a=r[0],o=r.slice(1);return QB.has(a)?rV(e,o,i,t):{stdout:``,stderr:`${e}: unknown subcommand '${a}' (supported: install, i)\n`,exitCode:1}})}const aV=/require\(\s*["']([^"']+)["']\s*\)/;function oV(e){return`${e} - run an installed package's executable bin
|
|
6849
6849
|
|
|
6850
6850
|
Usage:
|
|
6851
6851
|
${e} <pkg-or-bin> [args...]
|
|
@@ -6856,12 +6856,12 @@ forwarding argv and stdin. Exit codes propagate.
|
|
|
6856
6856
|
|
|
6857
6857
|
Options:
|
|
6858
6858
|
-h, --help Show this help message
|
|
6859
|
-
`}async function
|
|
6860
|
-
`)}\n`:``}}catch(n){return{error:
|
|
6861
|
-
`,exitCode:1};let r=
|
|
6862
|
-
`)}\n`:``,exitCode:+!i}})}function
|
|
6863
|
-
`,exitCode:2};let i=
|
|
6864
|
-
`,exitCode:2}:
|
|
6859
|
+
`}async function sV(e,t){let n=await e.readFile(t);return typeof n==`string`?n:new TextDecoder().decode(n)}async function cV(e,t){try{return(await e.stat(t)).type===`file`}catch{return!1}}async function lV(e,t){try{return(await e.stat(t)).type===`directory`}catch{return!1}}function*uV(e){let t=rt(e);for(;yield it(t,`node_modules`),t!==`/`;)t=nt(t).dir}async function dV(e,t,n){for(let r of uV(t)){let t=it(r,`.bin`,n);if(!await cV(e,t))continue;let i=await sV(e,t),a=aV.exec(i),o=nt(t).dir;return{binFilePath:a?it(o,a[1]):t,argvName:t}}return null}function fV(e){if(e.startsWith(`@`)){let t=e.indexOf(`/`);if(t!==-1)return e.slice(t+1)}return e}function pV(e,t){if(typeof e==`string`)return{binName:fV(t),binPath:e};if(typeof e!=`object`||!e)return null;let n=e,r=[t,fV(t)];for(let e of r)if(typeof n[e]==`string`)return{binName:e,binPath:n[e]};let i=Object.entries(n).filter(([,e])=>typeof e==`string`);if(i.length===1){let[e,t]=i[0];return{binName:e,binPath:t}}return null}async function mV(e,t,n){for(let r of uV(t)){let t=it(r,n),i=it(t,`package.json`);if(!await cV(e,i))continue;let a;try{a=JSON.parse(await sV(e,i))}catch{return null}let o=pV(a.bin,n);return o?{binFilePath:it(t,o.binPath.replace(/^\.\//,``)),argvName:it(r,`.bin`,o.binName)}:null}return null}async function hV(e,t,n){return await dV(e,t,n)??await mV(e,t,n)}async function gV(e,t,n){for(let r of uV(t))if(await cV(e,it(r,n,`package.json`)))return!0;return!1}function _V(e){return e instanceof Error?e.message:String(e)}function vV(e,t){return{stdout:``,stderr:`${e}: ${t}\n`,exitCode:1}}async function yV(e,t,n,r){try{let i=await Vt([t],{fs:r.fs,fetch:r.fetch,cwd:n.cwd});if(i.errors.length>0)return{error:vV(e,`failed to install '${t}': ${_V(i.errors[0].error)}`)};let a=i.results.map(t=>`${e}: installed ${t.name}@${t.version}`);return{progress:a.length>0?`${a.join(`
|
|
6860
|
+
`)}\n`:``}}catch(n){return{error:vV(e,`failed to install '${t}': ${_V(n)}`)}}}async function bV(e,t,n,r){return await cV(r,n)?null:await lV(r,n)?vV(e,`bin target '${n}' is a directory, not a file`):vV(e,`bin file '${n}' for '${t}' does not exist`)}function xV(e,t){return{name:e,trusted:!0,async execute(n,r){if(n.length===0||n[0]===`--help`||n[0]===`-h`)return{stdout:oV(e),stderr:``,exitCode:+(n.length===0)};let i=n[0],a=n.slice(1),o;try{o=await hV(t.fs,r.cwd,i)}catch(t){return vV(e,_V(t))}let s=``;if(!o){if(await gV(t.fs,r.cwd,i))return vV(e,`package '${i}' does not expose an executable bin`);let n=await yV(e,i,r,t);if(`error`in n)return n.error;if(s=n.progress,o=await hV(t.fs,r.cwd,i),!o)return vV(e,`package '${i}' was installed but does not expose an executable bin`)}let c=await bV(e,i,o.binFilePath,t.fs);if(c)return c;let l=await Lk(IE(await sV(t.fs,o.binFilePath)),[`node`,o.argvName,...a],r,void 0,{filename:o.binFilePath});return{stdout:l.stdout,stderr:s+l.stderr,exitCode:l.exitCode}}}}const SV=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]);function CV(e={}){return G(`kill`,async t=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return kV();let n=e.processManager??wV();if(!n)return{stdout:``,stderr:`kill: no process manager available in this runtime
|
|
6861
|
+
`,exitCode:1};let r=TV(t);if(!r.ok)return{stdout:``,stderr:r.stderr,exitCode:r.exitCode};let{allDelivered:i,errors:a}=EV(n,r.pids,r.signal);return{stdout:``,stderr:a.length?`${a.join(`
|
|
6862
|
+
`)}\n`:``,exitCode:+!i}})}function wV(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.signal==`function`?e:null}function TV(e){let t=`SIGTERM`,n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i===`-s`||i===`--signal`){let n=e[++r];if(!n)return{ok:!1,stderr:`kill: -s requires a signal name
|
|
6863
|
+
`,exitCode:2};let i=DV(n);if(i instanceof Error)return{ok:!1,stderr:`kill: ${i.message}\n`,exitCode:2};t=i;continue}if(i.startsWith(`-`)){let e=OV(i);if(e instanceof Error)return{ok:!1,stderr:`kill: ${e.message}\n`,exitCode:2};t=e;continue}let a=Number.parseInt(i,10);if(!Number.isFinite(a)||String(a)!==i)return{ok:!1,stderr:`kill: invalid pid '${i}'\n`,exitCode:2};n.push(a)}return n.length===0?{ok:!1,stderr:`kill: no pids supplied
|
|
6864
|
+
`,exitCode:2}:SV.has(t)?{ok:!0,signal:t,pids:n}:{ok:!1,stderr:`kill: signal ${t} not supported\n`,exitCode:2}}function EV(e,t,n){let r=!0,i=[];for(let a of t)e.signal(a,n)||(r=!1,i.push(e.get(a)?`kill: (${a}) - process already terminated`:`kill: (${a}) - no such process`));return{allDelivered:r,errors:i}}function DV(e){let t=e.toUpperCase(),n=t.startsWith(`SIG`)?t:`SIG${t}`;return n===`SIGINT`||n===`SIGTERM`||n===`SIGKILL`||n===`SIGSTOP`||n===`SIGCONT`?n:Error(`unknown signal '${e}'`)}function OV(e){return e===`-9`?`SIGKILL`:DV(e.slice(1))}function kV(){return{stdout:`Usage: kill [-s SIGNAL | -INT | -TERM | -KILL | -STOP | -CONT | -9] PID [PID …]
|
|
6865
6865
|
|
|
6866
6866
|
Send a signal to one or more processes tracked by the kernel.
|
|
6867
6867
|
|
|
@@ -6883,7 +6883,7 @@ Examples:
|
|
|
6883
6883
|
kill -INT 1024 1025 SIGINT both
|
|
6884
6884
|
kill -STOP 1024 pause; \`kill -CONT 1024\` resumes
|
|
6885
6885
|
kill -s SIGKILL 1024 explicit signal name
|
|
6886
|
-
`,stderr:``,exitCode:0}}const
|
|
6886
|
+
`,stderr:``,exitCode:0}}const AV=jn.id;function jV(){return`local-llm — inspect and configure the Local LLM provider
|
|
6887
6887
|
|
|
6888
6888
|
Usage:
|
|
6889
6889
|
local-llm Show current config + verify connection
|
|
@@ -6902,20 +6902,20 @@ Common base URLs:
|
|
|
6902
6902
|
llama.cpp http://localhost:8080/v1
|
|
6903
6903
|
vLLM http://localhost:8000/v1
|
|
6904
6904
|
Jan http://localhost:1337/v1
|
|
6905
|
-
`}function
|
|
6906
|
-
`,exitCode:1};let c=await a(s,t(
|
|
6905
|
+
`}function MV(){return G(AV,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:jV(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-R1mQ9-PX.js`),{verifyConnection:a}=await import(`./local-llm-kMFFJCDT.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(AV);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
6906
|
+
`,exitCode:1};let c=await a(s,t(AV)??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(`
|
|
6907
6907
|
`)+`
|
|
6908
|
-
`,exitCode:1}}if(o===`discover`){let e=n(
|
|
6908
|
+
`,exitCode:1}}if(o===`discover`){let e=n(AV)??``;return i(AV,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(`
|
|
6909
6909
|
`)+`
|
|
6910
6910
|
`,stderr:``,exitCode:0}}return{stdout:[`✓ ${s}`,` runtime: ${c.runtime.kind}${c.runtime.version?` (${c.runtime.version})`:``}`,` models: ${c.models.length}`,...c.models.map(e=>` • ${e}`)].join(`
|
|
6911
6911
|
`)+`
|
|
6912
|
-
`,stderr:``,exitCode:0}})}function
|
|
6912
|
+
`,stderr:``,exitCode:0}})}function NV(){return{stdout:`usage: man <topic>
|
|
6913
6913
|
|
|
6914
6914
|
Fetches documentation for a given topic from sliccy.com.
|
|
6915
|
-
`,stderr:``,exitCode:0}}function
|
|
6915
|
+
`,stderr:``,exitCode:0}}function PV(e){return e.replace(/<[^>]*>/g,``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `).trimEnd()}function FV(){let e=l();return G(`man`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return NV();if(t.length===0)return{stdout:``,stderr:`What manual page do you want?
|
|
6916
6916
|
For example, try 'man commands'.
|
|
6917
|
-
`,exitCode:1};let n=t.join(`-`),r=`https://www.sliccy.com/man/${n}.plain.html`;try{let t=await e(r,{method:`GET`});return t.status===404?{stdout:``,stderr:`No manual entry for ${n}\n`,exitCode:1}:t.status<200||t.status>=300?{stdout:``,stderr:`man: failed to fetch manual page for ${n}: ${t.status} ${t.statusText}\n`,exitCode:1}:{stdout:
|
|
6918
|
-
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`man: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const
|
|
6917
|
+
`,exitCode:1};let n=t.join(`-`),r=`https://www.sliccy.com/man/${n}.plain.html`;try{let t=await e(r,{method:`GET`});return t.status===404?{stdout:``,stderr:`No manual entry for ${n}\n`,exitCode:1}:t.status<200||t.status>=300?{stdout:``,stderr:`man: failed to fetch manual page for ${n}: ${t.status} ${t.statusText}\n`,exitCode:1}:{stdout:PV(new TextDecoder(`utf-8`).decode(t.body))+`
|
|
6918
|
+
`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`man: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}const IV=n(`mcp-command`),LV=`/workspace/.mcp/aliases`;function RV(e){return{stdout:e,stderr:``,exitCode:0}}function zV(e,t=1){return{stdout:``,stderr:`${e}\n`,exitCode:t}}function BV(){return`usage: mcp <command> [args]
|
|
6919
6919
|
|
|
6920
6920
|
Commands:
|
|
6921
6921
|
add <url> <name> Register an MCP server. Runs OAuth if required.
|
|
@@ -6937,7 +6937,7 @@ Examples:
|
|
|
6937
6937
|
mcp search forecast
|
|
6938
6938
|
mcp auth weather
|
|
6939
6939
|
mcp delete weather
|
|
6940
|
-
`}function
|
|
6940
|
+
`}function VV(e={}){return G(`mcp`,async t=>{if(t.length===0||t[0]===`--help`||t[0]===`-h`)return RV(BV());let n=t[0],r=t.slice(1);try{switch(n){case`add`:return await HV(r,e);case`list`:case`ls`:return await WV(r,e);case`delete`:case`rm`:return await JV(r,e);case`invoke`:return await YV(r,e);case`search`:return await KV(r,e);case`refresh`:return await oH(r,e);case`auth`:return await sH(r,e);default:return zV(`mcp: unknown subcommand "${n}" (try \`mcp --help\`)`)}}catch(e){let t=e instanceof Error?e.message:String(e);return IV.error(`mcp subcommand failed`,{sub:n,error:t}),e instanceof Mn?zV(`mcp ${n}: ${t}`,124):zV(`mcp ${n}: ${t}`)}})}async function HV(e,t){if(e.includes(`--help`)||e.includes(`-h`))return RV(`usage: mcp add <url> <name>
|
|
6941
6941
|
|
|
6942
6942
|
Probes <url> with an unauthenticated MCP \`initialize\`. If the server
|
|
6943
6943
|
returns 401, runs OAuth discovery → dynamic client registration → PKCE
|
|
@@ -6946,20 +6946,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
6946
6946
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
6947
6947
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
6948
6948
|
short name resolves on the PATH.
|
|
6949
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return
|
|
6949
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return zV(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return zV(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return zV(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-fjjsfL92.js`).then(e=>e.r);if(await a(i,t.fs))return zV(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CpLUc-P8.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 UV(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>lH(i)}),await l.initialize()}let d=await l.toolsList(),f=await l.appsList(),p=new Date().toISOString();await o(i,{url:r,tools:d,apps:f,addedAt:p,lastRefreshedAt:p,...u?{auth:u}:{}},t.fs),await hH(i,t);let m=await vH(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-P5X9hREk.js`);e({name:i,serverUrl:r,auth:u})}return RV([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${LV}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
6950
6950
|
`)+`
|
|
6951
|
-
`)}async function
|
|
6952
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
6951
|
+
`)}async function UV(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-R1mQ9-PX.js`),c=await fH(r.oauthFetchImpl),l=r.oauthLauncher??await uH(),u=await i(e,n,c);IV.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await dH(),f=await a(u,d,c),p=u.supportedScopes&&u.supportedScopes.length>0?u.supportedScopes.join(` `):void 0,m=await o({asMetadata:u,clientId:f.clientId,scope:p,redirectUri:d,launcher:l,fetchImpl:c}),h=`mcp:${t}`;return await s({providerId:h,accessToken:m.accessToken,refreshToken:m.refreshToken,tokenExpiresAt:m.expiresAt}),{providerId:h,authorizationServer:u.issuer,clientId:f.clientId,scope:m.scope??p,registrationClientUri:f.registrationClientUri}}async function WV(e,t){if(e.includes(`--help`)||e.includes(`-h`))return RV(`usage: mcp list
|
|
6952
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-P5X9hREk.js`);await n();let{listServers:r}=await import(`./store-fjjsfL92.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return RV("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 RV(GV(o))}function GV(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(`
|
|
6953
6953
|
`)+`
|
|
6954
|
-
`}async function
|
|
6954
|
+
`}async function KV(e,t){if(e[0]===`--help`||e[0]===`-h`)return RV(`usage: mcp search <query>
|
|
6955
6955
|
|
|
6956
6956
|
Case-insensitive substring search across the cached tools of every
|
|
6957
6957
|
registered MCP server. Matches tool name OR description and prints a
|
|
6958
6958
|
table of (server, tool, description, match-field) rows.
|
|
6959
|
-
`);if(e.length===0)return
|
|
6960
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
6959
|
+
`);if(e.length===0)return zV(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-P5X9hREk.js`);await i();let{listServers:a}=await import(`./store-fjjsfL92.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return RV("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 RV(`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,qV(e.description),e.match]);return RV(GV(l))}function qV(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function JV(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?zV(`mcp delete: expected <name>`):RV(`usage: mcp delete <name>
|
|
6960
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-P5X9hREk.js`);await r(n);let{deleteServer:a}=await import(`./store-fjjsfL92.js`).then(e=>e.r),o=await a(n,t.fs);await gH(n,t),await _H(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-R1mQ9-PX.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){IV.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?zV(`mcp delete: no server, alias, or account found for "${n}"`):RV([`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(`
|
|
6961
6961
|
`)+`
|
|
6962
|
-
`)}async function
|
|
6962
|
+
`)}async function YV(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?zV(`mcp invoke: expected <name>`):RV(QV());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-P5X9hREk.js`);await i(n);let{getServer:a}=await import(`./store-fjjsfL92.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return zV(`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 RV($V(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return zV(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=XV(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return RV(eH(n,l));let p=tH(d,l.inputSchema);if(!p.ok)return zV(`mcp invoke: ${p.error}`);let{McpClient:m}=await import(`./client-CpLUc-P8.js`).then(e=>e.n),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>lH(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=aH(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function XV(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=ZV(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=ZV(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 ZV(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 QV(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
6963
6963
|
|
|
6964
6964
|
mcp invoke <name> List tools on <name>.
|
|
6965
6965
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -6976,20 +6976,20 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
6976
6976
|
string/integer/number/boolean. Bare \`--flag\` (no value or "--" next)
|
|
6977
6977
|
is treated as true. Repeating a flag accumulates into an array when
|
|
6978
6978
|
the schema declares \`type: array\`.
|
|
6979
|
-
`}function
|
|
6979
|
+
`}function $V(e,t,n){let r=[];if(r.push(`MCP server "${e}" → ${t.url}`),n.length===0)r.push(" (no tools cached — run `mcp refresh "+e+"`)");else{r.push(``),r.push(`Tools:`);let t=n.reduce((e,t)=>Math.max(e,t.name.length),0);for(let e of n)r.push(` ${e.name.padEnd(t)} ${e.description??``}`.trimEnd());r.push(``),r.push(`Run \`${e} <tool> --help\` for tool-specific flags.`)}return r.join(`
|
|
6980
6980
|
`)+`
|
|
6981
|
-
`}function
|
|
6981
|
+
`}function eH(e,t){let n=t.inputSchema??{},r=n.properties??{},i=new Set(Array.isArray(n.required)?n.required:[]),a=[];a.push(`usage: ${e} ${t.name} [flags]`),t.description&&(a.push(``),a.push(t.description));let o=Object.keys(r);if(o.length===0)return a.push(``),a.push(`(no flags declared)`),a.join(`
|
|
6982
6982
|
`)+`
|
|
6983
6983
|
`;a.push(``),a.push(`Flags:`);let s=o.map(e=>{let t=r[e]??{};return` --${e} <${typeof t.type==`string`?t.type:`string`}>`}),c=s.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;e<o.length;e++){let t=o[e],n=r[t]??{},l=typeof n.description==`string`?n.description:``,u=i.has(t)?` (required)`:``;a.push(`${s[e].padEnd(c)} ${l}${u}`.trimEnd())}return a.join(`
|
|
6984
6984
|
`)+`
|
|
6985
|
-
`}function
|
|
6985
|
+
`}function tH(e,t){let n=t??{},r=n.properties??{},i=new Set(Array.isArray(n.required)?n.required:[]),a={},o=0;for(;o<e.length;){let t=nH(e,o,r,a);if(!t.ok)return t;o=t.nextIndex}for(let e of i)if(!(e in a))return{ok:!1,error:`missing required flag --${e}`};return{ok:!0,value:a}}function nH(e,t,n,r){let i=e[t];if(!i.startsWith(`--`))return{ok:!1,error:`unexpected positional argument "${i}"`};let{key:a,inlineValue:o}=rH(i),s=n[a],c=typeof s?.type==`string`?s.type:`string`,l=c===`array`,u=l&&s?.items&&typeof s.items.type==`string`?s.items.type:`string`,d=o,f;if(d===void 0){let n=e[t+1];if(c===`boolean`&&(n===void 0||n.startsWith(`--`)))return r[a]=!0,{ok:!0,nextIndex:t+1};if(n===void 0)return{ok:!1,error:`flag --${a} requires a value`};d=n,f=t+2}else f=t+1;let p=iH(d,l?u:c);if(!p.ok)return{ok:!1,error:`--${a}: ${p.error}`};if(l){let e=r[a];Array.isArray(e)?e.push(p.value):r[a]=[p.value]}else r[a]=p.value;return{ok:!0,nextIndex:f}}function rH(e){let t=e.indexOf(`=`);return t>2?{key:e.slice(2,t),inlineValue:e.slice(t+1)}:{key:e.slice(2),inlineValue:void 0}}function iH(e,t){switch(t){case`integer`:return/^-?\d+$/.test(e)?{ok:!0,value:Number(e)}:{ok:!1,error:`expected integer, got "${e}"`};case`number`:{let t=Number(e);return Number.isFinite(t)?{ok:!0,value:t}:{ok:!1,error:`expected number, got "${e}"`}}case`boolean`:return e===`true`||e===`1`||e===`yes`?{ok:!0,value:!0}:e===`false`||e===`0`||e===`no`?{ok:!0,value:!1}:{ok:!1,error:`expected boolean, got "${e}"`};default:return{ok:!0,value:e}}}function aH(e){let t=e??{},n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n)if(!(!e||typeof e!=`object`))switch(e.type){case`text`:typeof e.text==`string`&&r.push(e.text);break;case`image`:r.push(`[image: ${e.mimeType??`unknown mime`}]`);break;case`resource`:{let t=e.resource?.uri??e.uri??`unknown uri`;r.push(`[resource: ${t}]`);break}default:r.push(`[${e.type??`unknown`}]`)}let i=r.join(`
|
|
6986
6986
|
`),a=i.endsWith(`
|
|
6987
6987
|
`)?``:`
|
|
6988
|
-
`;return t.isError?{stdout:``,stderr:(i||`(tool reported error)`)+a,exitCode:1}:{stdout:i+(i?a:``),stderr:``,exitCode:0}}async function
|
|
6988
|
+
`;return t.isError?{stdout:``,stderr:(i||`(tool reported error)`)+a,exitCode:1}:{stdout:i+(i?a:``),stderr:``,exitCode:0}}async function oH(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?zV(`mcp refresh: expected <name>`):RV(`usage: mcp refresh <name>
|
|
6989
6989
|
|
|
6990
6990
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
6991
6991
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
6992
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
6992
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-P5X9hREk.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-fjjsfL92.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return zV(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await import(`./client-CpLUc-P8.js`).then(e=>e.n),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>lH(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return zV(`mcp refresh: server "${n}" returned 401 — token may have expired. Run \`mcp auth ${n}\` to re-authenticate.`);throw e}let u=await l.toolsList(),d=await l.appsList();await a(n,{...o,sessionId:void 0,tools:u,apps:d,lastRefreshedAt:new Date().toISOString()},t.fs);let f=await vH(n,d,t);return RV(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function sH(e,t){if(e.includes(`--help`)||e.includes(`-h`))return RV(`usage: mcp auth <name> [--silent | --interactive]
|
|
6993
6993
|
|
|
6994
6994
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
6995
6995
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -7001,7 +7001,7 @@ Options:
|
|
|
7001
7001
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
7002
7002
|
directly. Use after revoking a refresh token or
|
|
7003
7003
|
when the AS no longer accepts the cached one.
|
|
7004
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return
|
|
7004
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return zV(`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 zV(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-P5X9hREk.js`),s=await o(r),{getServer:c}=await import(`./store-fjjsfL92.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return zV(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return zV(`mcp auth: server "${r}" does not use OAuth`);if(!s)return zV(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-BXwvtxEC.js`).then(e=>e.r),f=d(u);if(!f)return zV(`mcp auth: provider "${u}" is not registered`);if(a)return await cH(r,f,t);if(!f.onSilentRenew)return i?zV(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await cH(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 zV(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);IV.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?RV(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?zV(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await cH(r,f,t)}async function cH(e,t,n){if(!t.onOAuthLogin)return zV(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await uH(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?RV(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):zV(`mcp auth: interactive login for "${e}" did not complete`)}async function lH(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-R1mQ9-PX.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-BXwvtxEC.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){IV.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function uH(){let{createOAuthLauncher:e}=await import(`./oauth-service-DSuwOpMz.js`);return e()}async function dH(){if(ue()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-DSuwOpMz.js`),{origin:t}=await e();return`${t}/auth/callback`}async function fH(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),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 pH(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-BZ8jCbhy.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await import(`./global-db-DvmmimLY.js`).then(e=>e.n);return await t.create({dbName:n})}function mH(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
7005
7005
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
7006
7006
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
7007
7007
|
const escape = (s) => {
|
|
@@ -7015,7 +7015,7 @@ const r = await exec(cmd);
|
|
|
7015
7015
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
7016
7016
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
7017
7017
|
process.exit(r.exitCode || 0);
|
|
7018
|
-
`}async function
|
|
7018
|
+
`}async function hH(e,t){let n=await pH(t.fs);await n.mkdir(LV,{recursive:!0}),await n.writeFile(`${LV}/${e}.jsh`,mH(e)),t.scriptCatalog?.invalidateJsh()}async function gH(e,t){let n=await pH(t.fs),r=`${LV}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){IV.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function _H(e,t){let{removeAppSprinkles:n}=await import(`./apps-Bf1H6-85.js`);await n(e,t.fs)}async function vH(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-Bf1H6-85.js`);return(await r(e,t,n.fs)).length}catch(t){return IV.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const yH=`/.cache/artificial-analysis.json`;async function bH(e,t=!1){if(e&&!t)try{let t=await e.readFile(yH),n=JSON.parse(t);if(Date.now()-n.fetchedAt<864e5)return n.models}catch{}let n=null;try{n=localStorage.getItem(`aa_api_key`)}catch{}let r={Accept:`application/json`};n&&(r[`x-api-key`]=n);let i=l(),a;try{a=await i(`https://artificialanalysis.ai/api/v2/data/llms/models`,{method:`GET`,headers:r})}catch{return[]}if(a.status===401||a.status<200||a.status>=300)return[];let o;try{let e=new TextDecoder().decode(a.body);o=JSON.parse(e)}catch{return[]}let s=(Array.isArray(o)?o:o?.data??o?.models??[]).map(e=>({slug:e.slug??``,name:e.name??``,creator_slug:e.model_creator?.slug??``,intelligence_index:e.evaluations?.artificial_analysis_intelligence_index??null,coding_index:e.evaluations?.artificial_analysis_coding_index??null,speed_tps:e.median_output_tokens_per_second??null}));if(e&&s.length>0){let t={fetchedAt:Date.now(),models:s};try{await e.mkdir(`/.cache`,{recursive:!0}),await e.writeFile(yH,JSON.stringify(t))}catch{}}return s}function xH(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function SH(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=xH(e),a=t.find(e=>xH(e.slug)===i);if(a)return a;let o=t.filter(e=>n.includes(e.slug)||e.slug.includes(n));if(o.length>0)return o.sort((e,t)=>t.slug.length-e.slug.length),o[0]}function CH(){return`models - list available LLM models
|
|
7019
7019
|
|
|
7020
7020
|
Usage: models [options]
|
|
7021
7021
|
|
|
@@ -7027,24 +7027,24 @@ Options:
|
|
|
7027
7027
|
--refresh Force re-fetch benchmark data from Artificial Analysis
|
|
7028
7028
|
--no-benchmarks Skip benchmark data enrichment (faster, works offline)
|
|
7029
7029
|
-h, --help Show this help message
|
|
7030
|
-
`}function
|
|
7030
|
+
`}function wH(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function TH(e){return`$${e.toFixed(2)}`}const EH=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function DH(e){let t=`${e.id} ${e.name??``}`;return!EH.test(t)}function OH(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 kH(e){let t=new Map;for(let n of e){let e=OH(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function AH(e,t,n,r,i){let a=i?SH(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 jH(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=`${TH(e.cost.input)} / ${TH(e.cost.output)}`,a=`${wH(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(`
|
|
7031
7031
|
`)+`
|
|
7032
|
-
`}function
|
|
7033
|
-
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await
|
|
7032
|
+
`}function MH(e){return G(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-R1mQ9-PX.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:CH(),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.
|
|
7033
|
+
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await bH(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(DH);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>AH(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=kH(n)),w.push(...n),!l){let t=i(e);T.push(jH(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
7034
7034
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
7035
7035
|
`);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(`
|
|
7036
|
-
`),stderr:``,exitCode:0}})}function
|
|
7037
|
-
`,stderr:``,exitCode:0}}function
|
|
7038
|
-
`,exitCode:9};r=t[1],i=`[eval]`,a=[`node`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let e=t[0],o=n.fs.resolvePath(n.cwd,e);if(!await n.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${e}'\n`,exitCode:1};r=await n.fs.readFile(o),i=o,a=[`node`,o,...t.slice(1)]}else if(
|
|
7039
|
-
`,exitCode:9};return
|
|
7036
|
+
`),stderr:``,exitCode:0}})}function NH(){return{stdout:`usage: node -e <code> [args...]
|
|
7037
|
+
`,stderr:``,exitCode:0}}function PH(){return{stdout:`${yn}\n`,stderr:``,exitCode:0}}function FH(e={}){return{name:`node`,trusted:!0,async execute(t,n){if(t.includes(`--help`)||t.includes(`-h`))return NH();if(t.includes(`--version`)||t.includes(`-v`))return PH();let r=``,i,a,o=n;if(t.length>0&&(t[0]===`-e`||t[0]===`--eval`)){if(!t[1])return{stdout:``,stderr:`node: option requires an argument -- eval
|
|
7038
|
+
`,exitCode:9};r=t[1],i=`[eval]`,a=[`node`,...t.slice(2)]}else if(t.length>0&&!t[0].startsWith(`-`)){let e=t[0],o=n.fs.resolvePath(n.cwd,e);if(!await n.fs.exists(o))return{stdout:``,stderr:`node: cannot find module '${e}'\n`,exitCode:1};r=await n.fs.readFile(o),i=o,a=[`node`,o,...t.slice(1)]}else if(Pk(n.stdin).trim().length>0)r=Pk(n.stdin),i=`<stdin>`,a=[`node`],o={...n,stdin:``};else if(t.length>0)return{stdout:``,stderr:`node: unsupported option '${t[0]}'\n`,exitCode:9};else return{stdout:``,stderr:`node: REPL mode is not supported in this environment; use node -e "code"
|
|
7039
|
+
`,exitCode:9};return Lk(IE(r),a,o,e.buildProcessConfig?.(),{filename:i})}}}const IH=[`slicc:welcome-flow-fired`,`slicc.trayJoinUrl`,`slicc.trayWorkerBaseUrl`];async function LH(){try{let e=await navigator.serviceWorker?.getRegistrations?.();e&&await Promise.all(e.map(e=>e.unregister().catch(()=>!1)))}catch{}try{let e=await indexedDB.databases();await Promise.all(e.filter(e=>!!e.name).map(e=>new Promise(t=>{let n=indexedDB.deleteDatabase(e.name);n.onsuccess=()=>t(),n.onerror=()=>t(),n.onblocked=()=>t()})))}catch{}try{let e=navigator.storage;if(typeof e?.getDirectory==`function`){let t=await e.getDirectory(),n=[];for await(let e of t.keys())n.push(e);await Promise.all(n.map(e=>t.removeEntry(e,{recursive:!0}).catch(()=>{})))}}catch{}}function RH(){return G(`nuke`,async e=>e.includes(`--help`)||e.includes(`-h`)?{stdout:`Usage: nuke <launch-code>
|
|
7040
7040
|
|
|
7041
7041
|
Completely reset the environment by deleting all local data and reloading.
|
|
7042
7042
|
Destroys the file system, chat history, and scoops database.
|
|
7043
7043
|
Requires the secret launch code to proceed.
|
|
7044
|
-
`,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{await
|
|
7044
|
+
`,stderr:``,exitCode:0}:e.join(``).includes(`1234`)?((async()=>{await LH(),zH(IH)})(),{stdout:`Nuking everything…
|
|
7045
7045
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`⚠️ WARNING: this will reset the entire environment, file system, chats, and scoops.
|
|
7046
7046
|
Run nuke again with the secret launch code to proceed.
|
|
7047
|
-
`,exitCode:1})}function
|
|
7047
|
+
`,exitCode:1})}function zH(e=[]){let t=[...e];try{if(typeof BroadcastChannel==`function`){let e=new BroadcastChannel(`slicc-nuke-control`);e.postMessage({type:`nuke-reload`,keysToRemove:t}),setTimeout(()=>e.close(),100)}}catch{}for(let e of t)try{globalThis.localStorage?.removeItem(e)}catch{}try{globalThis.location?.reload?.()}catch{}}function BH(){return`oauth-domain — manage extra allowed domains for OAuth-issued tokens
|
|
7048
7048
|
|
|
7049
7049
|
Usage:
|
|
7050
7050
|
oauth-domain list List extra domains for every provider
|
|
@@ -7069,7 +7069,7 @@ Examples:
|
|
|
7069
7069
|
oauth-domain add adobe '*.da.live'
|
|
7070
7070
|
oauth-domain list adobe
|
|
7071
7071
|
oauth-domain remove adobe admin.da.live
|
|
7072
|
-
`}function
|
|
7072
|
+
`}function VH(){return G(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:BH(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-R1mQ9-PX.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(`
|
|
7073
7073
|
`)+`
|
|
7074
7074
|
`,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)
|
|
7075
7075
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -7077,7 +7077,7 @@ Examples:
|
|
|
7077
7077
|
`,stderr:``,exitCode:0}}case`add`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain add: requires <providerId> and <domain>
|
|
7078
7078
|
`,exitCode:1};let e=t(a),r=o.toLowerCase();return e.some(e=>e.toLowerCase()===r)?{stdout:`(${o} already in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,[...e,o]),{stdout:`Added ${o} to ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`remove`:{if(!a||!o)return{stdout:``,stderr:`oauth-domain remove: requires <providerId> and <domain>
|
|
7079
7079
|
`,exitCode:1};let e=t(a),r=o.toLowerCase(),i=e.filter(e=>e.toLowerCase()!==r);return i.length===e.length?{stdout:`(${o} not found in ${a} extras)\n`,stderr:``,exitCode:0}:(await n(a,i),{stdout:`Removed ${o} from ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0})}case`clear`:return a?(await n(a,[]),{stdout:`Cleared extra domains for ${a}. Reload the page to apply.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`oauth-domain clear: requires <providerId>
|
|
7080
|
-
`,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${
|
|
7080
|
+
`,exitCode:1};default:return{stdout:``,stderr:`oauth-domain: unknown subcommand "${i}"\n${BH()}`,exitCode:1}}}catch(e){return{stdout:``,stderr:`oauth-domain: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function HH(){return`oauth-token — get an OAuth access token for a provider, or run an
|
|
7081
7081
|
ad-hoc OAuth interception against an arbitrary authorize URL.
|
|
7082
7082
|
|
|
7083
7083
|
Usage:
|
|
@@ -7127,16 +7127,16 @@ Examples:
|
|
|
7127
7127
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
7128
7128
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
7129
7129
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
7130
|
-
`}function
|
|
7130
|
+
`}function UH(){return G(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-R1mQ9-PX.js`),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-BXwvtxEC.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:HH(),stderr:``,exitCode:0};if(e.includes(`--list`))return YH(i,o,a,n);if(e.includes(`--renew`))return WH(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return KH(e,t);let s,c=e.indexOf(`--scope`);if(c>=0){if(s=e[c+1]?.trim(),!s||s.startsWith(`-`))return{stdout:``,stderr:`oauth-token: --scope requires a value
|
|
7131
7131
|
`,exitCode:1};e.splice(c,2)}let l,u=e.indexOf(`--provider`);if(u>=0){if(l=e[u+1],!l)return{stdout:``,stderr:`oauth-token: --provider requires a value
|
|
7132
7132
|
`,exitCode:1}}else if(e.length>0)l=e[0];else{let e=r(),t=a(e);if(t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted))l=e;else if(l=o().find(e=>{let t=a(e);return t?.isOAuth&&(t.onOAuthLogin||t.onOAuthLoginIntercepted)}),!l)return{stdout:``,stderr:`oauth-token: no OAuth providers configured
|
|
7133
7133
|
`,exitCode:1}}let d=a(l);if(!d)return{stdout:``,stderr:`oauth-token: unknown provider "${l}"\n`,exitCode:1};if(!d.isOAuth||!d.onOAuthLogin&&!d.onOAuthLoginIntercepted)return{stdout:``,stderr:`oauth-token: provider "${l}" is not an OAuth provider\n`,exitCode:1};if(!s){let e=n(l);if(e&&!e.expired){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}}try{if(d.onOAuthLoginIntercepted){let{createInterceptingOAuthLauncherForCurrentRuntime:e}=await import(`./oauth-service-DSuwOpMz.js`),t=await e();if(!t)return{stdout:``,stderr:`oauth-token: provider "${l}" needs the controlled-browser interceptor, but no CDP transport is available in this runtime.\n`,exitCode:1};await d.onOAuthLoginIntercepted(t,()=>{},s?{scopes:s}:void 0)}else if(d.onOAuthLogin){let{createOAuthLauncher:e}=await import(`./oauth-service-DSuwOpMz.js`),t=e();await d.onOAuthLogin(t,()=>{},s?{scopes:s}:void 0)}else return{stdout:``,stderr:`oauth-token: provider "${l}" has no OAuth login hook\n`,exitCode:1};let e=n(l);if(e?.token){let t=e.maskedValue;return t?{stdout:`${t}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`oauth-token: no masked value for ${l} (try logging in again)\n`,exitCode:1}}return console.error(`[oauth-token] Provider ${l}: login completed but no token was saved`),{stdout:``,stderr:`oauth-token: login completed but no token was saved
|
|
7134
|
-
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function
|
|
7134
|
+
`,exitCode:1}}catch(e){let t=e instanceof Error?e.message:String(e);return console.error(`[oauth-token] Provider ${l}: login failed:`,t),{stdout:``,stderr:`oauth-token: login failed: ${t}\n`,exitCode:1}}})}async function WH(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-R1mQ9-PX.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-BXwvtxEC.js`).then(e=>e.r),a=e.filter(e=>!e.startsWith(`-`))[0];if(!a){let e=t();a=r(e)?.onSilentRenew?e:i().find(e=>r(e)?.onSilentRenew)}if(!a)return JH(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return JH(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return JH(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${GH(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: ${GH(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(`
|
|
7135
7135
|
`)+`
|
|
7136
|
-
`,stderr:``,exitCode:+!u}}function
|
|
7136
|
+
`,stderr:``,exitCode:+!u}}function GH(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 KH(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-DSuwOpMz.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return JH(`oauth-token: --from-file requires a path`);try{let e=t.fs.resolvePath(t.cwd,n),r=await t.fs.readFile(e);i=JSON.parse(typeof r==`string`?r:new TextDecoder().decode(r))}catch(e){return JH(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=qH(e,`--authorize-url`),n=qH(e,`--redirect-pattern`);if(!t)return JH(`oauth-token: --authorize-url is required`);if(!n)return JH(`oauth-token: --redirect-pattern is required`);let r=[];for(let t=0;t<e.length;t++){if(e[t]!==`--rewrite`)continue;let n=e[t+1];if(!n)return JH(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return JH(`oauth-token: --rewrite "${n}" must be "<match>=<key>=<value>"`);let[a,o,...s]=i;r.push({match:a,appendParams:{[o]:s.join(`=`)}})}i={authorizeUrl:t,redirectUriPattern:n,onCapture:e.includes(`--leave-tab`)?`leave`:`close`,...r.length>0?{rewrite:r}:{}}}let o=n(i);if(!o.ok)return JH(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return JH(`oauth-token: no CDP transport available in this runtime; --intercept needs the controlled browser.`);let c=await s(o.config);return c?{stdout:`${c}\n`,stderr:``,exitCode:0}:JH(`oauth-token: intercept timed out or was cancelled`)}function qH(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function JH(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function YH(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
7137
7137
|
`,stderr:``,exitCode:0};let a=[];for(let e of i){let t=r(e);if(!t)a.push(`${e} (no token)`);else if(t.expired){let n=t.userName?` as ${t.userName}`:``;a.push(`${e} (expired${n})`)}else{let n=[];if(t.userName?n.push(`logged in as ${t.userName}`):n.push(`logged in`),t.expiresAt){let e=t.expiresAt-Date.now();if(e>0){let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4);t>0?n.push(`expires in ${t}h`):n.push(`expires in ${r}m`)}}a.push(`${e} (${n.join(`, `)})`)}}return{stdout:a.join(`
|
|
7138
7138
|
`)+`
|
|
7139
|
-
`,stderr:``,exitCode:0}}const
|
|
7139
|
+
`,stderr:``,exitCode:0}}const XH=new Set([`--download`,`-d`,`--view`,`-v`]),ZH={low:256,medium:768,high:1536};function QH(){return{stdout:`usage: open [--download|-d] [--view|-v [--size <spec>]] <url|path> [url|path...]
|
|
7140
7140
|
|
|
7141
7141
|
VFS paths are served in a new browser tab via the preview service worker.
|
|
7142
7142
|
URLs (http/https/etc.) are opened directly in a new tab.
|
|
@@ -7150,19 +7150,19 @@ Examples:
|
|
|
7150
7150
|
medium (768x768), high (1536x1536), or a custom WxH
|
|
7151
7151
|
box like 512x512. The image is fit inside the box
|
|
7152
7152
|
with aspect ratio preserved and is never upscaled.
|
|
7153
|
-
`,stderr:``,exitCode:0}}function
|
|
7153
|
+
`,stderr:``,exitCode:0}}function $H(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function eU(e){if(e in ZH){let t=ZH[e];return{maxW:t,maxH:t}}let t=/^(\d+)x(\d+)$/.exec(e);if(t){let e=parseInt(t[1],10),n=parseInt(t[2],10);if(e>0&&n>0)return{maxW:e,maxH:n}}return null}function tU(e,t){if(t===`image/png`||t===`image/apng`){if(e.length<26)return!1;let t=e[25];return t===4||t===6}if(t===`image/webp`){if(e.length<16)return!1;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);return t===`VP8L`?!0:t===`VP8X`?e.length<21?!1:(e[20]&16)!=0:!1}return!1}function nU(){return`open --view requires --size to bound the inlined image. Use one of:
|
|
7154
7154
|
--size low (256x256)
|
|
7155
7155
|
--size medium (768x768)
|
|
7156
7156
|
--size high (1536x1536)
|
|
7157
7157
|
--size WxH (custom box, e.g. 512x512)
|
|
7158
|
-
`}const
|
|
7159
|
-
`)}async function
|
|
7160
|
-
`);let r;try{r=await n(e)}catch(e){return
|
|
7161
|
-
`);let i;try{i=await n.fs.stat(t)}catch{return
|
|
7162
|
-
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=xn(e,await hn(t.fs,i?e:dn(e))),o;try{o=await r(a)}catch(e){return
|
|
7163
|
-
`);if(sn(e))return
|
|
7158
|
+
`}const rU=new Set([`image/png`,`image/webp`]);function iU(e){let t=new ArrayBuffer(e.byteLength),n=new Uint8Array(t);return n.set(e),n}async function aU(e,t){let n=iU(e),r=new Blob([n],{type:t}),i=await createImageBitmap(r);try{return{width:i.width,height:i.height}}finally{i.close?.()}}async function oU(e,t,n,r){let i=iU(e),a=new Blob([i],{type:t}),o=await createImageBitmap(a);try{let i=o.width,a=o.height,s=Math.min(n/i,r/a,1),c=Math.max(1,Math.round(i*s)),l=Math.max(1,Math.round(a*s)),u=new OffscreenCanvas(c,l),d=u.getContext(`2d`);if(!d)throw Error(`failed to acquire 2d context for resize`);d.drawImage(o,0,0,c,l);let f=tU(e,t)?rU.has(t)?t:`image/png`:`image/jpeg`,p=await u.convertToBlob(f===`image/jpeg`?{type:`image/jpeg`,quality:.85}:{type:f});return{bytes:new Uint8Array(await p.arrayBuffer()),mime:f,width:c,height:l,nativeWidth:i,nativeHeight:a}}finally{o.close?.()}}function sU(e){let t={download:!1,view:!1,sizeSpec:void 0,targets:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`--download`||r===`-d`)t.download=!0;else if(r===`--view`||r===`-v`)t.view=!0;else if(r===`--size`){let r=e[n+1];if(r===void 0||XH.has(r)||r===`--size`||r.startsWith(`--size=`))return t.error=`open: --size requires a value (low|medium|high|WxH)`,t;t.sizeSpec=r,n++}else r.startsWith(`--size=`)?t.sizeSpec=r.slice(7):t.targets.push(r)}return t}function cU(e){return{ok:!0,message:e}}function lU(e){return{ok:!1,result:{stdout:``,stderr:e,exitCode:1}}}function uU(e){return e?` (targetId: ${e})`:``}function dU(e,t,n){return async r=>{if(e)return e.createPage(r);if(t){window.open(r,`_blank`,`noopener,noreferrer`);return}try{await n.call(`window-open`,{url:r,target:`_blank`,features:`noopener,noreferrer`})}catch(e){throw Error(`open: ${e instanceof Error?e.message:String(e)}`)}}}async function fU(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,e);if(n){let e=(a.split(`/`).pop()??``).replace(/\.shtml$/,``);try{return await n.open(e),cU(`opened sprinkle ${e} from ${a}`)}catch(e){return lU(`open: ${e instanceof Error?e.message:String(e)}\n`)}}if(r){let e=xn(a,await hn(t.fs,dn(a))),n;try{n=await i(e)}catch(e){return lU(`${e instanceof Error?e.message:String(e)}\n`)}return cU(`opened ${a} → ${e}${uU(n)}`)}return lU(`open: sprinkle manager not initialized
|
|
7159
|
+
`)}async function pU(e,t,n){if(!t)return lU(`open: browser APIs are unavailable in this environment
|
|
7160
|
+
`);let r;try{r=await n(e)}catch(e){return lU(`${e instanceof Error?e.message:String(e)}\n`)}return cU(`opened ${e}${uU(r)}`)}async function mU(e,t,n,r){let i;try{i=await n.fs.stat(t)}catch{return lU(`open: no such file: ${e}\n`)}if(!i.isFile)return lU(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return lU(`open: failed to read: ${e}\n`)}let o=_n(t),s=new Uint8Array(a),c=null;if(r!==void 0&&(c=eU(r),!c))return lU(`open: invalid --size spec '${r}' (expected low|medium|high or WxH such as 512x512)\n`);if(!c){let n;try{n=await aU(s,o)}catch(t){return lU(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let r=Math.round(s.byteLength/1024);return lU(`open --view: ${t} is ${n.width}x${n.height} (${r} KB, ${o})\n`+nU())}let l;try{l=await oU(s,o,c.maxW,c.maxH)}catch(t){return lU(`open: not an image or failed to decode: ${e} (${t instanceof Error?t.message:String(t)})\n`)}let u=$H(l.bytes),d=Math.round(l.bytes.byteLength/1024);return cU(`${t} (${l.nativeWidth}x${l.nativeHeight} → ${l.width}x${l.height}, ${d} KB, ${l.mime})\n<img:data:${l.mime};base64,${u}>`)}async function hU(e,t,n,r){if(!r)return lU(`open: --download requires the in-panel terminal (DOM-only)
|
|
7161
|
+
`);let i;try{i=await n.fs.stat(t)}catch{return lU(`open: no such file: ${e}\n`)}if(!i.isFile)return lU(`open: not a file: ${e}\n`);let a;try{a=await n.fs.readFileBuffer(t)}catch{return lU(`open: failed to read: ${e}\n`)}let o=new Uint8Array(a.byteLength);o.set(a);let s=new Blob([o.buffer],{type:_n(t)}),c=URL.createObjectURL(s),l=document.createElement(`a`);return l.href=c,l.download=mn(t)||`download`,l.style.display=`none`,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(c),0),cU(`downloaded ${t}`)}async function gU(e,t,n,r){if(!n)return lU(`open: browser APIs are unavailable in this environment
|
|
7162
|
+
`);let i=!1;try{i=(await t.fs.stat(e)).isDirectory}catch{}let a=xn(e,await hn(t.fs,i?e:dn(e))),o;try{o=await r(a)}catch(e){return lU(`${e instanceof Error?e.message:String(e)}\n`)}return cU(`opened ${e} → ${a}${uU(o)}`)}async function _U(e,t,n,r){if(!sn(e)&&e.endsWith(`.shtml`)&&t.fs)return fU(e,t,r.sprinkleManager,r.canOpenWindow,r.openExternal);if(!n.view&&!r.canOpenWindow)return lU(`open: browser APIs are unavailable in this environment
|
|
7163
|
+
`);if(sn(e))return pU(e,r.canOpenWindow,r.openExternal);let i=t.fs.resolvePath(t.cwd,e);return n.view?mU(e,i,t,n.sizeSpec):n.download?hU(e,i,t,r.hasDom):gU(i,t,r.canOpenWindow,r.openExternal)}function vU(e){return G(`open`,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return QH();let r=sU(t);if(r.error)return{stdout:``,stderr:`${r.error}\n`,exitCode:1};let{download:i,view:a,sizeSpec:o,targets:s}=r;if(s.length===0)return QH();let c=globalThis.__slicc_sprinkleManager,l=typeof window<`u`&&typeof document<`u`,u=l?null:He(),d={canOpenWindow:!!e||l||!!u,hasDom:l,sprinkleManager:c,openExternal:dU(e,l,u)},f=[];for(let e of s){let t=await _U(e,n,{view:a,download:i,sizeSpec:o},d);if(!t.ok)return t.result;f.push(t.message)}return{stdout:f.join(`
|
|
7164
7164
|
`)+`
|
|
7165
|
-
`,stderr:``,exitCode:0}})}let
|
|
7165
|
+
`,stderr:``,exitCode:0}})}let yU=null,bU=null;async function xU(){return yU||=import(`./es-CP2z28j0.js`),yU}async function SU(){return bU||=import(`./dist-Cc2eS9kS.js`),bU}function CU(e){return e.endsWith(`right`)?{range:e.slice(0,-5),rotation:90}:e.endsWith(`left`)?{range:e.slice(0,-4),rotation:270}:e.endsWith(`down`)?{range:e.slice(0,-4),rotation:180}:{range:e}}function wU(e){let{range:t,rotation:n}=CU(e);if(/^\d+$/.test(t)){let e=parseInt(t,10);return{start:e,end:e,rotation:n}}let r=t.match(/^(\d+)-(\d+|end)$/);if(r)return{start:parseInt(r[1],10),end:r[2]===`end`?`end`:parseInt(r[2],10),rotation:n};throw Error(`Invalid page range: ${e}`)}function TU(e,t){let n=e.start,r=e.end;if(n<1||n>t)throw Error(`Page ${n} out of range (1-${t})`);let i=r===`end`?t:r;if(i<1||i>t)throw Error(`Page ${i} out of range (1-${t})`);if(i<n)throw Error(`Invalid range: ${n}-${i}`);let a=[];for(let e=n;e<=i;e++)a.push(e);return a}function EU(){return{stdout:`usage: pdftk <input.pdf> <operation> [args...]
|
|
7166
7166
|
|
|
7167
7167
|
Operations:
|
|
7168
7168
|
dump_data Print metadata (page count, title, author, etc.)
|
|
@@ -7186,14 +7186,14 @@ Page ranges:
|
|
|
7186
7186
|
1-endright Pages 1 to end, rotated 90° clockwise
|
|
7187
7187
|
3left Page 3 rotated 270° (counterclockwise)
|
|
7188
7188
|
1-5down Pages 1-5 rotated 180°
|
|
7189
|
-
`,stderr:``,exitCode:0}}function
|
|
7189
|
+
`,stderr:``,exitCode:0}}function DU(e=`pdftk`){return G(e,async(t,n)=>{if(t.length===0||t.includes(`--help`)||t.includes(`-h`))return EU();try{let r=[],i=0;for(;i<t.length;){let e=t[i],a=e.match(/^([A-Z])=(.+)$/);if(a){let e=a[1],t=n.fs.resolvePath(n.cwd,a[2]);r.push({handle:e,path:t}),i++;continue}if([`dump_data`,`dump_data_utf8`,`cat`,`rotate`].includes(e))break;if(!e.startsWith(`-`)){let t=n.fs.resolvePath(n.cwd,e);r.push({handle:``,path:t}),i++;continue}break}if(r.length===0)return{stdout:``,stderr:`${e}: no input PDF specified\n`,exitCode:1};let a=t[i];if(i++,!a)return{stdout:``,stderr:`${e}: no operation specified\n`,exitCode:1};if(a===`dump_data`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data only supports a single input file\n`,exitCode:1};let t=await xU(),i=await n.fs.readFileBuffer(r[0].path),a=await t.PDFDocument.load(i),o=[];o.push(`NumberOfPages: ${a.getPageCount()}`);let s=a.getTitle();s&&o.push(`InfoBegin`),s&&o.push(`InfoKey: Title`),s&&o.push(`InfoValue: ${s}`);let c=a.getAuthor();c&&o.push(`InfoBegin`),c&&o.push(`InfoKey: Author`),c&&o.push(`InfoValue: ${c}`);let l=a.getCreator();l&&o.push(`InfoBegin`),l&&o.push(`InfoKey: Creator`),l&&o.push(`InfoValue: ${l}`);let u=a.getProducer();return u&&o.push(`InfoBegin`),u&&o.push(`InfoKey: Producer`),u&&o.push(`InfoValue: ${u}`),{stdout:o.join(`
|
|
7190
7190
|
`)+`
|
|
7191
|
-
`,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await
|
|
7192
|
-
`,stderr:``,exitCode:0}}if(a===`cat`){let a=await
|
|
7193
|
-
`,exitCode:1};let r=
|
|
7194
|
-
`,exitCode:2};let a=
|
|
7191
|
+
`,stderr:``,exitCode:0}}if(a===`dump_data_utf8`){if(r.length>1)return{stdout:``,stderr:`${e}: dump_data_utf8 only supports a single input file\n`,exitCode:1};let t=await SU(),i=await n.fs.readFileBuffer(r[0].path);return{stdout:(await t.extractText(i)).text+`
|
|
7192
|
+
`,stderr:``,exitCode:0}}if(a===`cat`){let a=await xU(),o=await a.PDFDocument.create(),s=t.slice(i),c=s.indexOf(`output`);if(c===-1)return{stdout:``,stderr:`${e}: cat operation requires 'output <filename>'\n`,exitCode:1};let l=s.slice(0,c),u=s[c+1];if(!u)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let d=n.fs.resolvePath(n.cwd,u),f=new Map;for(let e of r){let t=await n.fs.readFileBuffer(e.path),r=await a.PDFDocument.load(t),i=e.handle||`default`;f.set(i,r)}for(let t of l){if(/^[A-Z]$/.test(t)){let n=f.get(t);if(!n)return{stdout:``,stderr:`${e}: unknown handle '${t}'\n`,exitCode:1};let r=n.getPageCount(),i=Array.from({length:r},(e,t)=>t);(await o.copyPages(n,i)).forEach(e=>{o.addPage(e)});continue}let n=f.get(r[0].handle||`default`);if(!n)return{stdout:``,stderr:`${e}: no default input document\n`,exitCode:1};let i=n.getPageCount(),s=wU(t),c=TU(s,i).map(e=>e-1),l=await o.copyPages(n,c);for(let e of l)s.rotation&&e.setRotation(a.degrees(s.rotation)),o.addPage(e)}let p=await o.save();return await n.fs.writeFile(d,p),{stdout:`Created ${u}\n`,stderr:``,exitCode:0}}if(a===`rotate`){if(r.length>1)return{stdout:``,stderr:`${e}: rotate only supports a single input file\n`,exitCode:1};let a=await xU(),o=await n.fs.readFileBuffer(r[0].path),s=await a.PDFDocument.load(o),c=t.slice(i),l=c.indexOf(`output`);if(l===-1)return{stdout:``,stderr:`${e}: rotate operation requires 'output <filename>'\n`,exitCode:1};let u=c.slice(0,l),d=c[l+1];if(!d)return{stdout:``,stderr:`${e}: output filename not specified\n`,exitCode:1};let f=n.fs.resolvePath(n.cwd,d),p=s.getPageCount(),m=new Map;for(let t of u){let n=wU(t);if(!n.rotation)return{stdout:``,stderr:`${e}: rotation suffix required (right/left/down) for range '${t}'\n`,exitCode:1};let r=TU(n,p);for(let e of r)m.set(e-1,n.rotation)}let h=s.getPages();for(let[e,t]of m.entries()){let n=h[e],r=(n.getRotation().angle+t)%360;n.setRotation(a.degrees(r))}let g=await s.save();return await n.fs.writeFile(f,g),{stdout:`Created ${d}\n`,stderr:``,exitCode:0}}return{stdout:``,stderr:`${e}: unknown operation '${a}'\n`,exitCode:1}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}const OU=[`pid`,`ppid`,`kind`,`stat`,`start`,`scoop`,`command`],kU=[`pid`,`ppid`,`stat`,`start`,`scoop`,`command`],AU={running:`R`,pending:`S`,exited:`Z`,killed:`K`};function jU(e={}){return G(`ps`,async t=>{if(t.includes(`--help`)||t.includes(`-h`))return UU();let n=e.processManager??MU();if(!n)return{stdout:``,stderr:`ps: no process manager available in this runtime
|
|
7193
|
+
`,exitCode:1};let r=kU,i=!1,a=!1;for(let e=0;e<t.length;e++){let n=t[e];if(n===`-a`||n===`-A`||n===`-e`||n===`--all`){a=!0;continue}if(n===`-T`||n===`--tree`){i=!0;continue}if(n===`-o`||n.startsWith(`--columns=`)||n.startsWith(`-o=`)){let i=n.startsWith(`-o=`)?n.slice(3):n.startsWith(`--columns=`)?n.slice(10):t[++e];if(typeof i!=`string`)return{stdout:``,stderr:`ps: -o requires an argument
|
|
7194
|
+
`,exitCode:2};let a=NU(i);if(a instanceof Error)return{stdout:``,stderr:`ps: ${a.message}\n`,exitCode:2};r=a;continue}return{stdout:``,stderr:`ps: unrecognized argument '${n}'\n`,exitCode:2}}let o=n.list().sort((e,t)=>e.pid-t.pid),s=a?o:o.filter(e=>e.status===`running`||e.status===`pending`),c=(i?HU(s):s.map(e=>({proc:e,depth:0}))).map(({proc:e,depth:t})=>IU(e,r,t,i));return{stdout:[PU(r),...c].join(`
|
|
7195
7195
|
`)+`
|
|
7196
|
-
`,stderr:``,exitCode:0}})}function
|
|
7196
|
+
`,stderr:``,exitCode:0}})}function MU(){let e=globalThis.__slicc_pm;return e instanceof Object&&typeof e.list==`function`?e:null}function NU(e){let t=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(Boolean);if(t.length===0)return Error(`-o requires at least one column`);let n=[];for(let e of t){if(!OU.includes(e))return Error(`unknown column '${e}'; supported: ${OU.join(`, `)}`);n.push(e)}return n}function PU(e){return e.map(e=>FU(e)).join(` `)}function FU(e){switch(e){case`pid`:return`PID`.padStart(5);case`ppid`:return`PPID`.padStart(5);case`kind`:return`KIND`.padEnd(10);case`stat`:return`STAT`;case`start`:return`START`;case`scoop`:return`SCOOP`.padEnd(10);case`command`:return`COMMAND`}}function IU(e,t,n,r){return t.map(t=>LU(e,t,n,r)).join(` `)}function LU(e,t,n,r){switch(t){case`pid`:return String(e.pid).padStart(5);case`ppid`:return String(e.ppid).padStart(5);case`kind`:return e.kind.padEnd(10);case`stat`:return AU[e.status];case`start`:return RU(e.startedAt);case`scoop`:return zU(e).padEnd(10);case`command`:return BU(e,n,r)}}function RU(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}`}function zU(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?.slice(0,10)??`scoop`}function BU(e,t,n){let r=n&&t>0?` `.repeat(t-1)+`└─ `:``,i=e.argv.length===0?`[${e.kind}]`:e.argv.map(VU).join(` `);return r+(i.length>80?i.slice(0,79)+`…`:i)}function VU(e){return e===``?`''`:/^[A-Za-z0-9_./:=@%+-]+$/.test(e)?e:e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function HU(e){let t=new Map;for(let n of e)t.set(n.pid,n);let n=new Map,r=[];for(let i of e)if(t.has(i.ppid)){let e=n.get(i.ppid)??[];e.push(i),n.set(i.ppid,e)}else r.push(i);let i=[],a=new Set,o=(e,t)=>{if(a.has(e.pid))return;a.add(e.pid),i.push({proc:e,depth:t});let r=n.get(e.pid)??[];for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,t+1)};for(let e of r.sort((e,t)=>e.pid-t.pid))o(e,0);return i}function UU(){return{stdout:`Usage: ps [-a] [-T] [-o col[,col…]]
|
|
7197
7197
|
|
|
7198
7198
|
List processes tracked by the kernel.
|
|
7199
7199
|
|
|
@@ -7223,9 +7223,9 @@ Examples:
|
|
|
7223
7223
|
ps -T live tree
|
|
7224
7224
|
ps -a -T full tree
|
|
7225
7225
|
ps -o pid,kind,stat just three columns
|
|
7226
|
-
`,stderr:``,exitCode:0}}const
|
|
7227
|
-
`,stderr:``,exitCode:0}}function
|
|
7228
|
-
`,stderr:``,exitCode:0}}async function
|
|
7226
|
+
`,stderr:``,exitCode:0}}const WU=new Set([`dev`,`proc`,`lib`,`bin`,`usr`,`etc`,`home`,`tmp`]);async function GU(e,t=WU){let n=[],r=new Set;try{let i=await e.readdir(`/`);for(let a of i){if(!a||a.includes(`/`)||t.has(a))continue;let i=`/${a}`,o=!1;try{o=!!(await e.stat(i)).isDirectory}catch{continue}o&&(r.has(i)||(r.add(i),n.push(i)))}}catch{}return r.has(`/tmp`)||(r.add(`/tmp`),n.push(`/tmp`)),n}function KU(e,t){let n=e;if(typeof n.listMountPoints!=`function`)return[];let r=e=>{for(let n of t)if(e===n||e.startsWith(n===`/`?`/`:n+`/`)||n.startsWith(e+`/`))return!0;return!1},i=[];for(let e of n.listMountPoints())e.kind!==`proc`&&r(e.path)&&i.push({path:e.path,kind:e.kind});return i}function qU(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`slicc-fs`}catch{}}function JU(e){return{reader:{exists:t=>e.fs.exists(t),isDirectory:async t=>{try{return(await e.fs.stat(t)).isDirectory}catch{return!1}},readFile:t=>e.fs.readFile(t)},fromDir:e.cwd}}async function YU(e,t){try{let n=await e.readFile(`${t}/package.json`),r=JSON.parse(n);return typeof r.version==`string`?r.version:null}catch{return null}}function XU(e,t){return`installed pyodide ${e} is not the supported version ${t}: run \`ipk uninstall pyodide\` then \`ipk add pyodide@${t}\``}function ZU(){return{stdout:`usage: python3 [-c code | script.py] [args...]
|
|
7227
|
+
`,stderr:``,exitCode:0}}function QU(){return{stdout:`Python 3.14 (Pyodide)
|
|
7228
|
+
`,stderr:``,exitCode:0}}async function $U(e,t,n){if(t[0]===`-c`){if(!t[1])return{kind:`result`,result:{stdout:``,stderr:`${e}: option requires an argument -- 'c'\n`,exitCode:2}};let n=t[1];return{kind:`ok`,code:n,filename:`-c`,sysArgv:[`-c`,...t.slice(2)],procArgv:[e,`-c`,n,...t.slice(2)]}}if(t.length>0&&!t[0].startsWith(`-`)){let r=t[0],i=n.fs.resolvePath(n.cwd,r);return await n.fs.exists(i)?{kind:`ok`,code:await n.fs.readFile(i),filename:r,sysArgv:[r,...t.slice(1)],procArgv:[e,r,...t.slice(1)]}:{kind:`result`,result:{stdout:``,stderr:`${e}: can't open file '${r}': [Errno 2] No such file or directory\n`,exitCode:2}}}return Pk(n.stdin).trim().length>0?{kind:`ok`,code:Pk(n.stdin),filename:`<stdin>`,sysArgv:[`<stdin>`],procArgv:[e]}:t.length>0?{kind:`result`,result:{stdout:``,stderr:`${e}: unsupported option '${t[0]}'\n`,exitCode:2}}:{kind:`result`,result:{stdout:``,stderr:`${e}: no input provided (use -c CODE, script path, or stdin)\n`,exitCode:2}}}async function eW(e){let t=JU(e),n=await wv(t);if(!n)return{kind:`result`,result:{stdout:``,stderr:`${Sv}\n`,exitCode:1}};let r=await YU(t.reader,n);return r?r===bv?{kind:`ok`,assetRoot:n}:{kind:`result`,result:{stdout:``,stderr:`${XU(r,bv)}\n`,exitCode:1}}:{kind:`result`,result:{stdout:``,stderr:`${Sv}\n`,exitCode:1}}}function tW(e,t={}){return G(e,async(n,r)=>{if(n.includes(`--help`)||n.includes(`-h`))return ZU();if(n.includes(`--version`)||n.includes(`-V`))return QU();let i=await $U(e,n,r);if(i.kind===`result`)return i.result;let{code:a,filename:o,sysArgv:s,procArgv:c}=i,l=await GU(r.fs),u=KU(r.fs,l),d=t.buildProcessConfig?.(),f=d?.processManager??nW(),p=d?.owner??{kind:`system`},m=d?.getParentPid?.(),h=t.realmFactory??mE(),g=t.pyodideIndexURL??vE(),_=t.pyodideAssetRoot;if(!_&&g===void 0){let e=await eW(r);if(e.kind===`result`)return e.result;_=e.assetRoot}let v=o===`<stdin>`?``:Pk(r.stdin),y=qU();return f?kk({pm:f,realmFactory:h,owner:p,kind:`py`,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u,procKind:`py`,ppid:m}):iW({realmFactory:h,owner:p,code:a,argv:c,realmArgv:s,env:Object.fromEntries(r.env.entries()),cwd:r.cwd,filename:o,ctx:r,stdin:v,pyodideIndexURL:g,pyodideAssetRoot:_,pyodideMountDirs:l,opfsMountDbName:y,mountPoints:u})})}function nW(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}let rW=null;async function iW(e){if(!rW){let{ProcessManager:e}=await import(`./process-manager-B5dz0PkO.js`).then(e=>e.n);rW=new e}return kk({pm:rW,realmFactory:e.realmFactory,owner:e.owner,kind:`py`,code:e.code,argv:e.argv,realmArgv:e.realmArgv,env:e.env,cwd:e.cwd,filename:e.filename,ctx:e.ctx,stdin:e.stdin,pyodideIndexURL:e.pyodideIndexURL,pyodideAssetRoot:e.pyodideAssetRoot,pyodideMountDirs:e.pyodideMountDirs,mountPoints:e.mountPoints,opfsMountDbName:e.opfsMountDbName,procKind:`py`})}function aW(e,t,n={}){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Set,a=[],o=[],s=[];for(let t of e){i.add(t.path);let e=r.get(t.path);e?e.size===t.size&&e.mtimeMs===t.mtimeMs?s.push(t.path):o.push(t.path):a.push(t.path)}let c=[];if(n.delete)for(let e of t)i.has(e.path)||c.push(e.path);return{toAdd:a,toUpdate:o,toDelete:c,toSkip:s}}function oW(){return null}function sW(e){let t={dryRun:!1,delete:!1,verbose:!1},n=[];for(let r of e)if(r===`--dry-run`||r===`-n`)t.dryRun=!0;else if(r===`--delete`)t.delete=!0;else if(r===`--verbose`||r===`-v`)t.verbose=!0;else if(r===`--help`||r===`-h`)return{error:`__help__`};else if(r.startsWith(`-`))return{error:`Unknown flag: ${r}`};else n.push(r);if(n.length!==2)return{error:`Expected exactly 2 arguments: <source> <dest>`};let[r,i]=n,a=cW(r),o=cW(i);return a&&o?{error:`Cannot sync between two remote paths — one side must be local`}:!a&&!o?{error:`One argument must be a remote path (runtime-id:/path)`}:o?{direction:`push`,localPath:r,remotePath:o.path,runtimeId:o.runtimeId,...t}:{direction:`pull`,localPath:i,remotePath:a.path,runtimeId:a.runtimeId,...t}}function cW(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1);return r.startsWith(`/`)?{runtimeId:n,path:r}:null}function lW(){return{stdout:`rsync — sync files between local VFS and a remote tray runtime
|
|
7229
7229
|
|
|
7230
7230
|
Usage:
|
|
7231
7231
|
rsync [flags] <local-path> <runtime-id>:<remote-path> # push
|
|
@@ -7241,21 +7241,21 @@ Examples:
|
|
|
7241
7241
|
rsync /workspace follower-abc123:/workspace
|
|
7242
7242
|
rsync --delete /shared leader:/shared
|
|
7243
7243
|
rsync follower-abc123:/workspace/project /workspace/project
|
|
7244
|
-
`,stderr:``,exitCode:0}}async function
|
|
7244
|
+
`,stderr:``,exitCode:0}}async function uW(e,t){if(!await e.exists(t))return[];let n=[];for await(let r of e.walk(t)){let i=r.slice(t.length).replace(/^\//,``);if(!i)continue;let a=await e.stat(r);n.push({path:i,size:a.size,mtimeMs:a.mtime})}return n}async function dW(e,t,n){let r=(await e(t,{op:`walk`,path:n}))[0];if(!r.ok){if(r.code===`ENOENT`)return[];throw Error(`Remote walk failed: ${r.error}`)}if(r.data.type!==`paths`)throw Error(`Unexpected walk response type`);let i=r.data.paths,a=[];for(let r of i){let i=r.slice(n.length).replace(/^\//,``);if(!i)continue;let o=(await e(t,{op:`stat`,path:r}))[0];o.ok&&o.data.type===`stat`&&a.push({path:i,size:o.data.stat.size,mtimeMs:o.data.stat.mtime})}return a}async function fW(e,t,n){let r=await e(t,{op:`readFile`,path:n,encoding:`binary`}),i=``;for(let e of r){if(!e.ok)throw Error(`Remote read failed: ${e.error}`);e.data.type===`file`&&(i+=e.data.content)}return i}async function pW(e,t,n){let r=await e(t,{op:`mkdir`,path:n,recursive:!0});if(!r[0].ok)throw Error(`Remote mkdir failed: ${r[0].error}`)}function mW(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}async function hW(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:l}=n,u=aW(await uW(e,i),await dW(t,o,a),{delete:n.delete});if(s||l){for(let e of u.toAdd)r.push(`+ ${e}`);for(let e of u.toUpdate)r.push(`~ ${e}`);for(let e of u.toDelete)r.push(`- ${e}`);if(s)for(let e of u.toSkip)r.push(` ${e} (up to date)`)}let d=u.toAdd.length+u.toUpdate.length+u.toDelete.length;if(l)return r.push(`\n(dry run) ${d} file(s) would be transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
|
|
7245
7245
|
`)+`
|
|
7246
|
-
`,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let s=i+`/`+n,l=a+`/`+n;await
|
|
7246
|
+
`,stderr:``,exitCode:0};for(let n of[...u.toAdd,...u.toUpdate]){let s=i+`/`+n,l=a+`/`+n;await pW(t,o,mW(l));let u=await t(o,{op:`writeFile`,path:l,content:c(await e.readFile(s,{encoding:`binary`})),encoding:`base64`});if(!u[0].ok)return{stdout:r.join(`
|
|
7247
7247
|
`)+`
|
|
7248
7248
|
`,stderr:`Error writing ${l}: ${u[0].error}\n`,exitCode:1}}for(let e of u.toDelete){let n=a+`/`+e,i=await t(o,{op:`rm`,path:n});if(!i[0].ok)return{stdout:r.join(`
|
|
7249
7249
|
`)+`
|
|
7250
7250
|
`,stderr:`Error deleting ${n}: ${i[0].error}\n`,exitCode:1}}return r.push(`${d} file(s) transferred, ${u.toSkip.length} up to date`),{stdout:r.join(`
|
|
7251
7251
|
`)+`
|
|
7252
|
-
`,stderr:``,exitCode:0}}async function
|
|
7252
|
+
`,stderr:``,exitCode:0}}async function gW(e,t,n){let r=[],{localPath:i,remotePath:a,runtimeId:o,verbose:s,dryRun:c}=n,l=aW(await dW(t,o,a),await uW(e,i),{delete:n.delete});if(s||c){for(let e of l.toAdd)r.push(`+ ${e}`);for(let e of l.toUpdate)r.push(`~ ${e}`);for(let e of l.toDelete)r.push(`- ${e}`);if(s)for(let e of l.toSkip)r.push(` ${e} (up to date)`)}let u=l.toAdd.length+l.toUpdate.length+l.toDelete.length;if(c)return r.push(`\n(dry run) ${u} file(s) would be transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7253
7253
|
`)+`
|
|
7254
|
-
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=
|
|
7254
|
+
`,stderr:``,exitCode:0};for(let n of[...l.toAdd,...l.toUpdate]){let r=a+`/`+n,s=i+`/`+n,c=mW(s);await e.exists(c)||await e.mkdir(c,{recursive:!0});let l=d(await fW(t,o,r));await e.writeFile(s,l)}for(let t of l.toDelete){let n=i+`/`+t;await e.rm(n)}return r.push(`${u} file(s) transferred, ${l.toSkip.length} up to date`),{stdout:r.join(`
|
|
7255
7255
|
`)+`
|
|
7256
|
-
`,stderr:``,exitCode:0}}function
|
|
7256
|
+
`,stderr:``,exitCode:0}}function _W(e={}){let t=e.fs,n=e.getSendFsRequest??oW;return G(`rsync`,async e=>{if(e.includes(`--help`)||e.includes(`-h`)||e.length===0)return lW();if(!t)return{stdout:``,stderr:`rsync: no filesystem available
|
|
7257
7257
|
`,exitCode:1};let r=n();if(!r)return{stdout:``,stderr:`rsync: not connected to a tray — rsync requires a tray connection
|
|
7258
|
-
`,exitCode:1};let i=
|
|
7258
|
+
`,exitCode:1};let i=sW(e);if(`error`in i)return i.error===`__help__`?lW():{stdout:``,stderr:`rsync: ${i.error}\n`,exitCode:1};try{return i.direction===`push`?await hW(t,r,i):await gW(t,r,i)}catch(e){return{stdout:``,stderr:`rsync: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function vW(){return{stdout:`usage: say [-v voice] [-r rate] [-l lang] [-o file] [--list] <text>
|
|
7259
7259
|
say --status | --warmup
|
|
7260
7260
|
|
|
7261
7261
|
Speaks the given text. Uses on-device Kokoro voices when the model
|
|
@@ -7272,14 +7272,14 @@ Examples:
|
|
|
7272
7272
|
[web speech] otherwise); kokoro voices lead when ready
|
|
7273
7273
|
--status Show the on-device voice state (downloading/ready + ETA)
|
|
7274
7274
|
--warmup Stage + start the on-device voice download in the background
|
|
7275
|
-
`,stderr:``,exitCode:0}}function
|
|
7275
|
+
`,stderr:``,exitCode:0}}function yW(e){switch(e.state){case`ready`:return`voice engine: ready
|
|
7276
7276
|
`;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
|
|
7277
7277
|
`;case`idle`:return`voice engine: not downloaded (run say --warmup)
|
|
7278
|
-
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function
|
|
7278
|
+
`;case`loading`:{let t=e=>(e/1024/1024).toFixed(1);return`voice engine: downloading${e.loaded!=null&&e.total?` ${t(e.loaded)}/${t(e.total)} MB`:``}${e.etaSeconds!=null&&Number.isFinite(e.etaSeconds)?` · ready in ~${Math.max(1,Math.round(e.etaSeconds))}s`:``}\n`}}}function bW(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function xW(e){return e instanceof Error?e.message:String(e)}let SW=!1,CW=null;function wW(){return SW?Promise.resolve(speechSynthesis.getVoices()):(CW||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){SW=!0,e(t);return}let n=()=>{SW=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),SW=!0,e(speechSynthesis.getVoices())},1e3)}),CW)}const TW={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function EW(e,t,n){switch(t){case`-v`:return e.voiceName=n,null;case`-l`:return e.lang=n,null;case`-o`:case`--out`:return e.outFile=n,null;case`-r`:{let t=parseFloat(n);return Number.isNaN(t)||t<.1||t>10?`rate must be between 0.1 and 10`:(e.rate=t,null)}default:return`unknown option: ${t}`}}function DW(e){let t={voiceName:null,rate:1,lang:null,outFile:null,text:``},n=[];for(let r=0;r<e.length;r++){let i=e[r];if(i in TW){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return bW(`${i} requires ${TW[i]}`);let a=EW(t,i,n);if(a)return bW(a)}else if(i.startsWith(`-`)&&i!==`--list`)return bW(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function OW(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function kW(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-YEgNUk4w.js`),t=e().map(e=>OW({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await wW()).map(e=>OW({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
|
|
7279
7279
|
`)+`
|
|
7280
|
-
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>
|
|
7280
|
+
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>OW(e)).join(`
|
|
7281
7281
|
`)+`
|
|
7282
|
-
`,stderr:``,exitCode:0}}catch(e){return
|
|
7282
|
+
`,stderr:``,exitCode:0}}catch(e){return bW(xW(e))}}async function AW(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-YEgNUk4w.js`),n=t().map(e=>({name:e.id})),r=(await wW()).map(e=>({name:e.name}));return[...n,...r]}async function jW(e,t){let n=(await AW(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:bW(`voice "${t}" not found. Use --list to see available voices.`)}}async function MW(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-YEgNUk4w.js`);return{stdout:yW(t?n():e()),stderr:``,exitCode:0}}return{stdout:yW(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return bW(xW(e))}}async function NW(e,t){return t.includes(`--list`)?kW(e):t.includes(`--status`)?MW(e,!1):t.includes(`--warmup`)?MW(e,!0):null}async function PW(e){try{let{speak:t}=await import(`./speak-YEgNUk4w.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return bW(`speech synthesis error: ${xW(e)}`)}}async function FW(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return bW(xW(e))}}async function IW(e){let{synthesizeToWav:t}=await import(`./speak-YEgNUk4w.js`);try{return{bytes:await t(e)}}catch(e){return bW(xW(e))}}async function LW(e,t){try{let n=await e.panelRpc.call(`synthesize-to-wav`,{text:t.text,lang:t.lang,...t.voice?{voice:t.voice}:{},rate:t.rate},{timeoutMs:5*6e4});return{bytes:new Uint8Array(n.bytes)}}catch(e){return bW(xW(e))}}async function RW(e,t,n,r){let i=e.local?await IW(r):await LW(e,r);if(`exitCode`in i)return i;let a=t.fs.resolvePath(t.cwd,n);try{await t.fs.writeFile(a,i.bytes)}catch(e){return bW(`failed to write ${n}: ${xW(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function zW(){return G(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return vW();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:He()};if(!n.local&&!n.panelRpc)return bW(`Web Speech API unavailable in this environment`);let r=await NW(n,e);if(r)return r;let i=DW(e);if(`exitCode`in i)return i;if(!i.text)return vW();if(!i.lang)return bW(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await jW(n,i.voiceName);if(t)return t;a=e}let o={text:i.text,lang:i.lang,voice:a,rate:i.rate};return i.outFile?RW(n,t,i.outFile,o):n.local?PW(o):FW(n,o)})}function BW(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
|
|
7283
7283
|
|
|
7284
7284
|
Usage: screencapture [options] <output-file>
|
|
7285
7285
|
|
|
@@ -7295,12 +7295,12 @@ Examples:
|
|
|
7295
7295
|
screencapture screenshot.png # Capture to file
|
|
7296
7296
|
screencapture -c # Capture to clipboard
|
|
7297
7297
|
screencapture -v capture.png # Capture and return for agent vision
|
|
7298
|
-
`,stderr:``,exitCode:0}}function
|
|
7299
|
-
`,exitCode:1};if(n&&!
|
|
7298
|
+
`,stderr:``,exitCode:0}}function VW(e){let t=``,n=8192;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function HW(e){switch(e.split(`.`).pop()?.toLowerCase()){case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return`image/png`}}async function UW(e,t){let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);s.drawImage(r,0,0,i,a);let c=await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)});return{bytes:new Uint8Array(await c.arrayBuffer()),mimeType:e}}finally{n.getTracks().forEach(e=>{e.stop()})}}function WW(){return G(`screencapture`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return BW();let n=Ue(),r=He();if(!n&&!r)return{stdout:``,stderr:`screencapture: browser APIs are unavailable in this environment
|
|
7299
|
+
`,exitCode:1};if(n&&!NF()&&!navigator.mediaDevices?.getDisplayMedia)return{stdout:``,stderr:`screencapture: screen capture is not supported in this browser
|
|
7300
7300
|
`,exitCode:1};let i=e.includes(`--clipboard`)||e.includes(`-c`),a=e.includes(`--view`)||e.includes(`-v`),o=[`--clipboard`,`-c`,`--view`,`-v`,`--help`,`-h`],s=e.indexOf(`--`),c=(s>=0?e.slice(s+1):e.filter(e=>!o.includes(e)))[0];if(!i&&!c)return{stdout:``,stderr:`screencapture: output file required (or use -c for clipboard)
|
|
7301
|
-
`,exitCode:1};let l=c||`screenshot.png`,u=
|
|
7302
|
-
`,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(i)try{if(
|
|
7303
|
-
`,exitCode:1};if(n){let e=await
|
|
7301
|
+
`,exitCode:1};let l=c||`screenshot.png`,u=HW(l),d=u===`image/png`?1:.92,f;try{if(NF())f=(await FF({kind:`screen`,mimeType:u,quality:d})).bytes;else if(n)f=(await UW(u,d)).bytes;else{let e=await r.call(`screencapture`,{mimeType:u,quality:d},{timeoutMs:5*6e4});f=new Uint8Array(e.bytes)}}catch(e){let t=e instanceof Error?e.message:String(e);return t.includes(`Permission denied`)||t.includes(`NotAllowedError`)?{stdout:``,stderr:`screencapture: user cancelled or permission denied
|
|
7302
|
+
`,exitCode:1}:{stdout:``,stderr:`screencapture: ${t}\n`,exitCode:1}}if(i)try{if(NF()&&typeof document<`u`&&typeof document.hasFocus==`function`&&!document.hasFocus())return{stdout:``,stderr:`screencapture: clipboard capture needs a focused window; save to a file instead
|
|
7303
|
+
`,exitCode:1};if(n){let e=await GW(f,u),t=new ArrayBuffer(e.byteLength);new Uint8Array(t).set(e);let n=new Blob([t],{type:`image/png`});return await KW(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{stdout:`captured ${Math.round(n.size/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}return await r.call(`clipboard-write-image`,{bytes:f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),mimeType:u},{timeoutMs:5*6e4}),{stdout:`captured ${Math.round(f.byteLength/1024)} KB to clipboard\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`screencapture: failed to copy to clipboard: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let p=t.fs.resolvePath(t.cwd,l);try{await t.fs.writeFile(p,f)}catch(e){return{stdout:``,stderr:`screencapture: failed to write file: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let m=Math.round(f.length/1024);return a?{stdout:`${p} (${m} KB)\n<img:data:${u};base64,${VW(f)}>`,stderr:``,exitCode:0}:{stdout:`captured ${m} KB to ${mn(p)}\n`,stderr:``,exitCode:0}})}async function GW(e,t){if(t===`image/png`)return e;let n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let r=new Blob([n],{type:t}),i=URL.createObjectURL(r);try{let e=new Image;await new Promise((t,n)=>{e.onload=()=>t(),e.onerror=()=>n(Error(`Failed to load image for conversion`)),e.src=i});let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);if(!n)throw Error(`Failed to get canvas context`);n.drawImage(e,0,0);let r=await new Promise((e,n)=>{t.toBlob(t=>t?e(t):n(Error(`Failed to create PNG blob`)),`image/png`)});return new Uint8Array(await r.arrayBuffer())}finally{URL.revokeObjectURL(i)}}async function KW(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}function qW(e){return new Promise((t,n)=>{chrome.runtime.sendMessage(e,e=>{let r=chrome.runtime.lastError;if(r){n(Error(r.message??`chrome.runtime.lastError`));return}t(e)})})}async function JW(e,t,n){let r={method:e,headers:m({"Content-Type":`application/json`})};n&&(r.body=JSON.stringify(n));let i=await fetch(u(`/api/secrets${t}`),r),a=await i.json().catch(()=>({}));return{ok:i.ok,status:i.status,data:a}}function YW(){return{async list(){let[e,t]=await Promise.all([JW(`GET`,``),JW(`GET`,`/session`)]),n=[];if(e.ok)for(let t of e.data)n.push({name:t.name,domains:t.domains,persisted:!0});if(t.ok)for(let e of t.data)n.push({name:e.name,domains:e.domains,persisted:!1});return n},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){let{ok:t,data:n}=await JW(`GET`,`/masked`);return t?n.find(t=>t.name===e)??null:null},async peek(e){let{ok:t,data:n}=await JW(`GET`,`/peek?name=${encodeURIComponent(e)}`);return t?n:null},async setSession(e,t,n){let{ok:r,data:i}=await JW(`POST`,`/session`,{name:e,value:t,domains:n});if(!r)throw Error($W(i)??`failed to set session secret`)},async setPersisted(e,t,n){let{ok:r,data:i}=await JW(`POST`,``,{name:e,value:t,domains:n});if(!r)throw Error($W(i)??`failed to persist secret`)},async setScope(e,t){let{ok:n,data:r}=await JW(`POST`,`/scope`,{name:e,domains:t});if(!n)throw Error($W(r)??`failed to update scope`)},async delete(e){let{ok:t,status:n,data:r}=await JW(`DELETE`,`/${encodeURIComponent(e)}`);if(n===404)return{removed:!1};if(!t)throw Error($W(r)??`failed to delete secret`);return{removed:!0,fromSession:r&&typeof r==`object`&&`fromSession`in r?!!r.fromSession:void 0}}}}function XW(e){let t=t=>e(t);return{async list(){let[e,n]=await Promise.all([t({type:`secrets.list`}),t({type:`secrets.session.list`})]),r=[];for(let t of e?.entries??[])r.push({name:t.name,domains:t.domains,persisted:!0});for(let e of n?.entries??[])r.push({name:e.name,domains:e.domains,persisted:!1});return r},async getInfo(e){return(await this.list()).find(t=>t.name===e)??null},async getMasked(e){return((await t({type:`secrets.list-masked-entries`}))?.entries??[]).find(t=>t.name===e)??null},async peek(e){let n=await t({type:`secrets.peek`,name:e});if(n?.error)throw Error(n.error);return n?.record??null},async setSession(e,n,r){let i=await t({type:`secrets.session.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.session.set failed`)},async setPersisted(e,n,r){let i=await t({type:`secrets.set`,name:e,value:n,domains:r});if(!i?.ok)throw Error(i?.error??`secrets.set failed`)},async setScope(e,n){let r=await t({type:`secrets.set-domains`,name:e,domains:n});if(!r?.ok)throw Error(r?.error??`secrets.set-domains failed`)},async delete(e){let n=await t({type:`secrets.delete`,name:e});if(!n?.ok)throw Error(n?.error??`secrets.delete failed`);return{removed:n.removed??!0,fromSession:n.fromSession}}}}function ZW(){return XW(e=>qW(e))}function QW(){return XW(e=>{let{type:t,...n}=e;return w(t,n)})}function $W(e){if(e&&typeof e==`object`&&`error`in e){let t=e.error;if(typeof t==`string`)return t}}function eG(e){switch(e){case`extension-direct`:return ZW();case`extension-delegate`:return QW();default:return YW()}}function tG(){return`secret — manage secrets for the fetch proxy and mount backends
|
|
7304
7304
|
|
|
7305
7305
|
No approval (session-only, in-memory, never persisted):
|
|
7306
7306
|
secret set <name> <value> [--domain <pat>] Set a session secret. Free for a
|
|
@@ -7337,24 +7337,24 @@ Examples:
|
|
|
7337
7337
|
secret peek OPENAI_KEY
|
|
7338
7338
|
secret set GITHUB_TOKEN ghp_… --domain "api.github.com" --persist # prompts
|
|
7339
7339
|
secret scope GITHUB_TOKEN --domain "api.github.com,*.github.com" # prompts
|
|
7340
|
-
`}function
|
|
7341
|
-
`,exitCode:1}}function
|
|
7340
|
+
`}function nG(e){let t=e.indexOf(`--domain`);return t===-1||!e[t+1]?null:e[t+1].split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}const rG={persist:`persist secret`,scope:`edit secret scope`,value:`change secret value`},iG=new Set;function aG(e,t){if(e===t)return!0;try{return yt(e).test(t)}catch{return!1}}function oG(e,t){for(let n of e)if(aG(n,t))return!0;return!1}function sG(){return{stdout:``,stderr:`secret: approval denied
|
|
7341
|
+
`,exitCode:1}}function cG(e){let t=E(),n=e.isExtension??(t===`extension-direct`||t===`extension-delegate`),r=e.backend??eG(t),i=e.grants??iG,a=e.broker,o=()=>(a??=Da(),a);return{backend:r,inExtension:n,gate:async(e,t)=>{let n=`secret:${e}:${t}`;if(oG(i,n))return!0;let r=await o().requestApproval({kind:`secret`,detail:`${rG[e]}: ${t}`,suggestedPattern:n});if(r.decision===`deny`)return!1;if(r.decision===`always`){let e=r.pattern?.trim();i.add(e&&aG(e,n)?e:n)}return!0},injectMaskedEnv:async t=>{if(e.setEnv&&es(t))try{let n=await r.getMasked(t);n&&e.setEnv(t,n.maskedValue)}catch{}}}}function lG(e){let t=Pk(e);if(t.length!==0)return t.endsWith(`\r
|
|
7342
7342
|
`)?t.slice(0,-2):t.endsWith(`
|
|
7343
|
-
`)?t.slice(0,-1):t}async function
|
|
7344
|
-
`,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):
|
|
7345
|
-
`,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=
|
|
7343
|
+
`)?t.slice(0,-1):t}async function uG(e,t,n,r){return n.length===0?{stdout:``,stderr:`secret: --domain is required to persist a secret
|
|
7344
|
+
`,exitCode:1}:await r.gate(`persist`,e)?(await r.backend.setPersisted(e,t,n),await r.injectMaskedEnv(e),{stdout:`Persisted "${e}" (domains: ${n.join(`, `)})\n`,stderr:``,exitCode:0}):sG()}async function dG(e,t,n,r){return await r.backend.getInfo(e)&&!await r.gate(`value`,e)?sG():(await r.backend.setSession(e,t,n),await r.injectMaskedEnv(e),{stdout:`Set session secret "${e}"${n.length>0?` (domains: ${n.join(`, `)})`:``} — in-memory only, not persisted.\n`,stderr:``,exitCode:0})}async function fG(e,t,n){let r=e[1];if(!r||r.startsWith(`-`))return{stdout:``,stderr:`secret: set requires a <name>
|
|
7345
|
+
`,exitCode:1};let i=e[2]&&!e[2].startsWith(`-`)?e[2]:void 0,a=lG(t.stdin);if(i!==void 0&&a!==void 0)return{stdout:``,stderr:`secret: provide <value> as an argument OR via stdin, not both
|
|
7346
7346
|
`,exitCode:1};let o=i??a;if(o===void 0)return{stdout:``,stderr:`secret: set requires a <value>: secret set <name> <value> [--domain <patterns>] [--persist]
|
|
7347
7347
|
or pipe the value on stdin: echo "$TOKEN" | secret set <name> [--domain ...]
|
|
7348
|
-
`,exitCode:1};let s=
|
|
7349
|
-
`,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7350
|
-
`,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7351
|
-
`,exitCode:1};let r=
|
|
7352
|
-
`,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):
|
|
7353
|
-
`,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function
|
|
7354
|
-
`,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?_(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function
|
|
7348
|
+
`,exitCode:1};let s=nG(e)??[];return e.includes(`--persist`)?uG(r,o,s,n):dG(r,o,s,n)}async function pG(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: get requires a <name>
|
|
7349
|
+
`,exitCode:1};let r=await t.backend.getMasked(n);return r?{stdout:`${r.name}=${r.maskedValue}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function mG(e,t){let n=e[1];if(!n)return{stdout:``,stderr:`secret: peek requires a <name>
|
|
7350
|
+
`,exitCode:1};let r=await t.backend.peek(n);return r?{stdout:`${r.name}: ${r.preview}\n domains: ${r.domains.join(`, `)||`(none)`}\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function hG(e,t){let n=e[1];if(!n||n.startsWith(`-`))return{stdout:``,stderr:`secret: scope requires a <name>
|
|
7351
|
+
`,exitCode:1};let r=nG(e)??[];return r.length===0?{stdout:``,stderr:`secret: scope requires --domain <patterns>
|
|
7352
|
+
`,exitCode:1}:await t.gate(`scope`,n)?(await t.backend.setScope(n,r),{stdout:`Updated scope for "${n}" (domains: ${r.join(`, `)})\n`,stderr:``,exitCode:0}):sG()}async function gG(e){let t=await e.backend.list();if(t.length===0)return{stdout:`No secrets stored
|
|
7353
|
+
`,stderr:``,exitCode:0};let n=Math.max(4,...t.map(e=>e.name.length)),r=`${`NAME`.padEnd(n)} TYPE DOMAINS\n`;for(let e of t){let t=e.persisted?`SAVED`:`SESSION`;r+=`${e.name.padEnd(n)} ${t.padEnd(7)} ${e.domains.join(`, `)}\n`}return{stdout:r,stderr:``,exitCode:0}}async function _G(e,t,n){let r=e[1];if(!r)return{stdout:``,stderr:`secret: ${t} requires a <name>\n`,exitCode:1};let i=await n.backend.delete(r);return i.removed?{stdout:`Removed ${i.fromSession===!0?`session`:`persisted`} secret "${r}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`secret: no secret named "${r}"\n`,exitCode:1}}async function vG(e,t){let n=e[1],r=e[2];if(!n||!r)return{stdout:``,stderr:`secret: test requires <name> <url>
|
|
7354
|
+
`,exitCode:1};let i;try{i=new URL(r).hostname}catch{return{stdout:``,stderr:`secret: invalid URL "${r}"\n`,exitCode:1}}let a=(await t.backend.list()).find(e=>e.name===n);return a?_(a.domains,i)?{stdout:`✓ ${n} is allowed for ${i}\n`,stderr:``,exitCode:0}:{stdout:`✗ ${n} is NOT allowed for ${i}\n Allowed domains: ${a.domains.join(`, `)}\n`,stderr:``,exitCode:1}:{stdout:``,stderr:`secret: no secret named "${n}"\n`,exitCode:1}}async function yG(e){if(!e.inExtension)return{stdout:`secret: in CLI mode, edit ~/.slicc/secrets.env directly with your text editor.
|
|
7355
7355
|
(changes are picked up on the next request — no restart needed)
|
|
7356
7356
|
`,stderr:``,exitCode:0};try{return await chrome.runtime.openOptionsPage(),{stdout:`Opened Mount Secrets options page in a new tab.
|
|
7357
|
-
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function
|
|
7357
|
+
`,stderr:``,exitCode:0}}catch{let e=chrome.runtime.getURL(`secrets.html`);return window.open(e,`_blank`),{stdout:`Opened ${e}\n`,stderr:``,exitCode:0}}}async function bG(e,t,n){let r=e[0];switch(r){case`set`:return fG(e,t,n);case`get`:case`read`:return pG(e,n);case`peek`:return mG(e,n);case`scope`:return hG(e,n);case`list`:return gG(n);case`delete`:case`rm`:return _G(e,r,n);case`test`:return vG(e,n);case`edit`:return yG(n);default:return{stdout:``,stderr:`secret: unknown command "${r}"\n`,exitCode:1}}}function xG(e={}){let t=cG(e);return G(`secret`,async(e,n)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:tG(),stderr:``,exitCode:0};try{return await bG(e,n,t)}catch(e){return{stdout:``,stderr:`secret: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}})}function SG(){return null}function CG(){return null}function wG(){return globalThis.__slicc_lickManager??null}let TG=null;async function EG(){if(TG)return TG;let{createLickManagerProxy:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return TG=e(),TG}async function DG(){let e=wG();if(e)return{createWebhook:(t,n,r)=>e.createWebhook(t,n,r),deleteWebhook:t=>e.deleteWebhook(t),listWebhooks:async()=>e.listWebhooks()};if(S())return null;let t=await EG(),{listWebhooksAsync:n}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return{createWebhook:(e,n,r)=>t.createWebhook(e,n,r),deleteWebhook:e=>t.deleteWebhook(e),listWebhooks:()=>n()}}function OG(){return{stdout:`usage: serve [--entry <relative-path>] [--bridge | --no-bridge] [--max-tabs <n>] [--quiet] [--stop <token>] [--list] <directory>
|
|
7358
7358
|
|
|
7359
7359
|
Mint a worker-hosted preview URL for a VFS directory, broadcast it to
|
|
7360
7360
|
all connected followers, and open it in the leader's browser.
|
|
@@ -7370,17 +7370,17 @@ Examples:
|
|
|
7370
7370
|
--list List active previews on this tray.
|
|
7371
7371
|
--project Obsolete; ignored. Root-absolute paths work natively
|
|
7372
7372
|
under unified preview.
|
|
7373
|
-
`,stderr:``,exitCode:0}}function
|
|
7373
|
+
`,stderr:``,exitCode:0}}function kG(e){return`error`in e}function AG(e,t,n){if(e===`--entry`)return t?(n.entry=t,{skip:1}):{error:`serve: missing value for --entry
|
|
7374
7374
|
`};if(e.startsWith(`--entry=`))return n.entry=e.slice(8),{skip:0};if(e===`--bridge`)return n.bridge=!0,{skip:0};if(e===`--no-bridge`)return n.noBridge=!0,{skip:0};if(e===`--project`)return n.project=!0,{skip:0};if(e===`--stop`)return t?(n.stop=t,{skip:1}):{error:`serve: missing value for --stop
|
|
7375
7375
|
`};if(e.startsWith(`--stop=`))return n.stop=e.slice(7),{skip:0};if(e===`--list`)return n.list=!0,{skip:0};if(e===`--max-tabs`){if(!t)return{error:`serve: missing value for --max-tabs
|
|
7376
7376
|
`};let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<=0?{error:`serve: --max-tabs must be a positive integer
|
|
7377
7377
|
`}:(n.maxTabs=e,{skip:1})}if(e.startsWith(`--max-tabs=`)){let t=Number.parseInt(e.slice(11),10);return!Number.isFinite(t)||t<=0?{error:`serve: --max-tabs must be a positive integer
|
|
7378
7378
|
`}:(n.maxTabs=t,{skip:0})}return e===`--quiet`?(n.quiet=!0,{skip:0}):e.startsWith(`-`)?{error:`serve: unknown option: ${e}\n`}:n.directory?{error:`serve: expected a single directory argument
|
|
7379
|
-
`}:(n.directory=e,{skip:0})}function
|
|
7380
|
-
`,exitCode:1};if(t.webhookId){let n=await
|
|
7379
|
+
`}:(n.directory=e,{skip:0})}function jG(e){let t={entry:`index.html`,bridge:!1,noBridge:!1,project:!1,list:!1,quiet:!1};for(let n=0;n<e.length;n+=1){let r=AG(e[n],e[n+1],t);if(kG(r))return{...t,error:r.error};n+=r.skip}return t}async function MG(e,t,n,r){if(!gn(t))return{stdout:``,stderr:`serve: invalid entry file: ${t}\n`,exitCode:1};let i=n.resolvePath(r,e),a;try{a=await n.stat(i)}catch{return{stdout:``,stderr:`serve: no such directory: ${e}\n`,exitCode:1}}if(!a.isDirectory)return{stdout:``,stderr:`serve: not a directory: ${e}\n`,exitCode:1};let o=nn(i,t),s;try{s=await n.stat(o)}catch{return{stdout:``,stderr:`serve: entry file not found: ${o}\n`,exitCode:1}}return s.isFile?{fullDirectory:i,entryPath:o}:{stdout:``,stderr:`serve: entry is not a file: ${o}\n`,exitCode:1}}function NG(e){return`exitCode`in e}async function PG(e){let t,n=CG();if(n)t=await n({type:`stop`,previewToken:e});else{let n=He();if(!n)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};t=await n.call(`tray-revoke-preview`,{previewToken:e})}if(!t.revoked)return{stdout:``,stderr:`serve: preview token not found or already revoked
|
|
7380
|
+
`,exitCode:1};if(t.webhookId){let n=await DG();if(!n)return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but the preview-bridge webhook could not be cleaned up (lick manager unavailable). It is a live endpoint — delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0};try{await n.deleteWebhook(t.webhookId)}catch(n){return{stdout:`Preview revoked: ${e}\n`,stderr:`serve: preview revoked, but webhook cleanup failed: ${n instanceof Error?n.message:String(n)}. Delete it with \`webhook delete ${t.webhookId}\`.\n`,exitCode:0}}}return{stdout:`Preview revoked: ${e}\n`,stderr:``,exitCode:0}}async function FG(){let e=CG();if(e){let t=(await e({type:`list`})).previews??[];return t.length===0?{stdout:`No active previews
|
|
7381
7381
|
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${t.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}let t=He();if(!t)return{stdout:``,stderr:"serve: no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.\n",exitCode:1};let n=(await t.call(`tray-list-previews`,void 0)).previews??[];return n.length===0?{stdout:`No active previews
|
|
7382
|
-
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function
|
|
7383
|
-
`:``,c=await
|
|
7382
|
+
`,stderr:``,exitCode:0}:{stdout:`Active previews:\n${n.map(e=>` ${e.previewToken} ${e.url} ${e.servedRoot} ${e.createdAt}\n`).join(``)}`,stderr:``,exitCode:0}}function IG(e){return e().catch(e=>({stdout:``,stderr:`serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}))}async function LG(e){let t=SG();if(t)return t(e);let n=He();if(!n)throw Error("no leader tray available. Enable multi-browser sync via `host enable` or the avatar popover.");return n.call(`tray-open-preview`,e)}async function RG(e,t){if(t)return t.createPage(e);typeof window<`u`&&typeof window.open==`function`&&window.open(e,`_blank`,`noopener,noreferrer`)}async function zG(e,t){if(!e)return{ok:!0};let n=await DG();if(!n)return{ok:!1,result:{stdout:``,stderr:`${t}serve: --bridge requires an active lick manager\n`,exitCode:1}};try{return{ok:!0,webhookId:(await n.createWebhook(`preview-bridge`)).id}}catch(e){return{ok:!1,result:{stdout:``,stderr:`${t}serve: webhook creation failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}}async function BG(e,t,n,r,i,a){let o;try{o=await LG({entryPath:n,servedRoot:t,bridge:e.bridge,noBridge:e.noBridge,maxTabs:e.maxTabs,quiet:e.quiet,webhookId:r})}catch(e){if(r){let e=await DG();e&&await e.deleteWebhook(r).catch(()=>{})}return{stdout:``,stderr:`${i}serve: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}let s=await RG(o.url,a),c=`${o.pushed} follower${o.pushed===1?``:`s`}`,l=s?` (targetId: ${s})`:``;return{stdout:`Preview URL: ${o.url}${l}\nPushed to ${c}\n`,stderr:i,exitCode:0}}async function VG(e,t,n){if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return OG();let r=jG(e);if(r.error)return{stdout:``,stderr:r.error,exitCode:1};if(r.stop){let e=r.stop;return await IG(()=>PG(e))}if(r.list)return await IG(()=>FG());if(!r.directory)return OG();let i=await MG(r.directory,r.entry,t.fs,t.cwd);if(NG(i))return i;let{fullDirectory:a,entryPath:o}=i,s=r.project?`serve: --project is obsolete; ignored (root-absolute paths work natively under unified preview)
|
|
7383
|
+
`:``,c=await zG(!r.noBridge&&r.bridge,s);return c.ok?BG(r,a,o,c.webhookId,s,n):c.result}function HG(e,t){return G(`serve`,(t,n)=>VG(t,n,e))}const UG=`slicc-sprinkle-routes`;function WG(){try{let e=localStorage.getItem(UG);return e?JSON.parse(e):{}}catch{return{}}}function GG(e){try{localStorage.setItem(UG,JSON.stringify(e))}catch{}}function KG(e){return WG()[e]}function qG(e,t){let n=WG();n[e]=t,GG(n)}function JG(e){let t=WG();delete t[e],GG(t)}function YG(){return WG()}function XG(){return{stdout:`usage: sprinkle <subcommand> [args]
|
|
7384
7384
|
|
|
7385
7385
|
list List available .shtml sprinkles
|
|
7386
7386
|
open <name> Open a sprinkle by name
|
|
@@ -7394,26 +7394,26 @@ Examples:
|
|
|
7394
7394
|
chat <html> Show inline HTML in chat (Tool UI)
|
|
7395
7395
|
Use data-action="name" on buttons for callbacks
|
|
7396
7396
|
Pipe HTML: echo "<div>...</div>" | sprinkle chat
|
|
7397
|
-
`,stderr:``,exitCode:0}}function
|
|
7397
|
+
`,stderr:``,exitCode:0}}function ZG(){return globalThis.__slicc_sprinkleManager??null}async function QG(e,t){let n=e.slice(1).join(` `);if(!n){let e=Pk(t.stdin);e&&(n=e)}if(!n)return{stdout:``,stderr:`sprinkle chat: HTML content required
|
|
7398
7398
|
`,exitCode:1};let r=await ie({html:n,onAction:async(e,t)=>({action:e,data:t})});return r===null?{stdout:``,stderr:`sprinkle chat: not in tool execution context
|
|
7399
7399
|
`,exitCode:1}:{stdout:JSON.stringify(r)+`
|
|
7400
|
-
`,stderr:``,exitCode:0}}async function
|
|
7400
|
+
`,stderr:``,exitCode:0}}async function $G(e){await e.refresh();let t=e.available();if(t.length===0)return{stdout:`No .shtml sprinkles found.
|
|
7401
7401
|
`,stderr:``,exitCode:0};let n=new Set(e.opened());return{stdout:t.map(e=>{let t=n.has(e.name)?` [open]`:``;return` ${e.name}${t} ${e.title} (${e.path})`}).join(`
|
|
7402
7402
|
`)+`
|
|
7403
|
-
`,stderr:``,exitCode:0}}async function
|
|
7404
|
-
`,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function
|
|
7405
|
-
`,exitCode:1}}async function
|
|
7406
|
-
`,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function
|
|
7403
|
+
`,stderr:``,exitCode:0}}async function eK(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle open: name required
|
|
7404
|
+
`,exitCode:1};try{return await e.open(n),{stdout:`Sprinkle "${n}" opened.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle open: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}function tK(e,t){let n=t[1];return n?(e.close(n),{stdout:`Sprinkle "${n}" closed.\n`,stderr:``,exitCode:0}):{stdout:``,stderr:`sprinkle close: name required
|
|
7405
|
+
`,exitCode:1}}async function nK(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle reload: name required
|
|
7406
|
+
`,exitCode:1};try{return await e.reload(n),{stdout:`Sprinkle "${n}" reloaded.\n`,stderr:``,exitCode:0}}catch(e){return{stdout:``,stderr:`sprinkle reload: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}async function rK(e){await e.refresh();let t=e.available().length;return{stdout:`Found ${t} sprinkle${t===1?``:`s`}.\n`,stderr:``,exitCode:0}}function iK(e){let t=e[1];if(!t){let e=YG(),t=Object.entries(e);return t.length===0?{stdout:`No sprinkle routes configured (all licks go to cone).
|
|
7407
7407
|
`,stderr:``,exitCode:0}:{stdout:`Sprinkle routes:
|
|
7408
7408
|
`+t.map(([e,t])=>` ${e} -> ${t}`).join(`
|
|
7409
7409
|
`)+`
|
|
7410
|
-
`,stderr:``,exitCode:0}}if(e.includes(`--clear`))return
|
|
7410
|
+
`,stderr:``,exitCode:0}}if(e.includes(`--clear`))return JG(t),{stdout:`Route cleared for sprinkle "${t}" (licks will go to cone).\n`,stderr:``,exitCode:0};let n=e.indexOf(`--scoop`),r=n===-1?void 0:e[n+1];if(!r){let e=KG(t);return e?{stdout:`${t} -> ${e}\n`,stderr:``,exitCode:0}:{stdout:`${t} -> cone (default)\n`,stderr:``,exitCode:0}}return qG(t,r),{stdout:`Sprinkle "${t}" lick events will route to scoop "${r}".\n`,stderr:``,exitCode:0}}function aK(e,t){let n=t[1];if(!n)return{stdout:``,stderr:`sprinkle send: name required
|
|
7411
7411
|
`,exitCode:1};let r=t.slice(2).join(` `);if(!r)return{stdout:``,stderr:`sprinkle send: JSON data required
|
|
7412
7412
|
`,exitCode:1};let i;try{i=JSON.parse(r)}catch{return{stdout:``,stderr:`sprinkle send: invalid JSON
|
|
7413
|
-
`,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function
|
|
7414
|
-
`,exitCode:1};switch(n){case`list`:return
|
|
7415
|
-
`,stderr:``,exitCode:0}}function
|
|
7416
|
-
`)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function
|
|
7413
|
+
`,exitCode:1}}return e.sendToSprinkle(n,i),{stdout:`Data sent to sprinkle "${n}".\n`,stderr:``,exitCode:0}}function oK(){return G(`sprinkle`,async(e,t)=>{if(e.length===0||e[0]===`--help`||e[0]===`-h`)return XG();let n=e[0];if(n===`chat`)return QG(e,t);let r=ZG();if(!r)return{stdout:``,stderr:`sprinkle: sprinkle manager not initialized
|
|
7414
|
+
`,exitCode:1};switch(n){case`list`:return $G(r);case`open`:return eK(r,e);case`close`:return tK(r,e);case`reload`:return nK(r,e);case`refresh`:return rK(r);case`route`:return iK(e);case`send`:return aK(r,e);default:return{stdout:``,stderr:`sprinkle: unknown subcommand "${n}"\n`,exitCode:1}}})}function sK(){return{stdout:`usage: sqlite3 [database] [sql]
|
|
7415
|
+
`,stderr:``,exitCode:0}}function cK(e=`sqlite3`){return G(e,async(t,n)=>{if(t.includes(`--help`)||t.includes(`-h`))return sK();let r=`:memory:`,i=t;t.length>0&&!t[0].startsWith(`-`)&&(r=t[0],i=t.slice(1));let a=i.join(` `).trim()||Pk(n.stdin).trim();if(!a)return{stdout:``,stderr:`${e}: interactive mode is not supported; provide SQL as argument or stdin\n`,exitCode:1};try{let e=await on(),t=r===`:memory:`,i=t?`:memory:`:n.fs.resolvePath(n.cwd,r),o;!t&&await n.fs.exists(i)&&(o=await n.fs.readFileBuffer(i));let s=o?new e.Database(o):new e.Database,c=s.exec(a);t||await n.fs.writeFile(i,s.export()),s.close();let l=[];for(let e of c)for(let t of e.values)l.push(t.map(vn).join(`|`));return{stdout:l.length>0?`${l.join(`
|
|
7416
|
+
`)}\n`:``,stderr:``,exitCode:0}}catch(t){return{stdout:``,stderr:`${e}: ${t instanceof Error?t.message:String(t)}\n`,exitCode:1}}})}function lK(e={}){let{broker:t,persistGrant:n,suppressNextGate:r}=e;return G(`sudo`,async(e,i)=>{if(e.length===0)return{stdout:``,stderr:`sudo: usage: sudo <command> [args...]
|
|
7417
7417
|
`,exitCode:1};if(e[0]===`--help`||e[0]===`-h`)return{stdout:`usage: sudo <command> [args...]
|
|
7418
7418
|
|
|
7419
7419
|
Request human approval to run <command> with elevation. If approved, the
|
|
@@ -7428,11 +7428,11 @@ Options:
|
|
|
7428
7428
|
`,stderr:``,exitCode:0};if(!t)return{stdout:``,stderr:`sudo: command-level approval is not configured
|
|
7429
7429
|
`,exitCode:1};if(!i.exec)return{stdout:``,stderr:`sudo: cannot dispatch inner command in this context
|
|
7430
7430
|
`,exitCode:1};let a=e.join(` `).trim(),o=await t.requestApproval({kind:`command`,detail:a});if(o.decision===`deny`)return{stdout:``,stderr:`sudo: approval denied
|
|
7431
|
-
`,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}function
|
|
7432
|
-
`,stderr:``,exitCode:0}}function
|
|
7433
|
-
`)}\n`:``,stderr:``,exitCode:0}}async function
|
|
7434
|
-
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=
|
|
7435
|
-
`)}\n`:``,stderr:``,exitCode:0}}function
|
|
7431
|
+
`,exitCode:1};if(o.decision===`always`){let e=o.pattern?.trim()||a;if(n)try{await n(e)}catch{}}return r&&r(a),i.exec(e[0],{cwd:i.cwd,args:e.slice(1)})})}function uK(){return{stdout:`usage: tar (-c|-x|-t) [-zv] -f <archive> [-C <dir>] [paths...]
|
|
7432
|
+
`,stderr:``,exitCode:0}}function dK(e){return{stdout:``,stderr:`tar: ${e}\n`,exitCode:1}}function fK(e,t){if(e.mode)return dK(`exactly one of -c, -x, or -t is required`);e.mode=t}function pK(e,t,n){if(n)return[n,t];let r=e[t+1];return r===void 0?void 0:[r,t+1]}const mK={c:`create`,x:`extract`,t:`list`};function hK(e,t,n,r,i){let a=mK[e];if(a)return{nextIndex:r,error:fK(i,a)};if(e===`z`)return i.gzip=!0,{nextIndex:r};if(e===`v`)return i.verbose=!0,{nextIndex:r};if(e!==`f`&&e!==`C`)return{nextIndex:r,error:dK(`unsupported option -${e}`)};let o=pK(n,r,t);return o?(e===`f`?i.archive=o[0]:i.directory=o[0],{nextIndex:o[1],consumedValue:!0}):{nextIndex:r,error:dK(`option -${e} requires an argument`)}}function gK(e,t,n){let r=e[t];for(let i=1;i<r.length;i++){let a=hK(r[i],r.slice(i+1),e,t,n);if(a.error||a.consumedValue)return a}return{nextIndex:t}}function _K(e){let t={gzip:!1,verbose:!1,directory:`.`,paths:[]};for(let n=0;n<e.length;n++){let r=e[n];if(!r.startsWith(`-`)||r===`-`){t.paths.push(r);continue}if(r.startsWith(`--`))return dK(`unsupported option ${r}`);let i=gK(e,n,t);if(i.error)return i.error;n=i.nextIndex}return t}function vK(e,t){let n=e.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^(?:\.\/)+/,``);return n?n===`.`?`.`:n.replace(/\/+$/,``):mn(t)}async function yK(e,t,n,r){let i=await e.fs.stat(t);if(i.isFile){r.push({path:n,bytes:await e.fs.readFileBuffer(t)});return}if(!i.isDirectory)throw Error(`unsupported file type: ${t}`);let a=n.endsWith(`/`)?n:`${n}/`;r.push({path:a,bytes:new Uint8Array,directory:!0});for(let n of await e.fs.readdir(t))await yK(e,pn(t,n),`${a}${n}`,r)}function bK(e,t){let n=e.length>=2&&e[0]===31&&e[1]===139;return Bt(t||n?Lt(e):e,{stripNpmPrefix:!1,includeDirectories:!0,preserveRawPaths:!0})}function xK(e,t,n){let r=n.replace(/\\/g,`/`);if(!r||r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)||r.split(`/`).includes(`..`))return;let i=e.fs.resolvePath(t,r);return rn(t,i)?i:void 0}async function SK(e,t){if(e.paths.length===0)return dK(`create mode requires at least one input path`);let n=[],r=t.fs.resolvePath(t.cwd,e.directory);for(let i of e.paths){let e=t.fs.resolvePath(r,i);await yK(t,e,vK(i,e),n)}let i=t.fs.resolvePath(t.cwd,e.archive),a=Ht(n);return await t.fs.writeFile(i,e.gzip?Nt(a):a),{stdout:e.verbose?`${n.map(e=>e.path).join(`
|
|
7433
|
+
`)}\n`:``,stderr:``,exitCode:0}}async function CK(e,t){if(e.paths.length>0)return dK(`${e.mode} mode does not accept input paths`);let n=t.fs.resolvePath(t.cwd,e.archive),r=bK(await t.fs.readFileBuffer(n),e.gzip);if(e.mode===`list`){let e=r.map(e=>e.path).join(`
|
|
7434
|
+
`);return{stdout:e?`${e}\n`:``,stderr:``,exitCode:0}}let i=t.fs.resolvePath(t.cwd,e.directory);await t.fs.mkdir(i,{recursive:!0});let a=[];for(let e of r){let n=xK(t,i,e.path);if(!n)return dK(`blocked suspicious path ${e.path}`);if(e.directory)await t.fs.mkdir(n,{recursive:!0});else{let r=dn(n);r!==`/`&&await t.fs.mkdir(r,{recursive:!0}),await t.fs.writeFile(n,e.bytes)}a.push(e.path)}return{stdout:e.verbose?`${a.join(`
|
|
7435
|
+
`)}\n`:``,stderr:``,exitCode:0}}function wK(){return G(`tar`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return uK();let n=_K(e);return`exitCode`in n?n:n.mode?n.archive?n.mode===`list`&&n.directory!==`.`?dK(`-C is only supported in create or extract mode`):n.mode===`create`?SK(n,t):CK(n,t):dK(`option -f requires an archive path`):dK(`exactly one of -c, -x, or -t is required`)})}var TK=`/**
|
|
7436
7436
|
* Standalone assertions - no dependency on test runner
|
|
7437
7437
|
*
|
|
7438
7438
|
* Each assertion:
|
|
@@ -7620,7 +7620,7 @@ function sameMembers(a, b) {
|
|
|
7620
7620
|
}
|
|
7621
7621
|
|
|
7622
7622
|
const slice = a => (isPrimitive(a) ? a : a.slice ? a.slice() : Object.assign({}, a))
|
|
7623
|
-
`,
|
|
7623
|
+
`,EK=`/**
|
|
7624
7624
|
* tst - minimal test runner
|
|
7625
7625
|
*
|
|
7626
7626
|
* - Standalone assertions (assert.js works anywhere)
|
|
@@ -8250,7 +8250,7 @@ function scheduleAutoRun() {
|
|
|
8250
8250
|
scheduleAutoRun()
|
|
8251
8251
|
|
|
8252
8252
|
export * from './assert.js'
|
|
8253
|
-
`;function
|
|
8253
|
+
`;function DK(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 OK=`tsc - thin wrapper over the ipk-loaded typescript package
|
|
8254
8254
|
|
|
8255
8255
|
Usage:
|
|
8256
8256
|
tsc [options] [files...]
|
|
@@ -8274,27 +8274,27 @@ Install:
|
|
|
8274
8274
|
Then \`tsc --version\` and the transpile commands above. There is no
|
|
8275
8275
|
bundled binary, no CDN fallback; a missing package exits non-zero
|
|
8276
8276
|
with a clear \`ipk add\` hint.
|
|
8277
|
-
`;function
|
|
8278
|
-
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function
|
|
8279
|
-
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function
|
|
8277
|
+
`;function kK(e){let t=[],n=!1,r=null,i=!1,a=!1;for(let o=0;o<e.length;o++){let s=e[o];if(s===`-h`||s===`--help`){i=!0;continue}if(s===`-v`||s===`--version`){a=!0;continue}if(s===`--noEmit`){n=!0;continue}if(s===`--outDir`){let t=e[o+1];if(typeof t!=`string`||t.startsWith(`-`))throw Error(`tsc: --outDir requires a value`);r=t,o+=1;continue}if(s.startsWith(`--outDir=`)){r=s.slice(9);continue}if(s.startsWith(`-`))throw Error(`tsc: unknown option: ${s}`);t.push(s)}return{files:t,noEmit:n,outDir:r,showHelp:i,showVersion:a}}function AK(e,t){let n=`${mn(e).replace(/\.(ts|tsx|mts|cts)$/i,``)}.js`;return t?`${t.endsWith(`/`)?t.slice(0,-1):t}/${n}`:`${dn(e)}/${n}`}async function jK(e,t){let n=t||`/`,r=``;for(;n&&n!==r;){let t=n===`/`?`/tsconfig.json`:`${n}/tsconfig.json`;if(await e.exists(t))return t;r=n,n=dn(n)}return null}const MK={target:`ES2022`,module:`ESNext`,moduleResolution:`Bundler`,esModuleInterop:!0,allowSyntheticDefaultImports:!0,isolatedModules:!0};async function NK(e,t,n){let r=await jK(e,n);if(!r)return{compilerOptions:{...MK}};let i;try{i=await e.readFile(r)}catch{return{compilerOptions:{...MK}}}let{config:a,error:o}=t.parseConfigFileTextToJson(r,i);if(o||!a)return{compilerOptions:{...MK}};let s=a.compilerOptions??{};return{compilerOptions:{...MK,...s}}}function PK(e,t){let n=e.flattenDiagnosticMessageText(t.messageText,`
|
|
8278
|
+
`);if(t.file&&typeof t.start==`number`){let{line:e,character:r}=t.file.getLineAndCharacterOfPosition(t.start);return`${t.file.fileName}(${e+1},${r+1}): error TS${t.code}: ${n}`}return`error TS${t.code}: ${n}`}function FK(e,t){let n=t.toLowerCase();return n.endsWith(`.tsx`)?e.ScriptKind.TSX:n.endsWith(`.jsx`)?e.ScriptKind.JSX:n.endsWith(`.js`)||n.endsWith(`.mjs`)||n.endsWith(`.cjs`)?e.ScriptKind.JS:e.ScriptKind.TS}function IK(e,t,n,r,i){let a=e.transpileModule(t,{compilerOptions:r,fileName:n,reportDiagnostics:i});return{outputText:a.outputText,diagnostics:a.diagnostics??[]}}function LK(e,t,n,r){let{outputText:i,diagnostics:a}=IK(e,r,`<stdin>.ts`,n.compilerOptions,!0),o=a.map(t=>PK(e,t)),s=o.length>0?`${o.join(`
|
|
8279
|
+
`)}\n`:``;return{stdout:t.noEmit?``:i,stderr:s,exitCode:+(a.length>0)}}async function RK(e,t,n,r,i){let a=t.fs.resolvePath(t.cwd,n);if(!await t.fs.exists(a))return{stderr:`tsc: ${n}: no such file\n`,hadError:!0};let o;try{o=await t.fs.readFile(a)}catch(e){return{stderr:`tsc: ${n}: ${e instanceof Error?e.message:String(e)}\n`,hadError:!0}}FK(e,a);let{outputText:s,diagnostics:c}=IK(e,o,a,i.compilerOptions,!0),l=[];for(let t of c)l.push(`${PK(e,t)}\n`);let u=c.length>0;if(r.noEmit)return{stderr:l.join(``),hadError:u};let d=t.fs.resolvePath(t.cwd,AK(a,r.outDir));try{await t.fs.writeFile(d,s)}catch(e){l.push(`tsc: ${d}: ${e instanceof Error?e.message:String(e)}\n`),u=!0}return{stderr:l.join(``),hadError:u}}async function zK(e,t){let n;try{n=kK(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:OK,stderr:``,exitCode:0}};let r;try{r=await fn(DK(t))}catch(e){return{done:{stdout:``,stderr:`tsc: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}return n.showVersion?{done:{stdout:`Version ${r.version}\n`,stderr:``,exitCode:0}}:{parsed:n,ts:r}}function BK(){return G(`tsc`,async(e,t)=>{let n=await zK(e,t);if(`done`in n)return n.done;let{parsed:r,ts:i}=n,a=await NK(t.fs,i,t.cwd);if(r.files.length===0){let e=Pk(t.stdin);return e?LK(i,r,a,e):{stdout:OK,stderr:``,exitCode:0}}let o=[],s=!1;for(let e of r.files){let n=await RK(i,t,e,r,a);n.stderr&&o.push(n.stderr),n.hadError&&(s=!0)}return{stdout:``,stderr:o.join(``),exitCode:+!!s}})}const VK=[`**/*.test.{js,ts}`];function HK(e){let t=[],n=`tap`,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`-h`||a===`--help`){r=!0;continue}if(a===`--reporter`){let t=e[i+1];if(t!==`tap`&&t!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=t,i+=1;continue}if(a.startsWith(`--reporter=`)){let e=a.slice(11);if(e!==`tap`&&e!==`spec`)throw Error(`test: --reporter must be tap or spec`);n=e;continue}if(a.startsWith(`-`))throw Error(`test: unknown option: ${a}`);t.push(a)}return{globs:t.length>0?t:[...VK],reporter:n,showHelp:r}}function UK(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=e.indexOf(`}`,t);if(n===-1)return[e];let r=e.slice(0,t),i=e.slice(n+1),a=e.slice(t+1,n).split(`,`),o=[];for(let e of a)for(let t of UK(`${r}${e}${i}`))o.push(t);return o}function WK(e){let t=``,n=0;for(;n<e.length;){let r=e[n];r===`*`&&e[n+1]===`*`?(t+=`(?:.*/)?`,n+=2,e[n]===`/`&&(n+=1)):r===`*`?(t+=`[^/]*`,n+=1):r===`?`?(t+=`[^/]`,n+=1):`.+^$()[]|\\`.includes(r)?(t+=`\\${r}`,n+=1):(t+=r,n+=1)}return RegExp(`^${t}$`)}async function GK(e,t,n){let r=n.flatMap(UK).map(WK),i=new Set,a=t===`/`?``:t;async function o(t){let n;try{n=await e.readdir(t)}catch{return}for(let s of n){if(s===`node_modules`||s.startsWith(`.`))continue;let n=t===`/`?`/${s}`:`${t}/${s}`,c=!1;try{c=(await e.stat(n)).isDirectory}catch{continue}if(c){await o(n);continue}let l=n.startsWith(`${a}/`)?n.slice(a.length+1):n;r.some(e=>e.test(l))&&i.add(n)}}return await o(t),[...i].sort()}let KK=null;async function qK(e){if(KK)return KK;let t={module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,esModuleInterop:!0,isolatedModules:!1};return KK=`
|
|
8280
8280
|
if (typeof process !== 'undefined' && !process.versions) {
|
|
8281
8281
|
try { process.versions = { node: '20.0.0' }; } catch (_) { /* readonly process.versions is fine */ }
|
|
8282
8282
|
}
|
|
8283
8283
|
const __tst_assert_exports = (function () {
|
|
8284
8284
|
const module = { exports: {} };
|
|
8285
8285
|
const exports = module.exports;
|
|
8286
|
-
${e.transpileModule(
|
|
8286
|
+
${e.transpileModule(TK,{compilerOptions:t,fileName:`assert.js`}).outputText}
|
|
8287
8287
|
return module.exports;
|
|
8288
8288
|
})();
|
|
8289
8289
|
const __tst_module_exports = (function () {
|
|
8290
8290
|
const module = { exports: {} };
|
|
8291
8291
|
const exports = module.exports;
|
|
8292
|
-
${e.transpileModule(
|
|
8292
|
+
${e.transpileModule(EK,{compilerOptions:t,fileName:`tst.js`}).outputText.replace(/require\(["']\.\/assert\.js["']\)/g,`__tst_assert_exports`).replace(/\bimport\.meta\b/g,`({url:""})`).replace(/await\s+import\(['"](?:worker_threads|fs|path)['"]\)/g,`await Promise.reject(new Error("test: fork mode is not supported in the realm"))`)}
|
|
8293
8293
|
return module.exports;
|
|
8294
8294
|
})();
|
|
8295
8295
|
const __tst = __tst_module_exports.default || __tst_module_exports;
|
|
8296
8296
|
__tst.manual = true;
|
|
8297
|
-
`.trim(),
|
|
8297
|
+
`.trim(),KK}function JK(e,t=new Map){return e.replace(/(^|[^\w$.])require\(\s*(["'`])([^"'`]+)\2\s*\)/g,(e,n,r,i)=>i===`tst`||i===`tst/tst.js`?`${n}__tstReq("tst")`:i===`tst/assert`||i===`tst/assert.js`?`${n}__tstReq("tst/assert")`:t.has(i)?`${n}__localReq(${JSON.stringify(t.get(i))})`:e)}function YK(e){let t=new Set,n=/(?:^|[^\w$.])require\(\s*(["'`])([^"'`]+)\1\s*\)/g,r;for(;(r=n.exec(e))!==null;)t.add(r[2]);return[...t]}async function XK(e,t,n){let r=rt(`${t}/${n}`),i=[r];r.endsWith(`.js`)&&i.push(`${r.slice(0,-3)}.ts`),/\.[a-zA-Z0-9]+$/.test(r)||i.push(`${r}.ts`,`${r}.js`);for(let t of i)if(await e.exists(t))return t;return null}async function ZK(e,t,n,r,i){let a=new Map,o=new Map,s=[{path:n,cjs:r}];for(;s.length>0;){let{path:n,cjs:r}=s.shift(),c=dn(n),l=new Map;for(let n of YK(r)){if(!n.startsWith(`./`)&&!n.startsWith(`../`))continue;let r=await XK(e,c,n);if(!r||(l.set(n,r),a.has(r)))continue;let o=await e.readFile(r),u=t.transpileModule(o,{compilerOptions:i,fileName:r}).outputText;a.set(r,u),s.push({path:r,cjs:u})}o.set(n,l)}return{modules:a,edgeRewrites:o}}function QK(e,t,n,r,i,a){let o=r===`spec`?`pretty`:`tap`,s=[];for(let[e,t]of i.entries()){let n=JK(t,a.get(e)??new Map);s.push(`${JSON.stringify(e)}: function (module, exports, require) {\n${n}\n}`)}return`"use strict";
|
|
8298
8298
|
${e}
|
|
8299
8299
|
const __tstReq = (id) => {
|
|
8300
8300
|
if (id === "tst") return __tst_module_exports;
|
|
@@ -8314,7 +8314,7 @@ const __localReq = (absPath) => {
|
|
|
8314
8314
|
return module.exports;
|
|
8315
8315
|
};
|
|
8316
8316
|
await (async function (require) {
|
|
8317
|
-
${
|
|
8317
|
+
${JK(n,a.get(t)??new Map)}
|
|
8318
8318
|
})(__tstReq);
|
|
8319
8319
|
const __state = await __tst.run({ format: ${JSON.stringify(o)} });
|
|
8320
8320
|
// EXT6 (F-C03): for an explicit single-file run under the default tap
|
|
@@ -8326,7 +8326,7 @@ const __state = await __tst.run({ format: ${JSON.stringify(o)} });
|
|
|
8326
8326
|
await Promise.resolve();
|
|
8327
8327
|
await new Promise((resolve) => setTimeout(resolve));
|
|
8328
8328
|
if (__state && __state.failed && __state.failed.length > 0) process.exit(1);
|
|
8329
|
-
`}const
|
|
8329
|
+
`}const $K={esModuleInterop:!0,allowJs:!0,isolatedModules:!1};function eq(e){return{module:e.ModuleKind.CommonJS,target:e.ScriptTarget.ES2022,...$K}}async function tq(e,t){let n;try{n=HK(e)}catch(e){return{done:{stdout:``,stderr:`${e instanceof Error?e.message:String(e)}\n`,exitCode:2}}}if(n.showHelp)return{done:{stdout:`test - run *.test.{js,ts} files with the bundled tst runner
|
|
8330
8330
|
|
|
8331
8331
|
Usage:
|
|
8332
8332
|
test [options] [glob...]
|
|
@@ -8339,7 +8339,7 @@ Notes:
|
|
|
8339
8339
|
- Default glob: **/*.test.{js,ts}, walked from the current cwd.
|
|
8340
8340
|
- .ts files are transpiled via the bundled typescript package.
|
|
8341
8341
|
- Each file runs in its own realm (same engine as 'node').
|
|
8342
|
-
`,stderr:``,exitCode:0}};let r=await
|
|
8342
|
+
`,stderr:``,exitCode:0}};let r=await GK(t.fs,t.cwd,n.globs);if(r.length===0)return{done:{stdout:``,stderr:`test: no test files matched ${n.globs.join(` `)}\n`,exitCode:1}};let i;try{i=await fn(DK(t))}catch(e){return{done:{stdout:``,stderr:`test: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}}let a=await qK(i);return{parsed:n,files:r,ts:i,harness:a,userOpts:eq(i)}}function nq(e){return e.includes(`# fail `)||/(^|\n)not ok /.test(e)}async function rq(e,t,n,r){let{ts:i,harness:a,userOpts:o,parsed:s}=t,c;try{c=await e.fs.readFile(n)}catch(e){return{stdout:``,stderr:`test: ${n}: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let l;try{l=i.transpileModule(c,{compilerOptions:o,fileName:n}).outputText}catch(e){return{stdout:``,stderr:`test: ${n}: transpile error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let u,d;try{({modules:u,edgeRewrites:d}=await ZK(e.fs,i,n,l,o))}catch(e){return{stdout:``,stderr:`test: ${n}: local-require resolve error: ${e instanceof Error?e.message:String(e)}\n`,failed:!0}}let f=await Lk(QK(a,n,l,s.reporter,u,d),[`node`,n],e,void 0,{filename:n});return{stdout:r?`# ${n}\n${f.stdout}`:f.stdout,stderr:f.stderr,failed:f.exitCode!==0||nq(f.stdout)}}function iq(){return G(`test`,async(e,t)=>{let n=await tq(e,t);if(`done`in n)return n.done;let r=n.files.length>1,i=``,a=``,o=!1;for(let e of n.files){let s=await rq(t,n,e,r);i+=s.stdout,a+=s.stderr,s.failed&&(o=!0)}return{stdout:i,stderr:a,exitCode:+!!o}})}const aq=`usage: theme <subcommand> [args]
|
|
8343
8343
|
|
|
8344
8344
|
Subcommands:
|
|
8345
8345
|
list List available preset and custom themes
|
|
@@ -8348,21 +8348,21 @@ Subcommands:
|
|
|
8348
8348
|
reset Reset to the default theme
|
|
8349
8349
|
current Show the currently active theme
|
|
8350
8350
|
export <id> <path> Export a theme to a VFS path
|
|
8351
|
-
`;function
|
|
8352
|
-
`),stderr:``,exitCode:0}}async function
|
|
8353
|
-
`,stderr:``,exitCode:0}}async function
|
|
8351
|
+
`;function oq(){return G(`theme`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:aq,stderr:``,exitCode:0};let n=e[0];return n===`list`?sq():n===`current`?cq():n===`reset`?lq():n===`apply`?uq(e.slice(1),t):n===`export`?dq(e.slice(1),t):{stdout:``,stderr:`theme: unknown subcommand "${n}"\n${aq}`,exitCode:1}})}async function sq(){let{PRESETS:e}=await import(`./theme-presets-xiOb9AFN.js`),t=[`Presets:`];for(let n of e)t.push(` ${n.id.padEnd(16)} ${n.name}`);return t.push(``),{stdout:t.join(`
|
|
8352
|
+
`),stderr:``,exitCode:0}}async function cq(){return{stdout:`Check the Theme settings dialog for the active theme.
|
|
8353
|
+
`,stderr:``,exitCode:0}}async function lq(){let e=He();return e?(await e.call(`theme-apply`,{action:`reset`}),{stdout:`Theme reset to default.
|
|
8354
8354
|
`,stderr:``,exitCode:0}):{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
8355
|
-
`,exitCode:1}}async function
|
|
8355
|
+
`,exitCode:1}}async function uq(e,t){if(e.length===0)return{stdout:``,stderr:`theme apply: missing theme id or path
|
|
8356
8356
|
`,exitCode:1};let n=He();if(!n)return{stdout:``,stderr:`theme: no panel-RPC connection available
|
|
8357
8357
|
`,exitCode:1};let r=e[0],{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===r);if(a){let e=JSON.stringify(a);return await n.call(`theme-apply`,{themeJson:e,action:`apply`}),{stdout:`Applied theme: ${a.name}\n`,stderr:``,exitCode:0}}let o=t.fs.resolvePath(t.cwd,r),s;try{s=await t.fs.readFile(o)}catch{return{stdout:``,stderr:`theme apply: "${r}" is not a known preset id and file not found at ${o}\n`,exitCode:1}}try{let e=JSON.parse(s);if(!e.id||!e.name||!e.base||!e.tokens)return{stdout:``,stderr:`theme apply: invalid theme file (missing id, name, base, or tokens)
|
|
8358
8358
|
`,exitCode:1}}catch{return{stdout:``,stderr:`theme apply: file is not valid JSON
|
|
8359
|
-
`,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:s,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function
|
|
8360
|
-
`,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function
|
|
8361
|
-
`,stderr:``,exitCode:0}}function
|
|
8359
|
+
`,exitCode:1}}return{stdout:`Applied theme: ${(await n.call(`theme-apply`,{themeJson:s,action:`apply`})).applied}\n`,stderr:``,exitCode:0}}async function dq(e,t){if(e.length<2)return{stdout:``,stderr:`theme export: usage: theme export <id> <path>
|
|
8360
|
+
`,exitCode:1};let[n,r]=e,{PRESETS:i}=await import(`./theme-presets-xiOb9AFN.js`),a=i.find(e=>e.id===n);if(!a)return{stdout:``,stderr:`theme export: unknown preset id "${n}"\n`,exitCode:1};let o=t.fs.resolvePath(t.cwd,r);try{await t.fs.writeFile(o,JSON.stringify(a,null,2))}catch(e){return{stdout:``,stderr:`theme export: write failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return{stdout:`Exported "${a.name}" to ${o}\n`,stderr:``,exitCode:0}}function fq(){return{stdout:`usage: uname
|
|
8361
|
+
`,stderr:``,exitCode:0}}function pq(){return G(`uname`,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return fq();if(e.length>0)return{stdout:``,stderr:`uname: unsupported arguments
|
|
8362
8362
|
`,exitCode:1};let t=globalThis.navigator?.userAgent;return typeof t!=`string`||t.length===0?{stdout:``,stderr:`uname: navigator.userAgent is unavailable
|
|
8363
|
-
`,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function
|
|
8364
|
-
`,stderr:``,exitCode:0}}function
|
|
8365
|
-
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=Ft(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!rn(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=dn(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const
|
|
8363
|
+
`,exitCode:1}:{stdout:`${t}\n`,stderr:``,exitCode:0}})}function mq(){return{stdout:`usage: unzip <archive.zip> [-d <destination>]
|
|
8364
|
+
`,stderr:``,exitCode:0}}function hq(){return G(`unzip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return mq();let n=`.`,r=[];for(let t=0;t<e.length;t++){let i=e[t];if(i===`-d`){n=e[t+1]??``,t++;continue}if(i.startsWith(`-`))return{stdout:``,stderr:`unzip: unsupported option ${i}\n`,exitCode:1};r.push(i)}if(r.length<1)return{stdout:``,stderr:`unzip: expected archive path
|
|
8365
|
+
`,exitCode:1};let i=t.fs.resolvePath(t.cwd,r[0]),a=t.fs.resolvePath(t.cwd,n||`.`);await t.fs.mkdir(a,{recursive:!0});let o=Ft(await t.fs.readFileBuffer(i)),s=0;for(let[e,n]of Object.entries(o)){let r=e.replace(/\\/g,`/`);if(!r||r.endsWith(`/`))continue;let i=t.fs.resolvePath(a,r);if(!rn(a,i))return{stdout:``,stderr:`unzip: blocked suspicious path ${e}\n`,exitCode:1};let o=dn(i);o!==`/`&&await t.fs.mkdir(o,{recursive:!0}),await t.fs.writeFile(i,n),s++}return{stdout:`extracted ${s} file(s) to ${a}\n`,stderr:``,exitCode:0}})}const gq=new Set([`--vid`,`--pid`,`--class`,`--subclass`,`--protocol`,`--serial`,`--request-type`,`--recipient`,`--request`,`--value`,`--index`,`--__resolved`]);function _q(e){return wm(e,gq)}function vq(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 yq(e){let t={};return e.has(`--vid`)&&(t.vendorId=vq(e.get(`--vid`),`vid`)),e.has(`--pid`)&&(t.productId=vq(e.get(`--pid`),`pid`)),e.has(`--class`)&&(t.classCode=vq(e.get(`--class`),`class`)),e.has(`--subclass`)&&(t.subclassCode=vq(e.get(`--subclass`),`subclass`)),e.has(`--protocol`)&&(t.protocolCode=vq(e.get(`--protocol`),`protocol`)),e.has(`--serial`)&&(t.serialNumber=e.get(`--serial`)),Object.keys(t).length>0?[t]:[]}const bq=new Set([`standard`,`class`,`vendor`]),xq=new Set([`device`,`interface`,`endpoint`,`other`]);function Sq(e){let t=e.get(`--request-type`)??`vendor`,n=e.get(`--recipient`)??`device`;if(!bq.has(t))throw Error(`invalid --request-type: '${t}'`);if(!xq.has(n))throw Error(`invalid --recipient: '${n}'`);return{requestType:t,recipient:n,request:vq(e.get(`--request`)??`0`,`request`),value:vq(e.get(`--value`)??`0`,`value`),index:vq(e.get(`--index`)??`0`,`index`)}}function Cq(e){let t=Fk(e.stdin),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e)&255;return n}function wq(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(` `)}function Tq(e){return`0x${e.toString(16).padStart(4,`0`)}`}function Eq(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${Tq(e.vendorId)}:${Tq(e.productId)}\t${t}${n}${r}`}function Dq(e){return{stdout:e,stderr:``,exitCode:0}}function Oq(e){return{stdout:``,stderr:`usb: ${e}\n`,exitCode:1}}const kq=`usb - access USB devices via WebUSB
|
|
8366
8366
|
|
|
8367
8367
|
Usage: usb <subcommand> [options]
|
|
8368
8368
|
|
|
@@ -8390,10 +8390,10 @@ Options:
|
|
|
8390
8390
|
--raw Emit raw bytes for *-in transfers (default: hex dump)
|
|
8391
8391
|
-h, --help
|
|
8392
8392
|
|
|
8393
|
-
Transfers are capped at ${
|
|
8394
|
-
`;function
|
|
8395
|
-
`):
|
|
8396
|
-
`)}\n`)}async function
|
|
8393
|
+
Transfers are capped at ${lO} bytes (4 MiB).
|
|
8394
|
+
`;function Aq(e,t){if(t){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return Dq(t)}return Dq(e.length?`${wq(e)}\n`:``)}async function jq(e){let t=await e.list();return t.length===0?Dq(`no granted USB devices
|
|
8395
|
+
`):Dq(`${t.map(Eq).join(`
|
|
8396
|
+
`)}\n`)}async function Mq(e,t){let n=e.get(`--__resolved`);if(n)return Dq(`${Eq(await t.info(n))}\n`);let r=yq(e),i=re();if(i){let e=await I(`usb-device`,r,i);if(e.handle)return Dq(`${Eq(await t.info(e.handle))}\n`);let n=e.info,a=iO();if(!a)return Oq(`request: WebUSB unavailable for device re-acquire`);let o=(await a.getDevices()).find(e=>e.vendorId===n.vendorId&&e.productId===n.productId&&(!n.serialNumber||e.serialNumber===n.serialNumber));return o?Dq(`${Eq(uO(cO().register(o),o))}\n`):Oq(`request: granted device could not be re-acquired`)}return Dq(`${Eq(await t.request(r))}\n`)}async function Nq(e,t,n){let r=t[1];return r?(e===`open`?await n.open(r):e===`close`?await n.close(r):await n.reset(r),Dq(``)):Oq(`${e}: handle required`)}async function Pq(e,t){let[,n,r]=e;return!n||r===void 0?Oq(`select-config: handle and value required`):(await t.selectConfig(n,vq(r,`configuration`)),Dq(``))}async function Fq(e,t,n){let[,r,i]=t;return!r||i===void 0?Oq(`${e}: handle and interface required`):(await(e===`claim`?n.claim:n.release).call(n,r,vq(i,`interface`)),Dq(``))}async function Iq(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Oq(`control-in: handle and length required`);let o=vq(a,`length`);return o>4194304?Oq(`control-in length exceeds 4 MiB limit`):Aq((await n.controlIn(i,Sq(t),o)).bytes,r)}async function Lq(e,t,n,r){let i=e[1];if(!i)return Oq(`control-out: handle required`);let a=Cq(t);return a.length>4194304?Oq(`control-out payload exceeds 4 MiB limit`):Dq(`${(await r.controlOut(i,Sq(n),a)).bytesWritten} bytes written\n`)}async function Rq(e,t,n,r){let[,i,a,o]=e;if(!i||a===void 0||o===void 0)return Oq(`transfer-in: handle, endpoint and length required`);let s=vq(o,`length`);return s>4194304?Oq(`transfer-in length exceeds 4 MiB limit`):Aq((await n.transferIn(i,vq(a,`endpoint`),s)).bytes,r)}async function zq(e,t,n,r){let[,i,a]=e;if(!i||a===void 0)return Oq(`transfer-out: handle and endpoint required`);let o=Cq(t);return o.length>4194304?Oq(`transfer-out payload exceeds 4 MiB limit`):Dq(`${(await r.transferOut(i,vq(a,`endpoint`),o)).bytesWritten} bytes written\n`)}async function Bq(e,t,n){let{positionals:r,flags:i,bools:a}=_q(e),o=r[0],s=a.has(`--raw`);switch(o){case`list`:return jq(n);case`request`:return Mq(i,n);case`open`:case`close`:case`reset`:return Nq(o,r,n);case`select-config`:return Pq(r,n);case`claim`:case`release`:return Fq(o,r,n);case`control-in`:return Iq(r,i,n,s);case`control-out`:return Lq(r,t,i,n);case`transfer-in`:return Rq(r,i,n,s);case`transfer-out`:return zq(r,t,i,n);default:return Oq(`unknown subcommand '${o??``}'. Try 'usb --help'.`)}}function Vq(){return G(`usb`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Dq(kq);let n=NO(Ue(),He());if(!n)return Oq(`WebUSB is unavailable in this environment`);try{return await Bq(e,t,n)}catch(e){let t=e instanceof Error?e.message:String(e);return/cancelled|NotFoundError|No device selected/i.test(t)?Oq(`user cancelled or no device selected`):Oq(t)}})}function Hq(){return{stdout:`usage: webhook <command> [options]
|
|
8397
8397
|
|
|
8398
8398
|
Commands:
|
|
8399
8399
|
create --scoop <name> [--name <name>] [--filter <code>] Create a new webhook endpoint
|
|
@@ -8411,16 +8411,16 @@ Examples:
|
|
|
8411
8411
|
webhook create --scoop slack-relay --name slack --filter "(e) => ({ text: e.body.text, user: e.body.user })"
|
|
8412
8412
|
webhook list
|
|
8413
8413
|
webhook delete abc123
|
|
8414
|
-
`,stderr:``,exitCode:0}}function
|
|
8414
|
+
`,stderr:``,exitCode:0}}function Uq(){return globalThis.__slicc_lickManager??null}async function Wq(){if(Uq())return Re().session?.webhookUrl??null;let{getTrayWebhookUrlAsync:e}=await import(`./lick-manager-proxy-DCbHSHHW.js`);return await e()}function Gq(e,t){return t?ze(t,e):S()?Ve(self.location.href,e):`(URL unavailable — connect a leader tray)`}function Kq(e){return{stdout:``,stderr:`webhook ${e}: kernel host has not booted yet — try again in a moment\n`,exitCode:1}}async function qq(e){let t=`default`,n,r,i=e.indexOf(`--name`);i!==-1&&e[i+1]&&(t=e[i+1]);let a=e.indexOf(`--filter`);a!==-1&&e[a+1]&&(n=e[a+1]);let o=e.indexOf(`--scoop`);if(o!==-1&&e[o+1]&&(r=e[o+1]),!r)return{stdout:``,stderr:`webhook create: --scoop is required (every webhook must route to a scoop)
|
|
8415
8415
|
`,exitCode:1};if(!S()&&n)return{stdout:``,stderr:`webhook create: --filter is not supported in extension mode (CSP forbids dynamic eval) — drop --filter, or use standalone CLI mode
|
|
8416
|
-
`,exitCode:1};let s=await
|
|
8417
|
-
`,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await
|
|
8418
|
-
`,exitCode:1};let n=await
|
|
8419
|
-
`,exitCode:1}}return null}async function
|
|
8416
|
+
`,exitCode:1};let s=await Xq();if(s)return s;let c=await DG();if(!c)return Kq(`create`);let l=await c.createWebhook(t,r,n),u=await Zq(l.id),d=`Created webhook "${l.name}"\nID: ${l.id}\nURL: ${u}\n`;return l.scoop&&(d+=`Scoop: ${l.scoop}\n`),l.filter&&(d+=`Filter: ${l.filter}\n`),{stdout:d,stderr:``,exitCode:0}}async function Jq(){let e=await DG();if(!e)return Kq(`list`);let t=await e.listWebhooks();if(t.length===0)return{stdout:`No active webhooks
|
|
8417
|
+
`,stderr:``,exitCode:0};let{trayUrlBase:n,urlResolutionError:r}=await Qq();return{stdout:$q(t.map(e=>({id:e.id,name:e.name,url:Gq(e.id,n),createdAt:e.createdAt,filter:e.filter,scoop:e.scoop})),n,r),stderr:``,exitCode:0}}async function Yq(e){let t=e[1];if(!t)return{stdout:``,stderr:`webhook delete: requires an ID
|
|
8418
|
+
`,exitCode:1};let n=await DG();return n?await n.deleteWebhook(t)?{stdout:`Deleted webhook "${t}"\n`,stderr:``,exitCode:0}:{stdout:``,stderr:`webhook delete: webhook "${t}" not found\n`,exitCode:1}:Kq(`delete`)}async function Xq(){if(S())return null;if(!await Wq()){let e=Re().state;return{stdout:``,stderr:(e===`leader`?`webhook create: tray session is not connected yet — wait for the leader to attach`:`webhook create: requires extension-leader mode with a tray worker URL configured (current state: "${e}")`)+`
|
|
8419
|
+
`,exitCode:1}}return null}async function Zq(e){try{return Gq(e,await Wq())}catch(e){return`(URL resolution failed: ${e instanceof Error?e.message:String(e)})`}}async function Qq(){try{return{trayUrlBase:await Wq(),urlResolutionError:null}}catch(e){return{trayUrlBase:null,urlResolutionError:e instanceof Error?e.message:String(e)}}}function $q(e,t,n){let r=`Active webhooks:
|
|
8420
8420
|
`;for(let t of e)r+=` ${t.id} ${t.name.padEnd(20)} ${t.url}`,t.scoop&&(r+=` -> ${t.scoop}`),t.filter&&(r+=` [filtered]`),r+=`
|
|
8421
8421
|
`;return n?r+=`\nNote: webhook URL resolution failed (${n}). Try again once the tray is connected.\n`:!S()&&!t&&(r+=`
|
|
8422
8422
|
Note: webhook URLs require a leader tray. Configure one in Settings to expose POST endpoints.
|
|
8423
|
-
`),r}function
|
|
8423
|
+
`),r}function eJ(){return G(`webhook`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return Hq();let t=e[0];try{switch(t){case`create`:return await qq(e);case`list`:return await Jq();case`delete`:return await Yq(e);default:return{stdout:``,stderr:`webhook: unknown command "${t}"\n`,exitCode:1}}}catch(e){let n=e instanceof Error?e.message:String(e);return{stdout:``,stderr:`webhook ${t??`?`}: ${n}\n`,exitCode:1}}})}function tJ(){return{stdout:`usage: websocat [FLAGS] [OPTIONS] <ws://URL | wss://URL>
|
|
8424
8424
|
|
|
8425
8425
|
Minimal websocat client. Sends stdin lines as WebSocket messages and prints
|
|
8426
8426
|
received messages to stdout. Server mode and advanced specifiers (exec:, tcp:,
|
|
@@ -8462,19 +8462,19 @@ EXAMPLES:
|
|
|
8462
8462
|
echo 'Page.navigate {"url":"https://example.com"}' \\
|
|
8463
8463
|
| websocat -1 --jsonrpc --jsonrpc-omit-jsonrpc \\
|
|
8464
8464
|
ws://127.0.0.1:9222/devtools/page/<id>
|
|
8465
|
-
`,stderr:``,exitCode:0}}const
|
|
8465
|
+
`,stderr:``,exitCode:0}}const nJ=new Set([`-s`,`--server-mode`,`--oneshot`,`--socks5`,`--basic-auth`,`--basic-auth-file`,`--header-to-env`,`--server-header`,`--exec`,`--ws-c-uri`,`--restrict-uri`,`--unlink`,`--strict`,`-S`]);function rJ(e){let t={text:!0,binary:!1,oneMessage:!1,noClose:!1,exitOnEof:!1,unidirectional:!1,unidirectionalReverse:!1,insecure:!1,quiet:!1,verbose:0,nullTerminated:!1,base64:!1,jsonrpc:!1,jsonrpcOmit:!1,bufferSize:65536,connTimeoutMs:3e4,customHeaders:[],showHelp:!1},n=(n,r)=>{let i=e[n].indexOf(`=`);if(i!==-1&&e[n].startsWith(r))return{value:e[n].slice(i+1),next:n};let a=e[n+1];return a===void 0?(t.error=`websocat: missing value for ${r}\n`,null):{value:a,next:n+1}};for(let r=0;r<e.length;r+=1){let i=e[r];if(i===`-h`||i===`--help`)return t.showHelp=!0,t;if(nJ.has(i)||nJ.has(i.split(`=`)[0]))return t.error=`websocat: flag '${i}' is not supported in slicc's minimal client\n`,t;if(i===`-t`||i===`--text`){t.text=!0,t.binary=!1;continue}if(i===`-b`||i===`--binary`){t.binary=!0,t.text=!1;continue}if(i===`-1n`||i===`-n1`){t.oneMessage=!0,t.noClose=!0;continue}if(i===`-1`||i===`--one-message`){t.oneMessage=!0;continue}if(i===`-n`||i===`--no-close`){t.noClose=!0;continue}if(i===`-E`||i===`--exit-on-eof`){t.exitOnEof=!0;continue}if(i===`-u`||i===`--unidirectional`){t.unidirectional=!0;continue}if(i===`-U`||i===`--unidirectional-reverse`){t.unidirectionalReverse=!0;continue}if(i===`-k`||i===`--insecure`){t.insecure=!0;continue}if(i===`-q`){t.quiet=!0;continue}if(i===`-v`){t.verbose+=1;continue}if(i===`-vv`){t.verbose+=2;continue}if(i===`-0`||i===`--null-terminated`){t.nullTerminated=!0;continue}if(i===`--base64`){t.base64=!0;continue}if(i===`--jsonrpc`){t.jsonrpc=!0;continue}if(i===`--jsonrpc-omit-jsonrpc`){t.jsonrpcOmit=!0,t.jsonrpc=!0;continue}if(i===`--close-status-code`||i.startsWith(`--close-status-code=`)){let e=n(r,`--close-status-code`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<1e3||i>4999)return t.error=`websocat: --close-status-code expects 1000..4999, got '${e.value}'\n`,t;t.closeStatus=i,r=e.next;continue}if(i===`--close-reason`||i.startsWith(`--close-reason=`)){let e=n(r,`--close-reason`);if(!e)return t;t.closeReason=e.value,r=e.next;continue}if(i===`-B`||i===`--buffer-size`||i.startsWith(`--buffer-size=`)){let e=n(r,i===`-B`?`-B`:`--buffer-size`);if(!e)return t;let a=Number(e.value);if(!Number.isFinite(a)||a<=0)return t.error=`websocat: --buffer-size expects positive integer
|
|
8466
8466
|
`,t;t.bufferSize=a,r=e.next;continue}if(i===`--max-messages`||i.startsWith(`--max-messages=`)){let e=n(r,`--max-messages`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --max-messages expects positive integer
|
|
8467
8467
|
`,t;t.maxMessages=i,r=e.next;continue}if(i===`--protocol`||i.startsWith(`--protocol=`)){let e=n(r,`--protocol`);if(!e)return t;t.protocol=e.value,r=e.next;continue}if(i===`--ping-interval`||i.startsWith(`--ping-interval=`)){let e=n(r,`--ping-interval`);if(!e)return t;t.pingInterval=Number(e.value),r=e.next;continue}if(i===`--conn-timeout`||i.startsWith(`--conn-timeout=`)){let e=n(r,`--conn-timeout`);if(!e)return t;let i=Number(e.value);if(!Number.isFinite(i)||i<=0)return t.error=`websocat: --conn-timeout expects positive seconds
|
|
8468
8468
|
`,t;t.connTimeoutMs=Math.round(i*1e3),r=e.next;continue}if(i===`-H`||i===`--header`||i.startsWith(`--header=`)){let e=n(r,i===`-H`?`-H`:`--header`);if(!e)return t;t.customHeaders.push(e.value),r=e.next;continue}if(i.startsWith(`-`))return t.error=`websocat: unknown flag '${i}'\n`,t;if(t.url)return t.error=`websocat: extra positional argument '${i}' — advanced mode is not supported\n`,t;t.url=i}return t.closeReason!==void 0&&t.closeStatus===void 0&&(t.error=`websocat: --close-reason requires --close-status-code (the WebSocket close frame cannot carry a reason without a status code)
|
|
8469
|
-
`),t}function
|
|
8470
|
-
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function
|
|
8469
|
+
`),t}function iJ(e,t){if(!e)return[];let n=t?`\0`:`
|
|
8470
|
+
`,r=e.split(n);return r.length>0&&r[r.length-1]===``&&r.pop(),r}function aJ(e,t,n){let r=e.trim();if(!r)return e;let i=r.search(/\s/),a=i===-1?r:r.slice(0,i),o=i===-1?``:r.slice(i+1).trim(),s=[];if(o)try{s=JSON.parse(o)}catch{s=[o]}let c={id:t,method:a,params:s};return n||(c.jsonrpc=`2.0`),JSON.stringify(c)}function oJ(e){let t=``;for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return btoa(t)}function sJ(e){try{return new TextDecoder(`utf-8`,{fatal:!1}).decode(e)}catch{return oJ(e)}}async function cJ(e,t,n={}){let r=rJ(e);if(r.showHelp)return tJ();if(r.error)return{stdout:``,stderr:r.error,exitCode:2};if(!r.url)return{stdout:``,stderr:`websocat: missing ws:// or wss:// URL (use --help for usage)
|
|
8471
8471
|
`,exitCode:2};if(!/^wss?:\/\//i.test(r.url))return{stdout:``,stderr:`websocat: URL must start with ws:// or wss://, got '${r.url}'\n`,exitCode:2};let i=n.WebSocketCtor??(typeof WebSocket<`u`?WebSocket:void 0);if(!i)return{stdout:``,stderr:`websocat: no WebSocket implementation available in this runtime
|
|
8472
8472
|
`,exitCode:1};let a=[],o=e=>{r.quiet||a.push(`websocat: ${e}`)};r.verbose>=1&&(r.customHeaders.length>0&&o(`-H/--header is accepted for parity but browsers do not allow setting WebSocket request headers; only --protocol is honored`),r.pingInterval!==void 0&&o(`--ping-interval has no effect in browsers (no ping API exposed)`),r.insecure&&o(`-k/--insecure has no effect in browsers`));let s=[],c=r.nullTerminated?`\0`:`
|
|
8473
|
-
`,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?
|
|
8473
|
+
`,l;try{l=r.protocol?new i(r.url,r.protocol):new i(r.url)}catch(e){return{stdout:``,stderr:`websocat: connect failed: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}l.binaryType=`arraybuffer`;let u=0,d=1e4,f=0,p=!1,m,h,g=new Promise((e,t)=>{m=e,h=t}),_,v=!1,y=new Promise(e=>{_=t=>{v||(v=!0,e(t))}}),b=0,x=!1,S=setTimeout(()=>{x=!0;try{l.close()}catch{}p||h(Error(`connect timeout`))},r.connTimeoutMs);l.onopen=()=>{clearTimeout(S),p=!0,m()};let C=!1;l.onmessage=e=>{if(!C){if(!r.unidirectional){let t,n=!1;typeof e.data==`string`?t=new TextEncoder().encode(e.data):e.data instanceof ArrayBuffer?(t=new Uint8Array(e.data),n=!0):ArrayBuffer.isView(e.data)?(t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength),n=!0):t=new TextEncoder().encode(String(e.data)),t.length>r.bufferSize&&(o(`inbound message of ${t.length} bytes exceeds --buffer-size ${r.bufferSize}; truncating`),t=t.slice(0,r.bufferSize));let i=n&&r.base64?oJ(t):sJ(t);s.length<d?s.push(i):(f===0&&o(`output buffer reached ${d} messages; dropping further inbound messages — use -1, --max-messages, or pipe to a file with a different tool for long-running streams`),f+=1)}if(u+=1,r.maxMessages!==void 0&&u>=r.maxMessages){C=!0,T();return}r.oneMessage&&(C=!0,T())}},l.onerror=()=>{x||(o(`websocket error`),b=1,p||h(Error(`connect failed`)))},l.onclose=e=>{if(clearTimeout(S),x){_(124);return}r.verbose>=1&&o(`closed code=${e.code} reason=${JSON.stringify(e.reason||``)}`),b===0&&e.code!==1e3&&e.code!==1005&&e.code!==1001&&(b=1),p||h(Error(`connect closed (code ${e.code})`)),_(b)};function w(e,t){try{t===void 0?l.close(e):l.close(e,t)}catch{}}function T(){if(r.noClose){_(b);return}w(r.closeStatus??1e3,r.closeReason)}try{await g}catch(e){clearTimeout(S);let t=e instanceof Error?e.message:String(e);return{stdout:s.join(c)+(s.length?c:``),stderr:a.concat([`websocat: ${t}`]).join(`
|
|
8474
8474
|
`)+`
|
|
8475
|
-
`,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=
|
|
8475
|
+
`,exitCode:t===`connect timeout`?124:1}}if(r.unidirectionalReverse)!r.noClose&&r.exitOnEof&&!r.oneMessage&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0);else{let e=iJ(t.stdin,r.nullTerminated),n=1,i=0,a=r.oneMessage?e.slice(0,1):e;for(let e of a){let t=e;r.jsonrpc&&(t=aJ(e,n,r.jsonrpcOmit),n+=1),r.binary?l.send(new TextEncoder().encode(t).buffer):l.send(t),i+=1}!r.oneMessage&&!r.noClose&&(r.exitOnEof||i===0)&&setTimeout(()=>{w(r.closeStatus??1e3,r.closeReason)},0)}let E=await y;return f>0&&o(`dropped ${f} inbound message(s) due to output buffer cap`),{stdout:s.length?s.join(c)+c:``,stderr:a.length?a.join(`
|
|
8476
8476
|
`)+`
|
|
8477
|
-
`:``,exitCode:E}}function
|
|
8477
|
+
`:``,exitCode:E}}function lJ(){return G(`websocat`,async(e,t)=>cJ(e,{stdin:Pk(t.stdin)}))}function uJ(){return G(`__wf_progress`,async()=>({stdout:``,stderr:``,exitCode:0}))}async function dJ(e){return e.scriptCatalog?e.scriptCatalog.getJshCommands():e.fs?Dn(e.fs):new Map}async function fJ(e){return e.scriptCatalog?e.scriptCatalog.getWorkflowCommands():e.fs?On(e.fs):new Map}function pJ(e,t,n,r,i){if(r.has(e)){let r=[`/usr/bin/${e}`];return(t||n)&&r.push(` (shadowed by built-in ${e})`),{lines:r,found:!0}}if(t){let e=[t];return n&&e.push(` ${n.path} (workflow, shadowed by .jsh)`),{lines:e,found:!0}}return n?{lines:[`${n.path} (workflow)`],found:!0}:i.has(e)?{lines:[`/usr/bin/${e}`],found:!0}:{lines:[],found:!1}}function mJ(e={}){let t=e.scriptCatalog!==void 0||e.fs!==void 0?e:typeof e.walk==`function`&&typeof e.exists==`function`?{fs:e}:{};return G(`which`,async(e,n)=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:`which - locate a command
|
|
8478
8478
|
|
|
8479
8479
|
Usage: which <command> [command...]
|
|
8480
8480
|
|
|
@@ -8484,9 +8484,9 @@ Prints the path of the given command(s).
|
|
|
8484
8484
|
|
|
8485
8485
|
Exit code 0 if all commands found, 1 if any not found.
|
|
8486
8486
|
`,stderr:``,exitCode:0};if(e.length===0)return{stdout:``,stderr:`which: missing argument
|
|
8487
|
-
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await
|
|
8487
|
+
`,exitCode:1};let r=n.getRegisteredCommands?.()??[],i=new Set(r),a=await dJ(t),o=await fJ(t),s=typeof t.getStaticBuiltins==`function`?new Set(t.getStaticBuiltins()):i,c=[],l=!0;for(let t of e){let e=pJ(t,a.get(t),o.get(t),s,i);c.push(...e.lines),e.found||(l=!1)}return{stdout:c.length>0?c.join(`
|
|
8488
8488
|
`)+`
|
|
8489
|
-
`:``,stderr:``,exitCode:+!l}})}const
|
|
8489
|
+
`:``,stderr:``,exitCode:+!l}})}const hJ=n(`workflow-run-manager`),gJ=`__slicc_workflows`,_J=`/shared/workflow-runs`,vJ=1e3;function yJ(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){hJ.warn(`observeRun handler threw`,e)}},i=t=>t===void 0?`terminal`:t===e.getConeJid()?`cone`:`scoop`,a=(e,n)=>wJ(e,n,t,()=>r(n));async function o(o){let l=o.runId??e.makeRunId(),u=o.sentinel,d={id:l,name:o.name,source:o.source,origin:i(o.parentJid),status:`running`,currentPhase:null,agentsStarted:0,agentsDone:0,logs:[],startedAt:new Date().toISOString(),finishedAt:null,resultPath:null,preview:null,error:null,pid:null};t.set(l,d),SJ(t,n);let f=a(o.ctx,l),p=CJ(e.processManager,d,l,()=>r(l));return e.runRealm(o.code,[`workflow`,o.filename,l],f).then(e=>s(l,u,e)).catch(e=>c(l,e instanceof Error?e.message:String(e))).finally(()=>p()).catch(e=>hJ.warn(`workflow run lifecycle error`,e)),{runId:l}}async function s(t,n,r){let{result:i,hadResult:a}=e.splitResult(r.stdout,n);return r.exitCode===137?l(t,`killed`,null,r.stderr||`killed (SIGKILL)`):r.exitCode!==0||!a?l(t,`error`,null,r.stderr||(a?`exit ${r.exitCode}`:`script produced no result`)):l(t,`done`,i,null)}function c(e,t){return l(e,`error`,null,t)}async function l(n,i,a,o){let s=t.get(n);if(!s||s.status!==`running`&&s.status!==`paused`)return;let c=`${_J}/${n}.json`,l=new Date().toISOString();try{await e.sharedFs.mkdir(_J,{recursive:!0}),await e.sharedFs.writeFile(c,JSON.stringify({name:s.name,status:i,result:i===`done`?a:null,error:o,logs:s.logs,startedAt:s.startedAt,finishedAt:l},null,2)),s.resultPath=c}catch(e){let t=e instanceof Error?e.message:String(e);hJ.error(`failed to write run result file`,{runId:n,resultPath:c,error:t}),o=`result file write failed: ${t}`,i===`done`&&(i=`error`)}s.status=i,s.error=o,s.finishedAt=l,s.preview=i===`done`?xJ(a):o??``,r(n),u(s)}function u(t){t.origin===`cone`&&e.fireLick({type:`workflow`,workflowRunId:t.id,workflowName:t.name??void 0,resultPath:t.resultPath??void 0,preview:t.preview??t.error??void 0,timestamp:new Date().toISOString(),body:{runId:t.id,status:t.status,error:t.error}})}return{start:o,getRun:e=>t.get(e)??null,listRuns:()=>Array.from(t.values()),observeRun(e,r){let i=n.get(e);i||(i=new Set,n.set(e,i)),i.add(r);let a=t.get(e);if(a)try{r(a)}catch(e){hJ.warn(`observeRun handler threw on initial state`,e)}return()=>i.delete(r)}}}function bJ(e){let t=yJ(e);return globalThis[gJ]=t,hJ.info(`workflow run manager published on globalThis.__slicc_workflows`),t}function xJ(e){return((typeof e==`string`?e:JSON.stringify(e))??`null`).slice(0,200)}function SJ(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 CJ(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 wJ(e,t,n,r){let i=e.exec;if(!i)return e;let a=(async(e,a)=>e===`__wf_progress`?TJ(n,t,a?.args??[],r):e===`agent`?EJ(n,t,()=>i(e,a),r):i(e,a));return a.spawn=e.exec.spawn,{...e,exec:a}}function TJ(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>vJ&&i.logs.splice(0,i.logs.length-vJ),r()}return{stdout:``,stderr:``,exitCode:0}}async function EJ(e,t,n,r){let i=e.get(t);i&&i.status===`running`&&(i.agentsStarted++,r());try{return await n()}finally{let n=e.get(t);n&&n.status===`running`&&(n.agentsDone++,r())}}const DJ=String.raw`
|
|
8490
8490
|
class WorkflowError extends Error {}
|
|
8491
8491
|
class WorkflowDeterminismError extends WorkflowError {}
|
|
8492
8492
|
class WorkflowAgentCapError extends WorkflowError {}
|
|
@@ -8596,11 +8596,11 @@ function log(message) {
|
|
|
8596
8596
|
}
|
|
8597
8597
|
const budget = { total: (__WF.budget == null ? null : __WF.budget), spent() { return 0; }, remaining() { return this.total == null ? Infinity : Math.max(0, this.total - this.spent()); } };
|
|
8598
8598
|
function workflow() { throw new WorkflowNestingUnsupportedError('nested workflow() unsupported in SP1'); }
|
|
8599
|
-
`;function
|
|
8599
|
+
`;function OJ(){return`WF_RESULT_${globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`}`}function kJ(e){let t=NJ(e);return t===null?{name:null,description:null}:{name:PJ(t,`name`),description:PJ(t,`description`)}}function AJ(e){return e.replace(/\bexport\s+(const|let|var|function|async\s+function|class)\b/g,`$1`)}function jJ(e){return`const __emit = console.log.bind(console);
|
|
8600
8600
|
const __stringify = JSON.stringify.bind(JSON);
|
|
8601
|
-
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${
|
|
8601
|
+
const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (async () => {\n${AJ(e.body)}\n})();\n__emit(${JSON.stringify(e.sentinel)} + __stringify(__r ?? null));\n`}function MJ(e,t){let n=e.split(`
|
|
8602
8602
|
`);for(let e=n.length-1;e>=0;e--)if(n[e].startsWith(t)){let r=[...n.slice(0,e),...n.slice(e+1)].join(`
|
|
8603
|
-
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function
|
|
8603
|
+
`).replace(/\n+$/,``);try{return{result:JSON.parse(n[e].slice(t.length)),log:r,hadResult:!0}}catch{return{result:null,log:r,hadResult:!0}}}return{result:null,log:e.replace(/\n+$/,``),hadResult:!1}}function NJ(e){let t=/\bmeta\s*=\s*\{/.exec(e);if(!t)return null;let n=t.index+t[0].length-1,r=0;for(let t=n;t<e.length;t++)if(e[t]===`{`)r++;else if(e[t]===`}`&&--r===0)return e.slice(n+1,t);return null}function PJ(e,t){let n=RegExp(`\\b${t}\\s*:\\s*(['"\\\`])((?:\\\\.|(?!\\1).)*)\\1`).exec(e);return n?n[2]:null}const FJ=n(`workflow-command`);function IJ(){return globalThis[gJ]}function LJ(){let e=globalThis.navigator?.hardwareConcurrency??8;return Math.min(16,Math.max(8,e*4))}function RJ(e,t,n,r){let i=t[n];switch(i){case`-h`:case`--help`:return{i:n,help:!0};case`--script`:return e.script=t[++n],{i:n};case`--wait`:return e.wait=!0,{i:n};case`--args`:try{e.args=JSON.parse(t[++n]??``),e.hasArgs=!0}catch{return{i:n,error:`workflow: --args must be valid JSON`}}return{i:n};case`--budget`:{let r=Number(t[++n]);return Number.isFinite(r)?(e.budget=r,{i:n}):{i:n,error:`workflow: --budget must be a number`}}case`--concurrency`:{let i=Number(t[++n]);return Number.isFinite(i)?(e.cap=Math.min(r,Math.max(1,Math.trunc(i))),{i:n}):{i:n,error:`workflow: --concurrency must be a number`}}default:return i.startsWith(`-`)?{i:n,error:`workflow: unknown flag '${i}'`}:e.file===void 0?(e.file=i,{i:n}):{i:n,error:`workflow: too many arguments`}}}function zJ(e){if(e[0]!==`run`)return e.length===0||e.includes(`-h`)||e.includes(`--help`)?{help:!0}:{error:`workflow: unknown subcommand '${e[0]}' (only 'run' in SP1)`};let t=LJ(),n={budget:null,cap:Math.min(8,t)};for(let r=1;r<e.length;r++){let i=RJ(n,e,r,t);if(i.help)return{help:!0};if(i.error)return{error:i.error};r=i.i}return n.script===void 0&&n.file===void 0?{error:`workflow: a <file.js> or --script is required`}:n}function BJ(e={}){return G(`workflow`,async(t,n)=>{if(t[0]===`list`||t[0]===`status`||t[0]===`stop`)return KJ(t,n);if(t[0]===`save`)return GJ(t,n,e);let r=zJ(t);if(r.help)return{stdout:`usage: workflow run <file.js> [--args <json>] [--budget <n>] [--concurrency <n>] [--wait]
|
|
8604
8604
|
workflow run --script '<inline js>' [...]
|
|
8605
8605
|
workflow list
|
|
8606
8606
|
workflow status <runId>
|
|
@@ -8609,26 +8609,26 @@ const __WF = ${JSON.stringify(e.config)};\n${e.prelude}\nconst __r = await (asyn
|
|
|
8609
8609
|
Runs a Claude-Code-format dynamic workflow. Default is non-blocking (returns a run id);
|
|
8610
8610
|
pass --wait to block and print the full result.
|
|
8611
8611
|
`,stderr:``,exitCode:0};if(r.error)return{stdout:``,stderr:r.error+`
|
|
8612
|
-
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=
|
|
8613
|
-
`,exitCode:1};let s=
|
|
8614
|
-
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const
|
|
8615
|
-
`,exitCode:1};if(!
|
|
8612
|
+
`,exitCode:1};let i,a;if(r.script!==void 0)i=r.script,a=`<workflow>`;else{let e=n.fs.resolvePath(n.cwd,r.file);if(!await n.fs.exists(e))return{stdout:``,stderr:`workflow: file not found: ${r.file}\n`,exitCode:1};i=await n.fs.readFile(e),a=r.file}let o=kJ(i);if(!o.name)return{stdout:``,stderr:`workflow: script must define a meta block with a name (description optional)
|
|
8613
|
+
`,exitCode:1};let s=OJ().slice(10,22),c=`/shared/workflow-runs/${s}/scratch/`;await n.fs.mkdir(c,{recursive:!0});let l=OJ(),u=jJ({prelude:DJ,config:{...r.hasArgs?{args:r.args}:{},cap:r.cap??8,budget:r.budget??null,cwd:n.cwd,agentCwd:c},body:i,sentinel:l});return r.wait?VJ(u,a,l,o,n):HJ({code:u,source:i,name:o.name,filename:a,sentinel:l,runId:s,ctx:n,options:e})})}async function VJ(e,t,n,r,i){let a;try{a=await Lk(e,[`workflow`,t],i,void 0,{filename:t})}catch(e){return FJ.error(`workflow run failed`,e),{stdout:``,stderr:`workflow: ${e instanceof Error?e.message:String(e)}\n`,exitCode:1}}return qJ(r,a,n)}async function HJ(e){let t=IJ();if(!t)return{stdout:``,stderr:`workflow: run manager not available
|
|
8614
|
+
`,exitCode:1};let n=e.options.getParentJid?.(),{runId:r}=await t.start({code:e.code,source:e.source,name:e.name,filename:e.filename,parentJid:n,ctx:e.ctx,sentinel:e.sentinel,runId:e.runId});return{stdout:`▶ workflow '${e.name}' started (run ${r}). Watch: workflow status ${r}\n`,stderr:``,exitCode:0}}const UJ=/^[a-z0-9][a-z0-9-]*$/,WJ=`/workspace/.workflows`;async function GJ(e,t,n){let r=!1,i=[];for(let t of e.slice(1))t===`--force`?r=!0:i.push(t);let[a,o,...s]=i;if(!a||!o||s.length>0)return{stdout:``,stderr:`usage: workflow save <runId> <name> [--force]
|
|
8615
|
+
`,exitCode:1};if(!UJ.test(o))return{stdout:``,stderr:`workflow: invalid name '${o}' (use [a-z0-9][a-z0-9-]*)\n`,exitCode:1};let c=IJ()?.getRun(a);if(!c)return{stdout:``,stderr:`workflow: no run '${a}' (only backgrounded runs are saveable; --wait runs are not)\n`,exitCode:1};if(!c.source)return{stdout:``,stderr:`workflow: run '${a}' has no source to save\n`,exitCode:1};let l=`${WJ}/${o}.workflow.js`;if(await t.fs.exists(l)){if(!r)return{stdout:``,stderr:`workflow: ${l} already exists (pass --force to overwrite)\n`,exitCode:1}}else if(new Set(t.getRegisteredCommands?.()??[]).has(o))return{stdout:``,stderr:`workflow: '${o}' is already a command — choose another name\n`,exitCode:1};await t.fs.mkdir(WJ,{recursive:!0}),await t.fs.writeFile(l,c.source);try{await n.syncScriptCommands?.()}catch(e){FJ.warn(`workflow save: command re-sync failed; workflow saved, will register on next sync`,{name:o,error:e instanceof Error?e.message:String(e)})}return{stdout:`saved workflow '${o}' → ${l}\nrun it as '${o}' (or 'workflow run ${l}' if a built-in/.jsh shadows the name)\n`,stderr:``,exitCode:0}}async function KJ(e,t){let n=IJ();if(e[0]===`list`){if(!n)return{stdout:``,stderr:`workflow: run manager not available
|
|
8616
8616
|
`,exitCode:1};let e=n.listRuns().map(e=>`${e.id} ${e.status.padEnd(7)} ${e.agentsDone}/${e.agentsStarted} ${e.name??``}`);return{stdout:(e.length?e.join(`
|
|
8617
8617
|
`):`(no runs)`)+`
|
|
8618
8618
|
`,stderr:``,exitCode:0}}let r=e[1],i=n?.getRun(r??``);if(!i)return{stdout:``,stderr:`workflow: no run '${r}'\n`,exitCode:1};if(e[0]===`status`)return{stdout:[`run ${i.id} (${i.name??`unnamed`}) status=${i.status}`,`agents ${i.agentsDone}/${i.agentsStarted} phase=${i.currentPhase??`-`}`,i.resultPath?`result: ${i.resultPath}`:``,i.preview?`preview: ${i.preview}`:``,i.error?`error: ${i.error}`:``].filter(Boolean).join(`
|
|
8619
8619
|
`)+`
|
|
8620
|
-
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function
|
|
8620
|
+
`,stderr:``,exitCode:0};if(i.pid==null)return{stdout:`workflow: run ${i.id} has not started a realm process yet (nothing to stop)\n`,stderr:``,exitCode:0};if(i.status!==`running`&&i.status!==`paused`)return{stdout:`workflow: run ${i.id} already ${i.status}\n`,stderr:``,exitCode:0};let a=await t.exec?.(`kill`,{cwd:t.cwd,args:[`-KILL`,String(i.pid)]});return a&&a.exitCode!==0?{stdout:``,stderr:a.stderr||`workflow: kill failed (exit ${a.exitCode})\n`,exitCode:a.exitCode}:{stdout:`stopped run ${i.id} (pid ${i.pid})\n`,stderr:``,exitCode:0}}function qJ(e,t,n){let{result:r,log:i,hadResult:a}=MJ(t.stdout,n),o=e.name?`workflow: ${e.name}${e.description?` — `+e.description:``}\n`:``,s=i?JJ(i)+`
|
|
8621
8621
|
`:``;return t.exitCode!==0||!a?{stdout:o+s,stderr:t.stderr||(a?``:`workflow: script produced no result
|
|
8622
8622
|
`),exitCode:t.exitCode||1}:{stdout:o+s+(typeof r==`string`?r:JSON.stringify(r))+`
|
|
8623
|
-
`,stderr:t.stderr,exitCode:0}}function
|
|
8623
|
+
`,stderr:t.stderr,exitCode:0}}function JJ(e){return e.split(`
|
|
8624
8624
|
`).map(e=>e.replace(/^WFPHASE/,`▸ `).replace(/^WFLOG/,`· `)).join(`
|
|
8625
|
-
`)}function
|
|
8625
|
+
`)}function YJ(e){return{stdout:``,stderr:`xxd: ${e}\n`,exitCode:1}}function XJ(e){if(e==null)throw Error(`missing option value`);let t=e.startsWith(`-`),n=t||e.startsWith(`+`)?e.slice(1):e,r;if(/^0x[0-9a-fA-F]+$/.test(n))r=parseInt(n.slice(2),16);else if(/^[0-9]+$/.test(n))r=parseInt(n,10);else throw Error(`invalid number: ${e}`);return t?-r:r}function ZJ(e,t){let n=e.toString(16).padStart(2,`0`);return t?n.toUpperCase():n}function QJ(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}function $J(e){return e.replace(/[^0-9a-zA-Z]/g,`_`)}function eY(e,t,n,r,i){let a=[];for(let o=0;o<e.length;o+=t){let s=Math.min(o+t,e.length),c=(i+o).toString(16).padStart(8,`0`),l=``;for(let i=0;i<t;i++)n>0&&i>0&&i%n===0&&(l+=` `),l+=o+i<s?ZJ(e[o+i],r):` `;let u=``;for(let t=o;t<s;t++)u+=e[t]>=32&&e[t]<=126?String.fromCharCode(e[t]):`.`;a.push(`${c}: ${l} ${u}`)}return a.length?a.join(`
|
|
8626
8626
|
`)+`
|
|
8627
|
-
`:``}function
|
|
8628
|
-
`}return r}function
|
|
8627
|
+
`:``}function tY(e,t,n){let r=``;for(let i=0;i<e.length;i+=t){let a=``;for(let r=0;r<t&&i+r<e.length;r++)a+=ZJ(e[i+r],n);r+=a+`
|
|
8628
|
+
`}return r}function nY(e,t,n,r){let i=Array.from(e,e=>`0x${ZJ(e,n)}`),a=[];for(let e=0;e<i.length;e+=t)a.push(` `+i.slice(e,e+t).join(`, `));let o=a.join(`,
|
|
8629
8629
|
`);return r===null?i.length?o+`
|
|
8630
|
-
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function
|
|
8631
|
-
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const
|
|
8630
|
+
`:``:`unsigned char ${r}[] = {\n${o}\n};\nunsigned int ${r}_len = ${e.length};\n`}function rY(e){let t=e.replace(/[^0-9a-fA-F]/g,``),n=Math.floor(t.length/2),r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=parseInt(t.substr(e*2,2),16);return r}function iY(e){let t=[],n=0;for(let r of e.split(`
|
|
8631
|
+
`)){let e=r.replace(/\r$/,``),i=e.indexOf(`:`);if(i<0)continue;let a=parseInt(e.slice(0,i).trim(),16);if(Number.isNaN(a))continue;let o=e.slice(i+1),s=o.indexOf(` `);s>=0&&(o=o.slice(0,s));let c=o.replace(/[^0-9a-fA-F]/g,``),l=[];for(let e=0;e+1<c.length;e+=2)l.push(parseInt(c.substr(e,2),16));l.length&&(t.push({offset:a,bytes:l}),n=Math.max(n,a+l.length))}if(!t.length)return new Uint8Array;let r=new Uint8Array(n);for(let e of t)for(let t=0;t<e.bytes.length;t++)r[e.offset+t]=e.bytes[t];return r}const aY={"-u":`upper`,"-p":`plain`,"-ps":`plain`,"-postscript":`plain`,"-i":`include`,"-include":`include`,"-r":`revert`,"-revert":`revert`},oY=[{key:`cols`,exact:[`-c`,`-cols`],attached:/^-c(0x)?[0-9]/},{key:`group`,exact:[`-g`,`-groupsize`],attached:/^-g(0x)?[0-9]/},{key:`length`,exact:[`-l`,`-len`],attached:/^-l(0x)?[0-9]/},{key:`seek`,exact:[`-s`,`-seek`],attached:/^-s[+-]?(0x)?[0-9]/}];function sY(e){let t={upper:!1,plain:!1,include:!1,revert:!1,positional:[]};for(let n=0;n<e.length;n++){let r=e[n],i=aY[r];if(i){t[i]=!0;continue}let a=oY.find(e=>e.exact.includes(r)||e.attached.test(r));if(a){t[a.key]=XJ(a.exact.includes(r)?e[++n]:r.slice(2));continue}if(r!==`-`&&r.startsWith(`-`)&&r.length>1)throw Error(`invalid option ${r}`);t.positional.push(r)}return t}function cY(e){return e.includes(`-h`)||e.includes(`--help`)||e.includes(`-help`)}async function lY(e,t,n){if(!n&&t)return e.fs.readFileBuffer(e.fs.resolvePath(e.cwd,t));let r=Fk(e.stdin),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e)&255;return i}function uY(e,t,n,r,i){let a=e.cols&&e.cols>0?e.cols:e.plain?30:e.include?12:16;return e.plain?tY(t,a,e.upper):e.include?nY(t,a,e.upper,i?null:$J(r??``)):eY(t,a,e.group!=null&&e.group>=0?e.group:2,e.upper,n)}function dY(e,t){let n=0,r=t;return e.seek!==void 0&&(n=e.seek<0?Math.max(0,r.length+e.seek):Math.min(e.seek,r.length),r=r.subarray(n)),e.length!==void 0&&(r=r.subarray(0,Math.max(0,e.length))),{data:r,base:n}}function fY(){return G(`xxd`,async(e,t)=>{if(cY(e))return{stdout:`usage: xxd [options] [infile [outfile]]
|
|
8632
8632
|
-c cols number of octets per line (default 16; 30 for -p; 12 for -i)
|
|
8633
8633
|
-g bytes number of octets per group (default 2; 0 disables grouping)
|
|
8634
8634
|
-l len stop after len octets
|
|
@@ -8638,11 +8638,11 @@ pass --wait to block and print the full result.
|
|
|
8638
8638
|
-i output in C include style
|
|
8639
8639
|
-r reverse: convert a hex dump back to binary (-r -p for plain)
|
|
8640
8640
|
-h show this help
|
|
8641
|
-
`,stderr:``,exitCode:0};let n;try{n=
|
|
8642
|
-
`,stderr:``,exitCode:0}}function
|
|
8643
|
-
`,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(/^\.\//,``))||mn(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await
|
|
8644
|
-
`,exitCode:1};let c=It(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function QJ(e={}){let t=[Zz({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),yM(),wG(e.browserAPI,e.fs),eU(e.browserAPI),NB(e),ZJ(),ZK(),oK(),JJ(),WG(`sqlite3`),WG(`sqllite`),SK(),BK(),SP(),oM(),_H({buildProcessConfig:e.buildProcessConfig}),LU(`python3`,{buildProcessConfig:e.buildProcessConfig}),LU(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[BB(`ipk`,{fs:e.fs,fetch:e.fetch}),BB(`npm`,{fs:e.fs,fetch:e.fetch}),BB(`i`,{fs:e.fs,fetch:e.fetch}),rV(`ipx`,{fs:e.fs,fetch:e.fetch}),rV(`npx`,{fs:e.fs,fetch:e.fetch}),JN(`di`,{fs:e.fs,fetch:e.fetch}),JN(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[iB({fetch:e.fetch})]:[],sI(),Iq(),Gq(),dN(),CV({fs:e.fs,scriptCatalog:e.scriptCatalog}),CI(),HG(),lU(`pdftk`),lU(`pdf`),tN(`convert`),tN(`magick`),Xq({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),HK(),YK(),_V(),eP(),TH(),CH(),mV(),rG({setEnv:e.setEnv}),$U({fs:e.fs}),EW(),VM(),HM(),UM(`xclip`),UM(`xsel`),xW(),LI(),uj(),dj(),mH(e.fs),mt(),bH(),kj({getParentJid:e.getParentJid}),sP(),pU({processManager:e.processManager}),aV({processManager:e.processManager}),Cq(),jB(),rF(),mF(),PM({registry:e.cherryRuntimeRegistry}),vN(),TN({fs:e.fs}),EN({fs:e.fs}),GG(e.sudoCommand),SJ({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),Kq()];return e.fs&&t.push(...RI.map(t=>Jz(t,e.browserAPI,e.fs))),t}const $J=Reflect.get(pt,`DefenseInDepthBox`);var eY=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=$J?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=rt(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=rt(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=rt(e);if(typeof t==`string`){let e=i(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=rt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new L(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof L&&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 L&&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=rt(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=rt(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=rt(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(rt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=rt(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=rt(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(rt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=rt(e),i=rt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new L(`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=it(e,r.name),i=it(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(rt(e),rt(t))})}resolvePath(e,t){return t.startsWith(`/`)?rt(t):rt(it(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,rt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(rt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(rt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function tY(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?tY(e.getUnderlyingFS?.()):null}var nY=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new eY(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new l_({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new is({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=tY(i)??tY(a);this.scriptCatalog=t.scriptCatalog??new An({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=l(),u=QJ({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),d=[s,this.createMountCustomCommand(),IA(t.fs),rj(t.fs,c,t.browserAPI),...u].filter(e=>this.isCommandAllowed(e.name)),f=[..._t(),...ft()],p=this.allowedCommands?f.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new ht({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:p,customCommands:d}),this.allowedCommands!==null){let e=this.bash;for(let t of ft())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let m=d.map(e=>e.name),h=p??[..._t(),...ft()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return vk(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){Hr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await Tk(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=Dt(e);if(!n)return;let r=`${vt}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
|
|
8645
|
-
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return
|
|
8641
|
+
`,stderr:``,exitCode:0};let n;try{n=sY(e)}catch(e){return YJ(e.message)}let r=n.positional[0],i=n.positional[1],a=!r||r===`-`,o;try{o=await lY(t,r,a)}catch{return YJ(`${r}: No such file or directory`)}if(n.revert){let e=QJ(o),r=n.plain?rY(e):iY(e);return i?(await t.fs.writeFile(t.fs.resolvePath(t.cwd,i),r),{stdout:``,stderr:``,exitCode:0}):{stdout:QJ(r),stderr:``,exitCode:0}}let{data:s,base:c}=dY(n,o),l=uY(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 pY(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=pn(t,o),s=n?`${n}/${o}`:o;a+=await pY(e,i,s,r)}return a}function mY(){return{stdout:`usage: zip [-r] <archive.zip> <path> [path...]
|
|
8642
|
+
`,stderr:``,exitCode:0}}function hY(){return G(`zip`,async(e,t)=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return mY();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
|
|
8643
|
+
`,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(/^\.\//,``))||mn(r);if(i.isDirectory&&!n)return{stdout:``,stderr:`zip: ${e} is a directory (use -r)\n`,exitCode:1};s+=await pY(t,r,a,o)}if(s===0)return{stdout:``,stderr:`zip: nothing to do
|
|
8644
|
+
`,exitCode:1};let c=It(o);return await t.fs.writeFile(i,c),{stdout:`created ${i} (${s} file(s))\n`,stderr:``,exitCode:0}})}function gY(e={}){let t=[hB({getJshCommands:e.getJshCommands,getWorkflowCommands:e.getWorkflowCommands}),LM(),HG(e.browserAPI,e.fs),vU(e.browserAPI),ZB(e),hY(),hq(),wK(),fY(),cK(`sqlite3`),cK(`sqllite`),BK(),iq(),BP(),wM(),FH({buildProcessConfig:e.buildProcessConfig}),tW(`python3`,{buildProcessConfig:e.buildProcessConfig}),tW(`python`,{buildProcessConfig:e.buildProcessConfig}),...e.fs&&e.fetch?[iV(`ipk`,{fs:e.fs,fetch:e.fetch}),iV(`npm`,{fs:e.fs,fetch:e.fetch}),iV(`i`,{fs:e.fs,fetch:e.fetch}),xV(`ipx`,{fs:e.fs,fetch:e.fetch}),xV(`npx`,{fs:e.fs,fetch:e.fetch}),fP(`di`,{fs:e.fs,fetch:e.fetch}),fP(`uv`,{fs:e.fs,fetch:e.fetch})]:[],...e.fetch?[SB({fetch:e.fetch})]:[],TI(),eJ(),lJ(),kN(),VV({fs:e.fs,scriptCatalog:e.scriptCatalog}),VI(),oK(),DU(`pdftk`),DU(`pdf`),yN(`convert`),yN(`magick`),mJ({fs:e.fs,scriptCatalog:e.scriptCatalog,getStaticBuiltins:e.getStaticBuiltins}),oq(),pq(),FV(),vP(),UH(),VH(),MV(),xG({setEnv:e.setEnv}),_W({fs:e.fs}),WW(),aN(),oN(),sN(`xclip`),sN(`xsel`),zW(),tL(),Oj(),kj(),MH(e.fs),mt(),RH(),qj({getParentJid:e.getParentJid}),TP(),jU({processManager:e.processManager}),CV({processManager:e.processManager}),Vq(),YB(),xF(),MF(),QM({registry:e.cherryRuntimeRegistry}),IN(),UN({fs:e.fs}),WN({fs:e.fs}),lK(e.sudoCommand),BJ({getParentJid:e.getParentJid,syncScriptCommands:e.syncScriptCommands}),uJ()];return e.fs&&t.push(...nL.map(t=>fB(t,e.browserAPI,e.fs))),t}const _Y=Reflect.get(pt,`DefenseInDepthBox`);var vY=class{vfs;registeredCommandsFn=null;constructor(e){this.vfs=e}setRegisteredCommandsFn(e){this.registeredCommandsFn=e}getVirtualBinCommands(){return this.registeredCommandsFn?.()??[]}canWrite(e){let t=this.vfs;return typeof t.canWrite!=`function`||t.canWrite(e)}listMountPoints(){let e=this.vfs;return typeof e.listMountPoints==`function`?e.listMountPoints():[]}trusted(e){let t=_Y?.runTrustedAsync;return t?t(e):Promise.resolve().then(e)}async readFile(e,t){return this.trusted(async()=>{let t=rt(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=rt(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=rt(e);if(typeof t==`string`){let e=i(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=rt(e);try{if((await this.vfs.stat(n)).type===`directory`)throw new L(`EISDIR`,`is a directory`,n)}catch(e){if(e instanceof L&&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 L&&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=rt(e);if(t===`/usr`||t===`/usr/bin`)return!0;if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);return e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e)}return this.vfs.exists(t)})}async stat(e){return this.trusted(async()=>{let t=rt(e);if(t===`/usr`||t===`/usr/bin`)return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)};if(t.startsWith(`/usr/bin/`)){let e=t.slice(9);if(e.length>0&&!e.includes(`/`)&&this.getVirtualBinCommands().includes(e))return{isFile:!0,isDirectory:!1,isSymbolicLink:!1,mode:493,size:0,mtime:new Date(0)}}let n=this.vfs.statSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!!n.isSymlink,mode:n.type===`directory`?493:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.stat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:!!r.isSymlink,mode:r.type===`directory`?493:420,size:r.size,mtime:new Date(r.mtime)}})}async lstat(e){return this.trusted(async()=>{let t=rt(e),n=this.vfs.lstatSync(t);if(n)return{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`,mode:n.type===`directory`?493:n.type===`symlink`?511:420,size:n.size,mtime:new Date(n.mtime)};let r=await this.vfs.lstat(t);return{isFile:r.type===`file`,isDirectory:r.type===`directory`,isSymbolicLink:r.type===`symlink`,mode:r.type===`directory`?493:r.type===`symlink`?511:420,size:r.size,mtime:new Date(r.mtime)}})}async mkdir(e,t){return this.trusted(async()=>{await this.vfs.mkdir(rt(e),t)})}async readdir(e){return this.trusted(async()=>{let t=rt(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=rt(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(rt(e),t)})}async cp(e,t,n){return this.trusted(async()=>{let r=rt(e),i=rt(t);if((await this.vfs.stat(r)).type===`directory`){if(!n?.recursive)throw new L(`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=it(e,r.name),i=it(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(rt(e),rt(t))})}resolvePath(e,t){return t.startsWith(`/`)?rt(t):rt(it(e,t))}getAllPaths(){return[]}async chmod(e,t){}async symlink(e,t){return this.trusted(async()=>{await this.vfs.symlink(e,rt(t))})}async link(e,t){throw Error(`Hard links not supported in VirtualFS`)}async readlink(e){return this.trusted(async()=>this.vfs.readlink(rt(e)))}async realpath(e){return this.trusted(async()=>this.vfs.realpath(rt(e)))}async utimes(e,t,n){}invalidatePaths(e){let t=this.vfs;t.invalidatePaths&&t.invalidatePaths(e)}};function yY(e){return e&&typeof e.getWatcher==`function`?e.getWatcher?.()??null:e&&typeof e.getUnderlyingFS==`function`?yY(e.getUnderlyingFS?.()):null}var bY=class e{options;bash;vfsAdapter;gitCommands;mountCommands;lastEnv;cwd;builtinCommandNames;staticBuiltinNames;allowedCommands;scriptCatalog;ownsScriptCatalog;registeredJshCommands=new Map;registeredWorkflowCommands=new Set;jshSyncInflight=null;jshSyncDirty=!1;pendingCommandGrants=[];pendingSudoBypasses=new Map;pendingEnvWrites=new Map;activeShellPid;resolveJshProcessConfig=()=>this.buildJshProcessConfig();static buildAllowedCommandSet(e){return e.sudo?.defaultDisposition===`require-approval`||!e.allowedCommands||e.allowedCommands.includes(`*`)?null:new Set(e.allowedCommands)}constructor(t){this.options=t,this.vfsAdapter=new vY(t.fs),this.allowedCommands=e.buildAllowedCommandSet(t);let n=t.cwd??`/`,r={HOME:`/`,PATH:`/usr/bin`,USER:`user`,SHELL:`/bin/bash`,PWD:n,...t.env};this.gitCommands=new l_({fs:t.fs,authorName:r.GIT_AUTHOR_NAME??`User`,authorEmail:r.GIT_AUTHOR_EMAIL??`user@example.com`}),this.mountCommands=new is({fs:t.fs,isScoop:t.isScoop});let i=t.jshDiscoveryFs??t.fs,a=t.bshDiscoveryFs??t.fs,o=yY(i)??yY(a);this.scriptCatalog=t.scriptCatalog??new An({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=l(),u=gY({onMediaPreview:async e=>this.renderMediaPreview(e),getJshCommands:()=>this.getJshCommandNames(),getWorkflowCommands:()=>this.getWorkflowCommandNames(),syncScriptCommands:()=>this.syncJshCommands(),getStaticBuiltins:()=>[...this.staticBuiltinNames],fs:t.fs,fetch:c,scriptCatalog:this.scriptCatalog,browserAPI:t.browserAPI,getParentJid:t.getParentJid,buildProcessConfig:this.resolveJshProcessConfig,processManager:t.processManager,sudoCommand:t.sudo?{broker:t.sudo.broker,persistGrant:async e=>{this.pendingCommandGrants.push(e)},suppressNextGate:e=>this.registerSudoBypass(e)}:void 0,setEnv:(e,t)=>{this.pendingEnvWrites.set(e,t),this.lastEnv[e]=t}}),d=[s,this.createMountCustomCommand(),ej(t.fs),xj(t.fs,c,t.browserAPI),...u].filter(e=>this.isCommandAllowed(e.name)),f=[..._t(),...ft()],p=this.allowedCommands?f.filter(e=>this.isCommandAllowed(e)):void 0;if(this.bash=new ht({fs:this.vfsAdapter,cwd:n,env:r,fetch:c,commands:p,customCommands:d}),this.allowedCommands!==null){let e=this.bash;for(let t of ft())this.isCommandAllowed(t)||e.commands.delete(t)}if(this.isTransparentGatingEnabled()){let e=this.bash;for(let[t,n]of e.commands)e.commands.set(t,this.wrapCommandForSudo(n))}let m=d.map(e=>e.name),h=p??[..._t(),...ft()];this.builtinCommandNames=new Set([...h,...m]),this.staticBuiltinNames=new Set(this.builtinCommandNames),this.vfsAdapter.setRegisteredCommandsFn(()=>[...this.builtinCommandNames]),this.lastEnv={...r},this.cwd=n,this.syncJshCommands().catch(()=>void 0)}getBash(){return this.bash}getCwd(){return this.cwd}getScriptCatalog(){return this.scriptCatalog}getEnv(){return{...this.lastEnv}}async getJshCommandNames(){return[...(await this.getFilteredJshCommands()).keys()]}async syncJshCommands(){return this.jshSyncInflight?(this.jshSyncDirty=!0,this.jshSyncInflight):(this.jshSyncInflight=this.doSyncJshCommands(),this.jshSyncInflight)}async executeCommand(e,t,n){let r=this.activeShellPid;n!==void 0&&(this.activeShellPid=n);try{let n=await this.runCommand(e,t);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}finally{this.activeShellPid=r}}async executeScriptFile(e,t=[]){return Ik(e,t,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig())}dispose(){this.ownsScriptCatalog&&this.scriptCatalog.dispose()}async renderMediaPreview(e){throw Error(`terminal preview is unavailable in headless mode`)}async runCommand(e,t){Hr(e.trim().split(/\s+/)[0]||`unknown`);let n={env:this.lastEnv,cwd:this.cwd,signal:t},r=await this.bash.exec(e,n);if(await this.flushPendingCommandGrants(),r.env&&(this.lastEnv={...r.env}),this.pendingEnvWrites.size>0){for(let[e,t]of this.pendingEnvWrites)this.lastEnv[e]=t;this.pendingEnvWrites.clear()}if(r.env?.PWD&&(this.cwd=r.env.PWD),r.exitCode===127){let t=await this.tryJshFallback(e);if(t)return this.syncJshCommands().catch(()=>void 0),t}return r}isTransparentGatingEnabled(){let e=this.options.sudo;return!!e&&e.transparentGating!==!1}wrapCommandForSudo(e){if(!this.isTransparentGatingEnabled())return e;let t=t=>this.gateCommandDispatch(e.name,t);return{name:e.name,trusted:e.trusted,async execute(n,r){return await t(n)||e.execute(n,r)}}}async gateCommandDispatch(e,t){let n=this.options.sudo;if(!n)return null;let r=`${e} ${t.join(` `)}`.trim();if(this.consumeSudoBypass(r))return null;let i=n.getPolicy();if(!i)return null;let a=await Uk(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=Dt(e);if(!n)return;let r=`${vt}/granted`,i=this.options.fs,a=``;try{await i.exists(r)&&(a=await i.readFile(r))}catch{a=``}let o=a&&!a.endsWith(`
|
|
8645
|
+
`)?`${a}\n`:a;await i.writeFile(r,`${o}NOPASSWD Cmnd ${n}\n`)}isCommandAllowed(e){return this.allowedCommands===null||this.allowedCommands.has(e)}async doSyncJshCommands(){try{let e=await this.scriptCatalog.getJshCommands(),t=await this.getFilteredWorkflowCommands();for(let[t,n]of e)this.isCommandAllowed(t)&&(this.builtinCommandNames.has(t)&&!this.registeredJshCommands.has(t)||this.registeredJshCommands.get(t)!==n&&(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(t))),this.registeredJshCommands.set(t,n),this.builtinCommandNames.add(t)));for(let e of t.keys())if(!this.registeredWorkflowCommands.has(e)){if(this.registeredJshCommands.has(e)){this.registeredWorkflowCommands.add(e);continue}this.builtinCommandNames.has(e)||(this.bash.registerCommand(this.wrapCommandForSudo(this.makeScriptCommand(e))),this.registeredWorkflowCommands.add(e),this.builtinCommandNames.add(e))}}finally{this.jshSyncInflight=null,this.jshSyncDirty&&(this.jshSyncDirty=!1,this.syncJshCommands().catch(()=>void 0))}}makeScriptCommand(e){let t=this.scriptCatalog,n=this,r=this.options.jshDiscoveryFs??this.options.fs,i=e;return{name:e,trusted:!0,async execute(e,a){let o=a.exec??((e,t)=>n.bash.exec(e,{env:Object.fromEntries(a.env),cwd:t?.cwd??a.cwd,args:t?.args})),s=(await t.getJshCommands()).get(i);if(s){let t;try{let e=await r.readFile(s,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${s}'\n`,exitCode:127}}return Lk(t,[`node`,s,...e],{fs:a.fs,cwd:a.cwd,env:a.env,stdin:a.stdin,exec:o},n.buildJshProcessConfig())}let c=(await t.getWorkflowCommands()).get(i);if(c){let t=kn(c.path,e);return o(t[0],{args:t.slice(1),cwd:a.cwd})}return{stdout:``,stderr:`${i}: command no longer exists\n`,exitCode:127}}}}createGitCustomCommand(){let e=this.gitCommands;return G(`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 G(`mount`,async(t,n)=>{let r=n.cwd,i=await e.execute(t,r,n.env);return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode}})}async getFilteredJshCommands(){let e=await this.scriptCatalog.getJshCommands(),t=new Map;for(let[n,r]of e)this.builtinCommandNames.has(n)||this.isCommandAllowed(n)&&t.set(n,r);return t}async getFilteredWorkflowCommands(){let e=await this.scriptCatalog.getWorkflowCommands(),t=new Map;for(let[n,r]of e)this.isCommandAllowed(n)&&t.set(n,r);return t}async getWorkflowCommandNames(){return[...(await this.getFilteredWorkflowCommands()).keys()]}async tryJshFallback(e){let t=e.trim(),n=t.indexOf(` `),r=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1).trim():``,a=(await this.getFilteredJshCommands()).get(r);if(!a)return null;let o=i?Hk(i):[],s=this.options.jshDiscoveryFs??this.options.fs,c;try{let e=await s.readFile(a,{encoding:`utf-8`});c=typeof e==`string`?e:new TextDecoder().decode(e)}catch{return{stdout:``,stderr:`jsh: cannot read script '${a}'\n`,exitCode:127,env:this.lastEnv}}let l=[`node`,a,...o],u=await Lk(c,l,{fs:this.vfsAdapter,cwd:this.cwd,env:new Map(Object.entries(this.lastEnv)),stdin:``,exec:(e,t)=>this.bash.exec(e,{env:this.lastEnv,cwd:t?.cwd??this.cwd})},this.buildJshProcessConfig());return{stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode,env:this.lastEnv}}buildJshProcessConfig(){if(!(!this.options.processManager||!this.options.processOwner))return{processManager:this.options.processManager,owner:this.options.processOwner,getParentPid:()=>this.activeShellPid??this.options.getCurrentShellPid?.()}}};function xY(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}var SY=class extends bY{terminal=null;fitAddon=null;terminalHost=null;previewHost=null;previewUrls=[];previewStateListener=null;hasPreview=!1;resizeObserver=null;themeObserver=null;currentLine=``;cursorPos=0;history=[];historyIndex=-1;isExecuting=!1;execAbort=null;continuationBuffer=``;constructor(e){super(e)}async runCommand(e,t){return super.runCommand(e,t??this.execAbort?.signal)}async mount(e){let t=e??this.options.container;if(!t)throw Error(`No container element provided`);let{Terminal:n}=await import(`./xterm-DX7Hb5S-.js`),{FitAddon:r}=await import(`./addon-fit-Crogpbda.js`);await Promise.resolve({ });let i=!document.documentElement.classList.contains(`theme-light`),a={background:`#141414`,foreground:`#cfcfcf`,cursor:`#3562ff`,cursorAccent:`#141414`,selectionBackground:`#3562ff40`,selectionForeground:`#ffffff`,black:`#1a1a1a`,red:`#e34850`,green:`#2d9d78`,yellow:`#e68619`,blue:`#3562ff`,magenta:`#a962e8`,cyan:`#2db9be`,white:`#cfcfcf`,brightBlack:`#5a5a5a`,brightRed:`#e34850`,brightGreen:`#2d9d78`,brightYellow:`#e68619`,brightBlue:`#4a75ff`,brightMagenta:`#a962e8`,brightCyan:`#2db9be`,brightWhite:`#ffffff`},o={background:`#f0f0f0`,foreground:`#1a1a1a`,cursor:`#2b54db`,cursorAccent:`#f0f0f0`,selectionBackground:`#2b54db30`,selectionForeground:`#000000`,black:`#1a1a1a`,red:`#d73220`,green:`#268e6c`,yellow:`#d17a00`,blue:`#2b54db`,magenta:`#8839ef`,cyan:`#1a9088`,white:`#e8e8e8`,brightBlack:`#6e6e6e`,brightRed:`#d73220`,brightGreen:`#268e6c`,brightYellow:`#d17a00`,brightBlue:`#1e44c4`,brightMagenta:`#8839ef`,brightCyan:`#1a9088`,brightWhite:`#ffffff`};this.terminal=new n({cursorBlink:!0,fontSize:11,fontFamily:`'Source Code Pro', 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace`,theme:i?a:o,convertEol:!0}),this.themeObserver?.disconnect(),this.themeObserver=new MutationObserver(()=>{if(!this.terminal)return;let e=document.documentElement.classList.contains(`theme-light`);this.terminal.options.theme=e?o:a}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),this.fitAddon=new r,this.terminal.loadAddon(this.fitAddon),t.replaceChildren(),this.terminalHost=document.createElement(`div`),this.terminalHost.className=`terminal-panel__terminal-host`,t.appendChild(this.terminalHost),this.previewHost=document.createElement(`div`),this.previewHost.className=`terminal-panel__preview`,t.appendChild(this.previewHost),this.terminal.open(this.terminalHost),this.fitAddon.fit(),this.resizeObserver?.disconnect(),this.resizeObserver=new ResizeObserver(()=>this.refit()),this.resizeObserver.observe(this.terminalHost),this.terminal.writeln(`\x1B[1mslicc\x1B[0m \x1B[90mshell (powered by just-bash)\x1B[0m`),this.terminal.writeln(`\x1B[90mType "help" for available commands.\x1B[0m
|
|
8646
8646
|
`),this.showPrompt(),this.setupInputHandler()}refit(){this.fitAddon?.fit()}setPreviewStateListener(e){this.previewStateListener=e,this.previewStateListener?.(this.hasPreview)}async executeCommandInTerminal(e){let t=e.trim();if(!t)return{stdout:``,stderr:``,exitCode:0};if(!this.terminal)return this.executeCommand(t);if(this.isExecuting||this.currentLine.length>0||this.continuationBuffer.length>0)return{stdout:``,stderr:`terminal is busy; finish current input first
|
|
8647
8647
|
`,exitCode:1};this.history[this.history.length-1]!==t&&this.history.push(t),this.historyIndex=-1,this.terminal.write(t),this.terminal.writeln(``),this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(t),n=this.execAbort.signal.aborted;return this.execAbort=null,n?{stdout:``,stderr:``,exitCode:130}:(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0),{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode})}catch(e){if(this.execAbort?.signal.aborted)return this.execAbort=null,{stdout:``,stderr:``,exitCode:130};this.execAbort=null;let t=`Error: ${e instanceof Error?e.message:String(e)}\n`;return this.writeToTerminal(t,!0),{stdout:``,stderr:t,exitCode:1}}finally{this.isExecuting=!1,this.showPrompt()}}clearTerminal(){this.terminal?.clear(),this.clearMediaPreview()}dispose(){this.themeObserver?.disconnect(),this.themeObserver=null,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.clearMediaPreview(),this.terminal?.dispose(),this.terminal=null,this.fitAddon=null,this.terminalHost=null,this.previewHost=null,super.dispose()}showPrompt(){if(!this.terminal)return;let e=this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd;this.terminal.write(`\x1b[34m${e}\x1b[0m \x1b[90m$\x1b[0m `)}setupInputHandler(){this.terminal&&this.terminal.onData(e=>{if(this.isExecuting){(e===``||e.length===1&&e.charCodeAt(0)===3)&&(this.execAbort?.abort(),this.terminal?.writeln(`^C`));return}if(e.startsWith(`\x1B[`)||e.startsWith(`\x1BO`)){switch(e){case`\x1B[A`:this.handleHistoryUp();return;case`\x1B[B`:this.handleHistoryDown();return;case`\x1B[C`:this.handleArrowRight();return;case`\x1B[D`:this.handleArrowLeft();return;case`\x1B[H`:case`\x1BOH`:case`\x1B[1~`:this.handleHome();return;case`\x1B[F`:case`\x1BOF`:case`\x1B[4~`:this.handleEnd();return;case`\x1B[3~`:this.handleDelete();return}return}for(let t of e)switch(t){case`\r`:this.handleEnter();break;case``:this.handleBackspace();break;case``:this.handleCtrlC();break;case` `:this.handleTab();break;default:t>=` `&&this.insertChar(t)}})}getPromptWidth(){return(this.cwd===`/`?`/`:this.cwd.split(`/`).pop()??this.cwd).length+3}getCursorVisualLine(){let e=0;for(let[t,n]of this.currentLine.split(`
|
|
8648
8648
|
`).entries()){if(e+n.length>=this.cursorPos)return t;e+=n.length+1}return 0}positionTerminalCursor(){let e=this.currentLine.split(`
|
|
@@ -8657,15 +8657,15 @@ pass --wait to block and print the full result.
|
|
|
8657
8657
|
`,this.cursorPos);if(e===-1&&(e=this.currentLine.length),this.cursorPos===e)return;let t=e-this.cursorPos;this.cursorPos=e,this.terminal?.write(`\x1b[${t}C`)}handleCtrlC(){this.terminal?.writeln(`^C`),this.currentLine=``,this.cursorPos=0,this.continuationBuffer=``,this.showPrompt()}handleHistoryUp(){this.history.length!==0&&this.historyIndex<this.history.length-1&&(this.historyIndex++,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex]))}handleHistoryDown(){this.historyIndex>0?(this.historyIndex--,this.continuationBuffer=``,this.replaceCurrentLine(this.history[this.history.length-1-this.historyIndex])):this.historyIndex===0&&(this.historyIndex=-1,this.continuationBuffer=``,this.replaceCurrentLine(``))}insertAtCursor(e){e&&(this.currentLine=this.currentLine.slice(0,this.cursorPos)+e+this.currentLine.slice(this.cursorPos),this.cursorPos+=e.length,this.terminal?.write(e))}async handleTab(){if(!this.terminal)return;let e=this.currentLine.slice(0,this.cursorPos).split(/\s+/),t=e[e.length-1]||``,n=e.length<=1||e.length===2&&e[0]===``,r=t?`'`+t.replace(/'/g,`'\\''`)+`'`:`''`,i=n?`compgen -A command -- ${r}`:`compgen -f -- ${r}`;try{let e=(await this.bash.exec(i,{env:this.lastEnv,cwd:this.cwd})).stdout.split(`
|
|
8658
8658
|
`).filter(Boolean);if(e.length===0)return;e.length===1?await this.applySingleCompletion(t,e[0],n,r):this.applyMultiCompletion(t,e)}catch(e){console.warn(`[Shell] Tab completion failed:`,e instanceof Error?e.message:String(e))}}async applySingleCompletion(e,t,n,r){let i=t.slice(e.length);this.insertAtCursor(i);let a=` `;n||(await this.bash.exec(`compgen -d -- ${r.slice(0,-1)}${i}'`,{env:this.lastEnv,cwd:this.cwd})).stdout.trim()===t&&(a=`/`),this.insertAtCursor(a)}applyMultiCompletion(e,t){let n=t[0];for(let e of t)for(;!e.startsWith(n);)n=n.slice(0,-1);let r=n.slice(e.length);if(r){this.insertAtCursor(r);return}this.terminal?.writeln(``),this.terminal?.writeln(t.map(e=>e.split(`/`).pop()??e).join(` `)),this.showPrompt(),this.terminal?.write(this.currentLine);let i=this.currentLine.length-this.cursorPos;i>0&&this.terminal?.write(`\x1b[${i}D`)}replaceCurrentLine(e){let t=this.getCursorVisualLine();t>0&&this.terminal?.write(`\x1b[${t}A`),this.terminal?.write(`\r\x1B[J`),this.showPrompt(),this.currentLine=e,this.cursorPos=e.length,this.terminal?.write(e)}isIncomplete(e){if(e.endsWith(`\\`))return!0;let t=!1,n=!1,r=!1;for(let i of e){if(r){r=!1;continue}if(i===`\\`&&!t){r=!0;continue}if(i===`'`&&!n){t=!t;continue}i===`"`&&!t&&(n=!n)}return t||n}async handleEnter(){let e=this.currentLine.split(`
|
|
8659
8659
|
`);if(e.length>1){let t=this.getCursorVisualLine(),n=e.length-1-t;n>0&&this.terminal?.write(`\x1b[${n}B`);let r=e[e.length-1].length;this.terminal?.write(`\r`),r>0&&this.terminal?.write(`\x1b[${r}C`)}this.terminal?.writeln(``);let t=this.currentLine;this.currentLine=``,this.cursorPos=0;let n=this.continuationBuffer?this.continuationBuffer+`
|
|
8660
|
-
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${
|
|
8660
|
+
`+t:t;if(this.isIncomplete(n)){this.continuationBuffer=n,this.terminal?.write(`> `);return}this.continuationBuffer=``;let r=n.trim();if(this.historyIndex=-1,!r){this.showPrompt();return}if(this.history[this.history.length-1]!==r&&this.history.push(r),r===`clear`){this.clearTerminal(),this.showPrompt();return}this.isExecuting=!0,this.execAbort=new AbortController;try{let e=await this.runCommand(r);this.execAbort.signal.aborted||(e.stdout&&this.writeToTerminal(e.stdout),e.stderr&&this.writeToTerminal(e.stderr,!0))}catch(e){if(!this.execAbort?.signal.aborted){let t=e instanceof Error?e.message:String(e);this.writeToTerminal(`Error: ${t}\n`,!0)}}this.execAbort=null,this.isExecuting=!1,this.showPrompt()}writeToTerminal(e,t=!1){this.terminal&&(t?this.terminal.write(`\x1b[31m${e}\x1b[0m`):this.terminal.write(e))}clearMediaPreview(){for(let e of this.previewUrls)URL.revokeObjectURL(e);this.previewUrls=[],this.hasPreview=!1,this.previewHost&&(this.previewHost.replaceChildren(),this.previewHost.classList.remove(`terminal-panel__preview--visible`)),this.previewStateListener?.(!1)}async renderMediaPreview(e){if(!this.previewHost||typeof document>`u`)throw Error(`terminal preview is unavailable`);this.clearMediaPreview();for(let t of e){let e=new Uint8Array(t.bytes),n=URL.createObjectURL(new Blob([e],{type:t.mimeType}));this.previewUrls.push(n);let r=document.createElement(`div`);r.className=`terminal-panel__preview-item`;let i=document.createElement(`div`);if(i.className=`terminal-panel__preview-label`,i.textContent=`${xY(t.path)} · ${t.mimeType}`,r.appendChild(i),t.mimeType.startsWith(`video/`)){let e=document.createElement(`video`);e.className=`terminal-panel__preview-media`,e.controls=!0,e.autoplay=!0,e.loop=!0,e.muted=!0,e.playsInline=!0,e.src=n,e.addEventListener(`loadedmetadata`,()=>this.refit(),{once:!0}),r.appendChild(e)}else{let e=document.createElement(`img`);e.className=`terminal-panel__preview-media`,e.alt=xY(t.path),e.src=n,e.addEventListener(`load`,()=>this.refit(),{once:!0}),r.appendChild(e)}this.previewHost.appendChild(r)}this.previewHost.classList.add(`terminal-panel__preview--visible`),this.hasPreview=e.length>0,this.previewStateListener?.(this.hasPreview),requestAnimationFrame(()=>this.refit())}};const CY=n(`tool:bash`),wY=/^(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:command\s+)?(?:grep|egrep|fgrep|rg)\b/;function TY(e){let t=[],n=``,r=null,i=!1,a=()=>{t.push(n),n=``};for(let t=0;t<e.length;t++){let o=e[t];if(i){n+=o,i=!1;continue}if(o===`\\`){n+=o,i=!0;continue}if(r){n+=o,o===r&&(r=null);continue}if(o===`"`||o===`'`){n+=o,r=o;continue}if((o===`&`||o===`|`)&&e[t+1]===o){a(),t++;continue}if(o===`;`||o===`|`){a();continue}n+=o}return a(),t}function EY(e){let t=TY(e);return(t[t.length-1]??``).trim()}function DY(e,t,n){return t!==1||n.trim()?!1:wY.test(EY(e))}function OY(e){return{name:`bash`,description:"Execute a bash command. Full shell with pipes, redirects, chaining, control flow. Includes: grep, rg, sed, awk, jq, find, curl, git, node, python3, sqlite3, open (--view for vision), playwright-cli (browser automation). Run `commands` for full list.",inputSchema:{type:`object`,properties:{command:{type:`string`,description:`The bash command to execute.`}},required:[`command`]},async execute(t,n){let r=t.command;CY.debug(`Execute`,{command:r});try{let t=await e.executeCommand(r,n);CY.debug(`Result`,{exitCode:t.exitCode,stdoutLength:t.stdout.length,stderrLength:t.stderr.length});let i=``;return t.stdout&&(i+=t.stdout),t.stderr&&(i+=t.stderr),i||=`(exit code: ${t.exitCode})`,{content:i,isError:t.exitCode!==0&&!DY(r,t.exitCode,t.stderr)}}catch(e){let t=e instanceof Error?e.message:String(e);return CY.error(`Error`,{command:r,error:t}),{content:`Shell error: ${t}`,isError:!0}}}}}const kY=n(`tool:fs`);function AY(e){return[jY(e),MY(e),NY(e)]}function jY(e){return{name:`read_file`,description:`Read the contents of a file. Returns the file content as a string with line numbers.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to read.`},offset:{type:`number`,description:`Line number to start reading from (1-based). Optional.`},limit:{type:`number`,description:`Maximum number of lines to read. Optional.`}},required:[`path`]},async execute(t){let n=t.path,r=t.offset??1,i=t.limit;kY.debug(`Read`,{path:n,offset:r,limit:i});try{let t=(await e.readTextFile(n)).split(`
|
|
8661
8661
|
`),a=Math.max(0,r-1),o=i===void 0?t.length:a+i;return{content:t.slice(a,o).map((e,t)=>`${String(a+t+1).padStart(6)} | ${e}`).join(`
|
|
8662
|
-
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return
|
|
8663
|
-
`)}async function
|
|
8664
|
-
`)}`}}function
|
|
8665
|
-
`)}}function
|
|
8666
|
-
`)}`}}async function GY(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),gY.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 KY(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=>CY(t,e)}}function qY(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:[...vY],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=>EY(t,e)}}function JY(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=>DY(t,e)}}function YY(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>OY(e)}}function XY(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes. Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...ki],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`}},required:[`name`]},execute:t=>jY(t,e)}}function ZY(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=>MY(t,e)}}function QY(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=>FY(t,e)}}function $Y(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=>LY(t,e)}}function eX(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=>BY(t,e)}}function tX(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=>HY(t,e)}}function nX(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>UY(t,e)}}function rX(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:()=>WY(e)}}function iX(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=>GY(t,e)}}function aX(e){let t=[],n=e.scoop.isCone;return n||(t.push(KY(e)),e.onSudoRequest&&t.push(qY(e))),n&&(e.onFeedScoop&&t.push(JY(e)),t.push(YY(e)),e.onScoopScoop&&t.push(XY(e)),e.onDropScoop&&t.push(ZY(e)),e.onMuteScoops&&t.push(QY(e)),e.onUnmuteScoops&&t.push($Y(e)),e.onScheduleScoopWait&&t.push(eX(e)),e.onSudoResolve&&(t.push(tX(e)),t.push(nX(e))),e.onListSudoRequests&&t.push(rX(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(iX(e))),t}const oX=n(`scoop-context`);function sX(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!at(t).includes(`xhigh`)?`high`:e}function cX(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 lX(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 uX(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 dX(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var fX=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await Do(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await ns(),i=this.buildSudoWiring(),a=i?St(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new iY({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),oX.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await Co(n,this.skillsDir)}}async buildTools(e){let t=aX({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...fY(e),uY(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:C()};return this.processManager?j(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):j(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=b(e.messages);return this.sessionCreatedAt=e.createdAt,oX.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){oX.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Mt(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?st(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):st(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:M()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:T({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>M()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);oX.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!M()){oX.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?y(this.scoop.config.modelId):D(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=sX(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new x({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>M()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),oX.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);oX.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=N()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(oX.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return lX(e)?(oX.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),Ir(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return kr(e)?(oX.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),Mr(this.scoop.isCone),Ir(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!uX(e)||t>=n)return!1;let a=r*2**(t-1);return oX.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await dX(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;oX.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),Ir(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(oX.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:uX(a)}),!!(t<n&&(await dX(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?y(this.scoop.config.modelId):D();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=D();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=sX(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,oX.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await Co(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,oX.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=sX(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(ki.includes(e))return e;oX.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8662
|
+
`)}}catch(e){let t=e instanceof Error?e.message:String(e);return kY.error(`Read failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function MY(e){return{name:`write_file`,description:`Write content to a file. Creates the file if it does not exist, or overwrites it if it does. Parent directories are created automatically.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to write.`},content:{type:`string`,description:`The content to write to the file.`}},required:[`path`,`content`]},async execute(t){let n=t.path,r=t.content;kY.debug(`Write`,{path:n,contentLength:r.length});try{return await e.writeFile(n,r),{content:`File written: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return kY.error(`Write failed`,{path:n,error:t}),{content:t,isError:!0}}}}}function NY(e){return{name:`edit_file`,description:`Edit a file by replacing an exact string match. The old_string must appear exactly once in the file. Use this instead of write_file when making targeted changes to existing files.`,inputSchema:{type:`object`,properties:{path:{type:`string`,description:`Absolute path to the file to edit.`},old_string:{type:`string`,description:`The exact string to find and replace. Must be unique in the file.`},new_string:{type:`string`,description:`The replacement string.`}},required:[`path`,`old_string`,`new_string`]},async execute(t){let n=t.path,r=t.old_string,i=t.new_string;kY.debug(`Edit`,{path:n,oldLength:r.length,newLength:i.length});try{let t=await e.readTextFile(n),a=t.split(r).length-1;if(a===0)return{content:`old_string not found in ${n}`,isError:!0};if(a>1)return{content:`old_string found ${a} times in ${n}. It must be unique. Provide more context.`,isError:!0};let o=t.replace(r,i);return await e.writeFile(n,o),{content:`File edited: ${n}`}}catch(e){let t=e instanceof Error?e.message:String(e);return kY.error(`Edit failed`,{path:n,error:t}),{content:t,isError:!0}}}}}const PY=n(`scoop-management-tools`);function FY(e,t){let n=t(),r=[],i=[];for(let t of e){let e=n.find(e=>!e.isCone&&(e.folder===t||e.name===t));e?r.push(e):i.push(t)}return{resolved:r,unknown:i}}const IY=[`command`,`read`,`write`,`secret`];function LY(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,50)+`-scoop`}function RY(e){return e===void 0?{ok:!0}:Ai(e)?{ok:!0,level:e}:{ok:!1,content:`Invalid thinking level "${e}". Must be one of: ${ki.join(`, `)}.`,isError:!0}}function zY(e,t){return{content:`Scoop "${e}" not found. Available: ${t().filter(e=>!e.isCone).map(e=>e.folder).join(`, `)}`,isError:!0}}function BY(e,t){let n=t?.(e.jid),r=n?.status??`unknown`,i=n?.lastActivity?new Date(n.lastActivity).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0}):``,a=i?` — ${r} (since ${i})`:` — ${r}`;return e.isCone?`- ${e.assistantLabel} (${e.folder}) [CONE]${a}`:`- ${e.name} (${e.folder})${a}`}async function VY(e,t){let{text:n,sender:r}=e;return t.onSendMessage(n,r),PY.info(`Message sent`,{scoopFolder:t.scoop.folder,textLength:n.length}),{content:`Message sent.`}}function HY(e){let{kind:t,detail:n,suggested_pattern:r}=e;return IY.includes(t)?typeof n!=`string`||n.trim().length===0?{ok:!1,result:{content:`detail must be a non-empty string.`,isError:!0}}:{ok:!0,request:{kind:t,detail:n,...r?{suggestedPattern:r}:{}}}:{ok:!1,result:{content:`Invalid sudo kind "${t}". Must be one of: ${IY.join(`, `)}.`,isError:!0}}}function UY(e){let t=[`Cone decision: ${e.decision}.`];return e.decision===`always`&&e.pattern&&t.push(`Persisted pattern: ${e.pattern}`),e.decision===`deny`&&t.push(`The sensitive action was not approved. Do not retry without addressing the reason for refusal.`),t.join(`
|
|
8663
|
+
`)}async function WY(e,t){let n=HY(e);if(!n.ok)return n.result;try{let e=await t.onSudoRequest(n.request);return PY.info(`Sudo request resolved`,{scoopFolder:t.scoop.folder,kind:n.request.kind,decision:e.decision}),{content:UY(e)}}catch(e){return{content:`sudo_request failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function GY(e,t){let{scoop_name:n,prompt:r}=e,i=t.getScoops().find(e=>e.folder===n||e.name===n);if(!i)return zY(n,t.getScoops);if(i.isCone)return{content:`Cannot feed the cone (yourself).`,isError:!0};try{return await t.onFeedScoop(i.jid,r),PY.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 KY(e){let t=e.getScoops();return t.length===0?{content:`No scoops registered.`}:{content:`Registered scoops:\n${t.map(t=>BY(t,e.getScoopTabState)).join(`
|
|
8664
|
+
`)}`}}function qY(e,t,n,r,i,a,o){return{name:e,folder:t,trigger:`@${t}`,isCone:!1,type:`scoop`,requiresTrigger:!0,assistantLabel:t,addedAt:new Date().toISOString(),config:{...n?{modelId:n}:{},visiblePaths:r??[`/workspace/`],writablePaths:i??[`/scoops/${t}/`,`/shared/`],...a?{allowedCommands:a}:{},...o?{thinkingLevel:o}:{}},configSchemaVersion:2}}async function JY(e,t,n,r,i){try{await i(e.jid,t)}catch(e){let t=e instanceof Error?e.message:String(e);return PY.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 YY(e,t){let{name:n,model:r,prompt:i,visiblePaths:a,writablePaths:o,allowedCommands:s,thinking:c}=e,l=RY(c);if(!l.ok)return{content:l.content,isError:l.isError};let u=LY(n);try{let e=qY(n,u,r,a,o,s,l.level),c=await t.onScoopScoop(e);return PY.info(`Scoop created`,{name:n,folder:u}),i&&t.onFeedScoop?JY(c,i,n,u,t.onFeedScoop):{content:`Scoop "${n}" created as "${u}". Use feed_scoop to give it a task.`}}catch(e){return{content:`Failed to create scoop: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}async function XY(e,t){let{scoop_name:n}=e,r=t.getScoops().find(e=>e.folder===n||e.name===n);if(!r)return zY(n,t.getScoops);if(r.isCone)return{content:`Cannot drop the cone (yourself).`,isError:!0};try{return await t.onDropScoop(r.jid),PY.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 ZY(){return{content:`scoop_names must be a non-empty array.`,isError:!0}}function QY(e){return{content:`No matching scoops found. Unknown: ${e.join(`, `)}`,isError:!0}}async function $Y(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return ZY();let{resolved:r,unknown:i}=FY(n,t.getScoops);return r.length===0?QY(i):(t.onMuteScoops(r.map(e=>e.jid)),PY.info(`Scoops muted`,{names:r.map(e=>e.folder)}),{content:`Muted: ${r.map(e=>e.folder).join(`, `)}${i.length>0?` (unknown: ${i.join(`, `)})`:``}`})}function eX(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 tX(e,t){let{scoop_names:n}=e;if(!Array.isArray(n)||n.length===0)return ZY();let{resolved:r,unknown:i}=FY(n,t.getScoops);if(r.length===0)return QY(i);let a=r.map(e=>e.jid),o=new Map(r.map(e=>[e.jid,e.folder])),s=await t.onUnmuteScoops(a);PY.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(...eX(s,o)),{content:c.join(`
|
|
8665
|
+
`)}}function nX(e,t){return!Array.isArray(e)||e.length===0?ZY():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 rX(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 iX(e,t){let{scoop_names:n,timeout_ms:r}=e,i=nX(n,r);if(i)return i;let{resolved:a,unknown:o}=FY(n,t.getScoops);if(a.length===0)return QY(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 PY.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:rX(u,o,d,r)}}function aX(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 oX(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?(PY.info(`Lick confirmed`,{id:n,always:!!r,persisted:e.persisted}),e.message?{content:e.message}:{content:aX(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 sX(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?(PY.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 cX(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(`
|
|
8666
|
+
`)}`}}async function lX(e,t){let{content:n}=e;try{return await t.onSetGlobalMemory(n),PY.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 uX(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=>VY(t,e)}}function dX(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:[...IY],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=>WY(t,e)}}function fX(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=>GY(t,e)}}function pX(e){return{name:`list_scoops`,description:`List all registered scoops.`,inputSchema:{type:`object`,properties:{}},execute:()=>KY(e)}}function mX(e){return{name:`scoop_scoop`,description:`Create a new scoop. Optionally specify a model, a prompt, and per-scoop sandbox shape (visible/writable paths + command allow-list). If prompt is provided, the scoop starts working immediately after creation (no separate feed_scoop needed).`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Display name for the scoop (e.g., "hero-block")`},model:{type:`string`,description:`Model ID for this scoop (e.g., "claude-sonnet-4-6"). If omitted, uses the same model as the cone.`},prompt:{type:`string`,description:`Task prompt for the scoop. If provided, the scoop starts working immediately after creation.`},visiblePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ (not write). Pure replace — what you set is what you get. Omit to use the default ["/workspace/"] which exposes the shared skills tree. Pass [] for no extra read-only paths. Note: the scoop's writablePaths are always readable too, so a true read-nothing sandbox also requires writablePaths: []. Mounts remain readable regardless. Trailing slash recommended (e.g. "/shared/data/").`},writablePaths:{type:`array`,items:{type:`string`},description:`VFS paths the scoop can READ AND WRITE. Pure replace. Omit to use the default ["/scoops/<folder>/", "/shared/"] which gives the scoop its own sandbox plus shared space. Pass [] to block all writes. Trailing slash recommended.`},allowedCommands:{type:`array`,items:{type:`string`},description:`Shell command allow-list. Omit for unrestricted access to every built-in, custom, and .jsh command (the default). Pass a list of command names to restrict the scoop's shell — e.g. ["echo","cat","grep"] for a read-only text-processing scoop. Pass ["*"] for explicit unrestricted. Applies to pipelines, substitutions, and network commands too.`},thinking:{type:`string`,enum:[...ki],description:`Reasoning / thinking-level for this scoop (pi-ai effort). One of: off, minimal, low, medium, high, xhigh. Omit to inherit the global default ("off"). Non-reasoning models always clamp to "off"; "xhigh" clamps to "high" on models that do not support the max tier.`}},required:[`name`]},execute:t=>YY(t,e)}}function hX(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=>XY(t,e)}}function gX(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=>$Y(t,e)}}function _X(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=>tX(t,e)}}function vX(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=>iX(t,e)}}function yX(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=>oX(t,e)}}function bX(e){return{name:`lick_dismiss`,description:`Dismiss (refuse) a pending actionable lick by its lick_id — currently a scoop sudo escalation raised via sudo_request. The scoop receives a deny decision and the sensitive action does NOT run.`,inputSchema:{type:`object`,properties:{lick_id:{type:`string`,description:`The id of the pending actionable lick (as delivered in the [sudo-request] notification). Use list_sudo_requests to see outstanding ids.`}},required:[`lick_id`]},execute:t=>sX(t,e)}}function xX(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:()=>cX(e)}}function SX(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=>lX(t,e)}}function CX(e){let t=[],n=e.scoop.isCone;return n||(t.push(uX(e)),e.onSudoRequest&&t.push(dX(e))),n&&(e.onFeedScoop&&t.push(fX(e)),t.push(pX(e)),e.onScoopScoop&&t.push(mX(e)),e.onDropScoop&&t.push(hX(e)),e.onMuteScoops&&t.push(gX(e)),e.onUnmuteScoops&&t.push(_X(e)),e.onScheduleScoopWait&&t.push(vX(e)),e.onSudoResolve&&(t.push(yX(e)),t.push(bX(e))),e.onListSudoRequests&&t.push(xX(e)),e.onSetGlobalMemory&&e.getGlobalMemory&&t.push(SX(e))),t}const wX=n(`scoop-context`);function TX(e,t){return!t.reasoning||e===void 0?`off`:e===`xhigh`&&!at(t).includes(`xhigh`)?`high`:e}function EX(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 DX(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 OX(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 kX(e,t){return t?.aborted?Promise.resolve(!0):new Promise(n=>{let r=()=>{clearTimeout(i),n(!0)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!1)},e);t?.addEventListener(`abort`,r,{once:!0})})}var AX=class{scoop;callbacks;fs=null;shell=null;agent=null;status=`initializing`;isProcessing=!1;disposed=!1;didStreamDeltas=!1;promptStreamErrorMessage=null;unsubscribe=null;promptAbortController=null;processManager=null;currentTurnProcess=null;sessionStore=null;sessionId;sessionCreatedAt=0;isRecovering=!1;coneJid;skillsFs=null;skillsDir=`/workspace/skills`;sudoManager=null;structuredOutputValue;activeEffortOverride;structuredOutputCaptured=!1;constructor(e,t,n,r,i,a,o,s){this.scoop=e,this.callbacks=t,this.fs=n,this.sessionStore=r??null,this.skillsFs=i??null,this.coneJid=a,this.processManager=o??null,this.sudoManager=s??null,this.sessionId=e.jid}getStructuredOutput(){return{captured:this.structuredOutputCaptured,value:this.structuredOutputValue}}buildSudoWiring(){if(!this.sudoManager)return null;let e=this.sudoManager,t=this.scoop.isCone,n=this.scoop.folder,r=this.callbacks.onSudoRequest,i=t||!r?e.getBroker():{requestApproval:e=>r(e)},a=t?()=>e.getPolicy():()=>e.getPolicyForScoop(n),o=t?`allow`:`require-approval`,s=e.getShellConfig(),c=t?s.persistCommandGrant:async()=>{};return{broker:i,getPolicy:a,defaultDisposition:o,shellConfig:{...s,broker:i,getPolicy:a,defaultDisposition:o,persistCommandGrant:c}}}async initShellAndSkills(){let e=this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,t=this.callbacks.getBrowserAPI();this.skillsDir=`/workspace/skills`,this.scoop.isCone&&await Do(this.fs,this.skillsDir);let n=this.skillsFs??this.fs,r=await ns(),i=this.buildSudoWiring(),a=i?St(this.fs,{broker:i.broker,getPolicy:i.getPolicy,defaultDisposition:i.defaultDisposition}):this.fs;return this.shell=new SY({fs:a,cwd:e,env:Object.keys(r).length>0?r:void 0,browserAPI:t,jshDiscoveryFs:this.skillsFs?n:void 0,allowedCommands:this.scoop.config?.allowedCommands,getParentJid:()=>this.scoop.jid,isScoop:()=>!this.scoop.isCone,sudo:i?.shellConfig,processManager:this.processManager??void 0,processOwner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getCurrentShellPid:()=>this.currentTurnProcess?.pid}),wX.info(`AlmostBashShell initialized`,{folder:this.scoop.folder}),{gatedFs:a,skills:await Co(n,this.skillsDir)}}async buildTools(e){let t=CX({scoop:this.scoop,onSendMessage:this.callbacks.onSendMessage,getScoops:this.callbacks.getScoops,getScoopTabState:this.callbacks.getScoopTabState,onFeedScoop:this.callbacks.onFeedScoop,onScoopScoop:this.callbacks.onScoopScoop,onDropScoop:this.callbacks.onDropScoop,onMuteScoops:this.callbacks.onMuteScoops,onUnmuteScoops:this.callbacks.onUnmuteScoops,onScheduleScoopWait:this.callbacks.onScheduleScoopWait,onSetGlobalMemory:this.callbacks.setGlobalMemory,getGlobalMemory:this.callbacks.getGlobalMemory,onSudoRequest:this.callbacks.onSudoRequest,onSudoResolve:this.callbacks.onSudoResolve,onListSudoRequests:this.callbacks.onListSudoRequests}),n=[...AY(e),OY(this.shell),...t];if(this.scoop.config?.structuredOutputSchema){let{createStructuredOutputTool:e}=await import(`./structured-output-tool-BDaIhclx.js`);n.push(e(this.scoop.config.structuredOutputSchema,e=>{this.structuredOutputValue=e,this.structuredOutputCaptured=!0}))}let r={scrubToolResult:C()};return this.processManager?j(n,{processManager:this.processManager,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},getParentPid:()=>this.currentTurnProcess?.pid},r):j(n,void 0,r)}async loadMemories(){let e=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`,t=``;try{let n=await this.fs.readFile(e,{encoding:`utf-8`});t=typeof n==`string`?n:new TextDecoder().decode(n)}catch{}let n=await this.callbacks.getGlobalMemory();if(n&&this.scoop.isCone)try{await(`getUnderlyingFS`in this.fs?this.fs.getUnderlyingFS():this.fs).writeFile(`/shared/CLAUDE.md`,n)}catch{}return{scoopMemory:t,globalMemory:n}}async restoreSession(){if(!this.sessionStore)return[];try{let e=await this.sessionStore.load(this.sessionId);if(e){let t=b(e.messages);return this.sessionCreatedAt=e.createdAt,wX.info(`Restored agent session`,{folder:this.scoop.folder,messageCount:t.length,droppedOrphans:e.messages.length-t.length}),t}}catch(e){wX.error(`Failed to restore agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.callbacks.onError(`Conversation history could not be restored. Starting fresh.`)}return[]}async buildSessionHelpers(e){let t=await Mt(this.scoop,this.coneJid),n=(e,n,r)=>{let i=this.activeEffortOverride,a=i?{...r,effort:i}:r;return e.provider===`adobe`?st(e,n,{...a,headers:{...r?.headers,"X-Session-Id":t}}):st(e,n,a)},r=e.provider===`adobe`?{"X-Session-Id":t}:void 0,i=this.scoop.isCone&&this.callbacks.appendConeMemory?t=>this.callbacks.appendConeMemory(t,{source:`compaction`,model:e,apiKey:M()??void 0,headers:r}):void 0;return{streamWithSessionId:n,compactFn:T({model:e,contextWindow:typeof e.contextWindow==`number`&&e.contextWindow>0?e.contextWindow:void 0,getApiKey:()=>M()??void 0,headers:r,onMemoryUpdates:i,onCompactionStateChange:this.callbacks.onCompactionStateChange})}}async init(){this.setStatus(`initializing`);try{if(!this.fs)throw Error(`Filesystem not provided`);wX.info(`Filesystem ready`,{folder:this.scoop.folder}),await this.ensureDirectoryStructure();let{gatedFs:e,skills:t}=await this.initShellAndSkills(),n=await this.buildTools(e),{scoopMemory:r,globalMemory:i}=await this.loadMemories();if(!M()){wX.info(`ScoopContext init deferred — no API key yet`,{folder:this.scoop.folder}),this.setStatus(`ready`);return}let a=this.scoop.config?.modelId?y(this.scoop.config.modelId):D(),o=this.scoop.isCone?`Cone`:`Scoop "${this.scoop.name}"`;console.log(`[model] ${o} using model: ${a.id} (provider: ${a.provider})`);let s=this.buildSystemPrompt(i,r,t),c=await this.restoreSession(),{streamWithSessionId:l,compactFn:u}=await this.buildSessionHelpers(a);if(this.disposed)return;let d=TX(this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel,a);this.activeEffortOverride=this.scoop.config?.effortOverride,this.agent=new x({initialState:{model:a,tools:n,systemPrompt:s,messages:c,thinkingLevel:d},getApiKey:()=>M()??void 0,transformContext:u,streamFn:l,afterToolCall:async e=>{this.scoop.config?.structuredOutputSchema&&e.toolCall.name===`StructuredOutput`&&(this.structuredOutputValue=e.args,this.structuredOutputCaptured=!0)}}),this.unsubscribe=this.agent.subscribe(e=>this.handleAgentEvent(e)),this.setStatus(`ready`),wX.info(`ScoopContext initialized`,{folder:this.scoop.folder,toolCount:n.length})}catch(e){if(this.disposed)return;let t=e instanceof Error?e.message:String(e);wX.error(`ScoopContext init failed`,{folder:this.scoop.folder,error:t}),this.setStatus(`error`),this.callbacks.onError(`Failed to initialize: ${t}`)}}async ensureAgentReady(){if(this.agent)return!0;if(await this.init(),!this.agent){let e=``;try{e=N()}catch{}return this.callbacks.onError(e?`No API key configured for provider "${e}". Open Settings to add one.`:`No API key configured. Open Settings to add one.`),!1}return!0}queuePromptIfBusy(e,t){let n=this.agent.state?.isStreaming??!1;return this.isProcessing||n?(wX.info(`Queueing prompt via followUp while processing`,{folder:this.scoop.folder,isProcessing:this.isProcessing,agentIsStreaming:n}),this.agent.followUp({role:`user`,content:[{type:`text`,text:e},...t],timestamp:Date.now()}),!0):!1}registerTurnProcess(e,t){if(!this.processManager)return null;let n=[`prompt`,e.length>200?e.slice(0,197)+`…`:e];return this.processManager.spawn({kind:`scoop-turn`,argv:n,cwd:this.scoop.isCone?`/workspace`:`/scoops/${this.scoop.folder}/workspace`,owner:{kind:this.scoop.isCone?`cone`:`scoop`,scoopJid:this.scoop.jid},adoptAbort:t})}handleNonRetryableError(e){return DX(e)?(wX.error(`Non-retryable agent error`,{folder:this.scoop.folder,error:e}),Ir(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed with unrecoverable error: ${e}`):this.callbacks.onError(e),!0):!1}handleStaleAssetError(e){return kr(e)?(wX.error(`Stale-asset import failure; requesting page reload`,{folder:this.scoop.folder,error:e}),Mr(this.scoop.isCone),Ir(`llm`,e),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" hit a stale build after a deploy; reloading to recover.`):this.callbacks.onError(e),!0):!1}async handleRetryableError(e,t,n,r,i){if(!OX(e)||t>=n)return!1;let a=r*2**(t-1);return wX.warn(`Retryable agent error, will retry`,{folder:this.scoop.folder,error:e,attempt:t,maxRetries:n,delayMs:a}),!await kX(a,i)&&!this.disposed}handleExhaustedRetries(e,t){let n=e.message;wX.error(`Agent error after retries exhausted`,{folder:this.scoop.folder,error:n,maxRetries:t}),Ir(`llm`,n),this.setStatus(`error`),this.callbacks.onFatalError?this.callbacks.onFatalError(`Scoop "${this.scoop.name}" failed after ${t} attempts: ${n}`):this.callbacks.onError(n)}cleanupPromptState(e,t,n,r){this.isProcessing=!1,!this.disposed&&this.status===`processing`&&this.setStatus(`ready`),this.promptAbortController===e&&(this.promptAbortController=null),t&&this.processManager&&(n&&!r.aborted?this.processManager.exit(t.pid,1):this.processManager.exit(t.pid,r.aborted?null:0)),this.currentTurnProcess===t&&(this.currentTurnProcess=null)}async tryAgentPrompt(e,t,n){this.didStreamDeltas=!1,this.promptStreamErrorMessage=null;try{return await e.prompt(t,n),this.promptStreamErrorMessage?Error(this.promptStreamErrorMessage):null}catch(e){return e instanceof Error?e:Error(String(e))}}async handlePromptAttemptError(e,t,n,r,i){let a=e.message;return this.handleStaleAssetError(a)||this.handleNonRetryableError(a)?!0:await this.handleRetryableError(a,t,n,r,i)?!1:(wX.error(`Agent error`,{folder:this.scoop.folder,error:a,attempt:t,isRetryable:OX(a)}),!!(t<n&&(await kX(r*2**(t-1),i)||this.disposed)))}async runAgentWithRetries(e,t,n,r){let i=null;for(let a=1;a<=3;a++){if(this.disposed||r.aborted)return null;let o=await this.tryAgentPrompt(e,t,n);if(!o||this.disposed||r.aborted||(i=o,await this.handlePromptAttemptError(o,a,3,1e3,r)))return null}return i}async prompt(e,t=[]){if(!await this.ensureAgentReady()||this.queuePromptIfBusy(e,t))return;let n=this.agent;this.promptAbortController?.abort();let r=new AbortController;this.promptAbortController=r;let i=r.signal;this.isProcessing=!0,this.setStatus(`processing`);let a=this.registerTurnProcess(e,r);this.currentTurnProcess=a;let o=null;try{if(o=await this.runAgentWithRetries(n,e,t,i),o&&!this.disposed&&!i.aborted){this.handleExhaustedRetries(o,3);return}!this.disposed&&!i.aborted&&this.status!==`error`&&this.setStatus(`ready`)}finally{this.cleanupPromptState(r,a,o,i)}}stop(){this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGINT`):this.promptAbortController?.abort(),this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.isProcessing=!1,this.setStatus(`ready`)}clearMessages(){this.agent&&(this.agent.state.messages=[])}getAgentMessages(){return this.agent?.state?.messages?structuredClone(this.agent.state.messages):[]}getContextFill(){let e=this.agent?.state?.messages??[];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role!==`assistant`||!n.usage)continue;let r=n.usage.input+n.usage.cacheRead+n.usage.output,i=2e5;try{let e=this.scoop.config?.modelId?y(this.scoop.config.modelId):D();typeof e.contextWindow==`number`&&e.contextWindow>0&&(i=e.contextWindow)}catch{}return Math.min(1,r/i)}return 0}getSessionId(){return this.sessionId}getFS(){return this.fs}getShell(){return this.shell}updateModel(){if(!this.agent)return;let e=D();this.agent.state.model=e;let t=this.getLockedEffortLevel()??this.scoop.config?.thinkingLevel;this.agent.state.thinkingLevel=TX(t,e),this.activeEffortOverride=e.reasoning?this.scoop.config?.effortOverride:void 0,wX.info(`Model updated on running agent`,{folder:this.scoop.folder,model:e.id,thinkingLevel:this.agent.state.thinkingLevel})}async reloadSkills(){if(!this.agent)return;let e=await Co(this.skillsFs??this.fs,this.skillsDir),t=``,n=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{let e=await this.fs.readFile(n,{encoding:`utf-8`});t=typeof e==`string`?e:new TextDecoder().decode(e)}catch{}let r=await this.callbacks.getGlobalMemory(),i=this.buildSystemPrompt(r,t,e);this.agent.state.systemPrompt=i,wX.info(`Skills reloaded`,{folder:this.scoop.folder,skillCount:e.length})}setThinkingLevel(e,t){if(!this.agent)return`off`;if(this.getLockedEffortLevel())return this.agent.state.thinkingLevel;this.activeEffortOverride=t;let n=TX(e,this.agent.state.model);return this.agent.state.thinkingLevel=n,n}getLockedEffortLevel(){try{let e=localStorage.getItem(`slicc_locked_effort_level`);if(!e)return null;if(ki.includes(e))return e;wX.warn(`Unrecognized locked effort level in localStorage, ignoring:`,e)}catch{}return null}getThinkingLevel(){return this.agent?.state.thinkingLevel??`off`}dispose(){this.disposed=!0,this.currentTurnProcess&&this.processManager?this.processManager.signal(this.currentTurnProcess.pid,`SIGTERM`):this.promptAbortController?.abort(),this.promptAbortController=null,this.agent?.clearAllQueues?.(),this.agent?.abort?.(),this.unsubscribe?.(),this.unsubscribe=null,this.shell?.dispose(),this.agent=null,this.shell=null,this.fs=null}setStatus(e){this.disposed||(this.status=e,this.callbacks.onStatusChange(e))}handleToolUIEvents(e){let t=e.partialResult;for(let n of t?.content??[])n.type===`tool_ui`&&n.requestId&&n.html?this.callbacks.onToolUI?.(e.toolName,n.requestId,n.html):n.type===`tool_ui_done`&&n.requestId&&this.callbacks.onToolUIDone?.(n.requestId)}formatToolResult(e){let t=e.result,n=[];for(let e of t?.content??[])e.type===`text`&&e.text&&n.push(e.text),e.type===`image`&&e.data&&e.mimeType&&n.push(`<img:data:${e.mimeType};base64,${e.data}>`);let r=n.join(`
|
|
8667
8667
|
`);if(e.isError){let t=n.filter(e=>!e.startsWith(`<img:`)).join(`
|
|
8668
|
-
`);Ir(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&
|
|
8668
|
+
`);Ir(`tool`,`${e.toolName}: ${t}`)}this.callbacks.onToolEnd?.(e.toolName,r,e.isError)}handleAgentEndEvent(e){if(e.length>0){let t=e[e.length-1];if(t.role===`assistant`&&t.errorMessage){let n=t.errorMessage;if(!this.isRecovering&&EX(n)){this.recoverFromImageError(e);return}if(!this.isRecovering&&bi(t)){this.recoverFromOverflow(e);return}if(!this.isRecovering&&this.isProcessing&&!this.didStreamDeltas){this.promptStreamErrorMessage=n;return}this.isRecovering=!1,Ir(`llm`,n),this.callbacks.onError(n)}else this.isRecovering=!1}let t=this.agent?.state?.messages??e;this.sessionStore&&t.length>0&&this.sessionStore.save({id:this.sessionId,messages:t,config:{},createdAt:this.sessionCreatedAt||Date.now(),updatedAt:Date.now()}).catch(e=>{wX.error(`Failed to save agent session`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)})})}handleAgentEvent(e){if(!this.disposed)switch(e.type){case`message_update`:{let t=e.assistantMessageEvent;t.type===`text_delta`&&(this.didStreamDeltas=!0,this.callbacks.onResponse(t.delta,!0));break}case`tool_execution_start`:this.callbacks.onToolStart?.(e.toolName,e.args);break;case`tool_execution_update`:this.handleToolUIEvents(e);break;case`tool_execution_end`:this.formatToolResult(e);break;case`message_end`:if(e.message.role===`assistant`){let t=e.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);t&&!this.didStreamDeltas&&this.callbacks.onResponse(t,!1)}break;case`turn_end`:this.callbacks.onResponseDone();break;case`agent_end`:this.handleAgentEndEvent(e.messages);break}}trimOversizedMessages(e){let t=e.slice(0,-1),n=0;for(let e=t.length-1;e>=0&&n<5;e--){let r=t[e];if(!Array.isArray(r.content))continue;let i=0;for(let e of r.content)e.type===`text`&&e.text&&(i+=e.text.length),e.type===`image`&&e.data&&(i+=e.data.length);if(i>4e4){let a={type:`text`,text:`[Content removed: ${r.role===`toolResult`?`tool result`:r.role} was too large for context window (${Math.round(i/1e3)}K chars). The operation completed but output could not be retained.]`};if(r.role===`assistant`){let n=r.content.filter(e=>e.type===`toolCall`);t[e]={...r,content:[a,...n]}}else t[e]={...r,content:[a]};n++,wX.info(`Replaced oversized message`,{index:e,role:r.role,size:i,preservedToolCalls:r.role===`assistant`?r.content.filter(e=>e.type===`toolCall`).length:0})}}return{trimmed:t,replaced:n}}recoverFromOverflow(e){if(this.agent){wX.warn(`Context overflow detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`overflow`,this.callbacks.onResponse(`Context window exceeded — recovering by trimming oversized messages...`,!1);try{let{trimmed:t,replaced:n}=this.trimOversizedMessages(e);this.agent.state.messages=t;let r=n>0?`[System: Context overflow recovered. ${n} oversized message(s) were replaced with placeholders to fit within the context window. The conversation continues — you may need to re-read files or re-run commands if their output was removed.]`:`[System: Context overflow recovered. Older messages were trimmed. The conversation continues — compaction will summarize history on the next turn.]`;this.agent.prompt(r).catch(e=>{wX.error(`Recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){wX.error(`Recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Context overflow recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}recoverFromImageError(e){if(this.agent){wX.warn(`Image processing error detected, attempting recovery`,{folder:this.scoop.folder,messageCount:e.length}),this.isRecovering=`image`,this.callbacks.onResponse(`Image rejected by API — removing problematic images and continuing...`,!1);try{let t=e.slice(0,-1),n=0,r=Math.max(0,t.length-10);for(let e=t.length-1;e>=r;e--){let r=t[e];if(!Array.isArray(r.content)||!r.content.some(e=>e.type===`image`))continue;let i=r.content.filter(e=>e.type!==`image`);i.length===0?t[e]={...r,content:[{type:`text`,text:`[Image removed: rejected by API]`}]}:t[e]={...r,content:i},n++}this.agent.state.messages=t;let i=`[System: An image was rejected by the API and has been removed from the conversation (${n} message(s) affected). The conversation continues without the image.]`;this.agent.prompt(i).catch(e=>{wX.error(`Image recovery re-prompt failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)})}catch(e){wX.error(`Image recovery failed`,{folder:this.scoop.folder,error:e instanceof Error?e.message:String(e)}),this.isRecovering=!1,this.callbacks.onError(`Image error recovery failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureDirectoryStructure(){if(!this.fs)return;let e=this.scoop.isCone?[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`]:[`/scoops/${this.scoop.folder}`,`/scoops/${this.scoop.folder}/workspace`,`/scoops/${this.scoop.folder}/home`,`/scoops/${this.scoop.folder}/tmp`,`/shared`];for(let t of e)try{await this.fs.mkdir(t,{recursive:!0})}catch{}let t=this.scoop.isCone?`/workspace/CLAUDE.md`:`/scoops/${this.scoop.folder}/CLAUDE.md`;try{await this.fs.readFile(t)}catch{let e=`# ${this.scoop.assistantLabel} Memory
|
|
8669
8669
|
|
|
8670
8670
|
${this.scoop.isCone?`Role: Cone (main orchestrator)`:`Scoop: ${this.scoop.name}`}
|
|
8671
8671
|
Folder: ${this.scoop.folder}
|
|
@@ -8676,7 +8676,7 @@ Created: ${new Date().toISOString()}
|
|
|
8676
8676
|
|
|
8677
8677
|
## Context
|
|
8678
8678
|
(Add important context here)
|
|
8679
|
-
`;try{await this.fs.writeFile(t,e)}catch(e){if(e?.code===`EACCES`)
|
|
8679
|
+
`;try{await this.fs.writeFile(t,e)}catch(e){if(e?.code===`EACCES`)wX.debug(`Skipping default memory write (sandbox is read-only)`,{folder:this.scoop.folder,path:t});else throw e}}}buildSystemPrompt(e,t,n){let r=this.scoop.config?.assistantName||this.scoop.assistantLabel,i=`# ${r}
|
|
8680
8680
|
|
|
8681
8681
|
You are ${r}, ${this.scoop.isCone?`the main assistant (cone)`:`a scoop assistant`} in SLICC (Self-Licking Ice Cream Cone).
|
|
8682
8682
|
|
|
@@ -8746,14 +8746,14 @@ ${e}
|
|
|
8746
8746
|
---
|
|
8747
8747
|
${this.scoop.isCone?`CONE`:`SCOOP`} MEMORY (${this.scoop.name}):
|
|
8748
8748
|
${t}
|
|
8749
|
-
---`);let a=Eo(n);return a&&(i+=a),i}};const pX=n(`scoop-lifecycle-manager`);var mX=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){pX.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){pX.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)pX.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{pX.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new dt(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new fX(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),pX.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),pX.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return pX.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(pX.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){pX.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){pX.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),pX.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),pX.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||zr(`spawn`,e.folder)}catch(n){pX.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){pX.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=>{pX.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{pX.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{pX.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&pX.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),pX.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){pX.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();pX.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{pX.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),pX.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){pX.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),zr(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);pX.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),zr(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){pX.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{pX.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const hX=n(`scoop-message-router`);var gX=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(hX.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){hX.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}`);zr(`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),hX.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);hX.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){hX.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){hX.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(hX.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){hX.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{hX.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){hX.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){hX.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i);if(hX.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){hX.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${wi(e.content,e.attachments)}`).join(`
|
|
8750
|
-
`),c=o.flatMap(e=>Ti(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);hX.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{hX.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=>{hX.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,[]),hX.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{hX.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),hX.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const _X=n(`orchestrator`);var vX=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new jo({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Qo({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Xo({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Ko({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;approvalRouter=new Ro({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>De(e),saveMessage:e=>be(e)});lickRegistry=new Po({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new gX({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>be(e),deleteMessage:e=>W(e),clearMessagesForScoop:e=>Te(e),clearAllMessages:()=>Oe(),getMessagesSince:(e,t,n)=>we(e,t,n),setState:(e,t)=>je(e,t)},isExternalLickChannel:Vn});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new mX({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=>Me(e),deleteScoop:e=>ye(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>et(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await Ae(),this.sharedFs=await ut.create({dbName:`slicc-fs`}),this.sessionStore=new Oi,this.fsWatcher=new lt,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new Fa({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await Ce();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await Se(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Io({onTaskRun:async(e,t)=>{_X.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(),_X.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);_X.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}gt(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>Ze(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await ut.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Do(this.sharedFs).catch(e=>{_X.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new Fa({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),_X.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 De(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&_X.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,_X.info(`Orchestrator shutdown`)}};function yX(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var bX=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=SX(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=CX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);return xX.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new L(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=SX(e);if(t.length!==2)throw new L(`EISDIR`,`is a directory`,e);let n=CX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!xX.includes(r))throw new L(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new L(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=SX(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=CX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=CX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!xX.includes(r))throw new L(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new L(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new L(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new L(`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 L(`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 AX(t);let n=this.pm.get(e);switch(t){case`status`:return wX(n);case`cmdline`:return TX(n);case`cwd`:return EX(n);case`stat`:return DX(n)}}};const xX=[`status`,`cmdline`,`cwd`,`stat`];function SX(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function CX(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function wX(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${OX(e.status)} (${e.status})`,`Owner:\t${kX(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(`
|
|
8749
|
+
---`);let a=Eo(n);return a&&(i+=a),i}};const jX=n(`scoop-lifecycle-manager`);var MX=class{deps;tabs=new Map;contexts=new Map;scoopObservers=new Map;constructor(e){this.deps=e}getContexts(){return this.contexts}getContext(e){return this.contexts.get(e)}getTab(e){return this.tabs.get(e)}observe(e,t){let n=this.scoopObservers.get(e);return n||(n=new Set,this.scoopObservers.set(e,n)),n.add(t),()=>{let n=this.scoopObservers.get(e);n&&(n.delete(t),n.size===0&&this.scoopObservers.delete(e))}}dispatch(e,t,...n){let r=this.scoopObservers.get(e);if(r)for(let i of r){let r=i[t];if(r)try{r(...n)}catch(n){jX.warn(`scoop observer threw`,{jid:e,event:t,error:n instanceof Error?n.message:String(n)})}}}async ensureSudoersLoaded(e){let t=this.deps.getSudoManager(),n=this.deps.getSharedFs();if(!(!t||!n))try{let r=`/scoops/${e.folder}/etc/sudoers`;await n.exists(r)?await t.reloadScoopPolicyByFolder(e.folder):await t.seedScoopSudoers(e.folder,e.config)}catch(t){jX.warn(`Failed to seed per-scoop sudoers; continuing with existing policy`,{folder:e.folder,error:t instanceof Error?t.message:String(t)})}}async createTab(e){let t=this.deps.getScoops().get(e);if(!t)throw Error(`Scoop not found: ${e}`);if(this.contexts.has(e))if(this.tabs.get(e)?.status===`error`)jX.info(`Re-creating context after error`,{jid:e}),this.contexts.get(e)?.dispose(),this.contexts.delete(e),this.tabs.delete(e);else{jX.debug(`Context already exists`,{jid:e});return}let n=this.deps.getSharedFs();if(!n)throw Error(`Shared filesystem not initialized`);let r=`scoop-${t.folder}-${Date.now()}`,i=t.isCone?n:new dt(n,t.config?.writablePaths?[...t.config.writablePaths]:[],t.config?.visiblePaths?[...t.config.visiblePaths]:[],`sudo-delegated`);t.isCone||await this.ensureSudoersLoaded(t);let a=this.buildContextCallbacks(e,t),o=Array.from(this.deps.getScoops().values()).find(e=>e.isCone)?.jid,s=new AX(t,a,i,this.deps.getSessionStore()??void 0,n??void 0,o,this.deps.getProcessManager()??void 0,this.deps.getSudoManager());this.contexts.set(e,s),this.tabs.set(e,{jid:e,contextId:r,status:`initializing`,lastActivity:new Date().toISOString()}),await s.init();let c=this.tabs.get(e);c&&c.status===`initializing`&&(c.status=`ready`,this.tabs.set(e,c),this.deps.callbacks.onStatusChange(e,`ready`),this.dispatch(e,`onStatusChange`,`ready`));let l=this.deps.getScoops().get(e);l&&!l.isCone&&this.deps.idleTimers.start(e),jX.info(`Scoop context created`,{jid:e,contextId:r})}destroyTab(e){this.deps.idleTimers.clear(e);let t=this.contexts.get(e);t&&(t.dispose(),this.contexts.delete(e),this.tabs.delete(e),this.scoopObservers.delete(e),jX.info(`Scoop context destroyed`,{jid:e}))}forgetObservers(e){this.scoopObservers.delete(e)}getTabsMap(){return this.tabs}setTab(e,t){this.tabs.set(e,t)}markTabError(e,t){let n=this.tabs.get(e);this.tabs.set(e,{jid:e,contextId:n?.contextId??`scoop-error-${e}`,status:`error`,error:t,lastActivity:new Date().toISOString()})}dispatchEvent(e,t,...n){this.dispatch(e,t,...n)}stopAndClearAllContexts(){for(let[e,t]of this.contexts.entries())this.deps.idleTimers.clear(e),t.stop(),this.contexts.delete(e)}async destroyAllTabs(){for(let e of Array.from(this.contexts.keys()))this.destroyTab(e)}async waitForTabReady(e,t=1e4){let n=Date.now();for(;Date.now()-n<t;){let t=this.tabs.get(e);if(!t)return!1;if(t.status===`ready`||t.status===`processing`)return!0;if(t.status===`error`)return!1;await new Promise(e=>setTimeout(e,100))}return jX.warn(`Timed out waiting for tab to become ready`,{jid:e}),!1}async sendPrompt(e,t,n,r,i=[]){let a=this.contexts.get(e);a||=(await this.createTab(e),this.contexts.get(e));let o=this.tabs.get(e);if(o?.status===`initializing`){if(jX.debug(`Context initializing, waiting to send message`,{jid:e}),!await this.waitForTabReady(e)){jX.error(`Context did not become ready in time, dropping prompt`,{jid:e});return}a=this.contexts.get(e),o=this.tabs.get(e)}if(!a){jX.error(`Context not found after creation`,{jid:e});return}this.deps.idleTimers.clear(e),this.deps.completionService.clearResponse(e),o&&(o.status=`processing`,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o),this.deps.callbacks.onStatusChange(e,`processing`),this.dispatch(e,`onStatusChange`,`processing`)),jX.debug(`Prompt sent to scoop`,{jid:e,textLength:t.length,imageCount:i.length}),await a.prompt(t,i)}async register(e){let t=this.deps.getScoops();await this.deps.db.saveScoop(e),t.set(e.jid,e),this.deps.messageRouter.ensureQueue(e.jid),jX.info(`Scoop registered`,{jid:e.jid,name:e.name});try{await this.createTab(e.jid),e.isCone||zr(`spawn`,e.folder)}catch(n){jX.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){jX.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=>{jX.warn(`Failed to rollback scoop registration`,{jid:e.jid,name:e.name,error:t instanceof Error?t.message:String(t)})}),n}}async unregister(e){let t=this.deps.getScoops(),n=t.get(e),r=this.deps.getLickManager();if(n&&r){let{webhooks:e,cronTasks:t}=await r.getLicksForScoopFromDb(n.name,n.folder),i=this.deps.buildActiveLicksError(n.folder,e,t);if(i)throw i}this.deps.costTracker.snapshot(e);let i=globalThis.__slicc_wsSubscribers;i&&i.dropForScoop(e).catch(t=>{jX.warn(`dropForScoop (ws subscribers) failed`,{jid:e,error:t instanceof Error?t.message:String(t)})}),this.deps.idleTimers.clear(e),this.destroyTab(e),this.deps.getSessionStore()?.delete(e).catch(t=>{jX.warn(`Failed to delete agent session`,{jid:e,error:t instanceof Error?t.message:String(t)})}),await this.deps.db.deleteScoop(e),t.delete(e),this.deps.messageRouter.forgetScoop(e),this.scoopObservers.delete(e),this.deps.completionService.forgetScoop(e,`unregister`);let a=this.deps.approvalRouter.failScoop(e);if(a>0&&jX.info(`Failed-closed pending sudo requests for unregistered scoop`,{jid:e,count:a}),jX.info(`Scoop unregistered`,{jid:e}),n)try{this.deps.callbacks.onScoopUnregistered?.(n)}catch(t){jX.warn(`onScoopUnregistered callback threw`,{jid:e,error:t instanceof Error?t.message:String(t)})}}updateModelOnAll(){for(let e of this.contexts.values())e.updateModel();jX.info(`Model updated on all active contexts`,{contextCount:this.contexts.size})}async reloadAllSkills(){let e=[];for(let[t,n]of this.contexts){let r=this.tabs.get(t);(r?.status===`ready`||r?.status===`processing`)&&e.push(n.reloadSkills().catch(e=>{jX.warn(`Failed to reload skills for scoop`,{jid:t,error:e instanceof Error?e.message:String(e)})}))}await Promise.all(e),jX.info(`Skills reloaded across all contexts`,{count:e.length})}async setThinkingLevel(e,t,n){let r=this.deps.getScoops().get(e);if(!r)return null;let i=this.contexts.get(e),a=i?i.setThinkingLevel(t,n):null;if(t===void 0){if(r.config&&r.config.thinkingLevel!==void 0){let{thinkingLevel:e,effortOverride:t,...n}=r.config;r.config=n}}else r.config={...r.config??{},thinkingLevel:t,effortOverride:n};try{await this.deps.db.saveScoop(r)}catch(t){jX.warn(`Failed to persist thinkingLevel`,{jid:e,error:t instanceof Error?t.message:String(t)})}return a}buildContextCallbacks(e,t){let{callbacks:n,completionService:r,cone:i}=this.deps,a=()=>this.deps.getScoops();return{onResponse:(i,o)=>{a().has(e)&&(n.onResponse(e,i,o),this.dispatch(e,`onResponse`,i,o),t.isCone||(o?r.appendResponseChunk(e,i):r.setResponseFull(e,i)))},onResponseDone:()=>{if(!a().has(e))return;let t=this.tabs.get(e);t&&(t.lastActivity=new Date().toISOString(),this.tabs.set(e,t)),n.onResponseDone(e)},onError:r=>{if(!a().has(e))return;let i=this.tabs.get(e);i&&(i.status=`error`,i.error=r,this.tabs.set(e,i)),zr(`error`,t.folder,r),n.onError(e,r),n.onStatusChange(e,`error`),this.dispatch(e,`onError`,r),this.dispatch(e,`onStatusChange`,`error`)},onFatalError:t=>this.handleFatalError(e,t),onStatusChange:i=>{if(!a().has(e))return;let o=this.tabs.get(e);o&&(o.status=i,o.lastActivity=new Date().toISOString(),this.tabs.set(e,o)),n.onStatusChange(e,i),this.dispatch(e,`onStatusChange`,i),i===`ready`&&!t.isCone&&r.notifyCompletion(e)},onCompactionStateChange:t=>{n.onCompactionStateChange?.(e,t)},onToolStart:(t,r)=>{n.onToolStart?.(e,t,r)},onToolEnd:(t,r,i)=>{n.onToolEnd?.(e,t,r,i)},onToolUI:(t,r,i)=>{n.onToolUI?.(e,t,r,i)},onToolUIDone:t=>{n.onToolUIDone?.(e,t)},onSendMessage:(t,r)=>{let i=`${r?`[${r}] `:``}${t}`;n.onSendMessage(e,i),this.dispatch(e,`onSendMessage`,t)},getScoops:()=>i.getScoops(),getScoopTabState:t.isCone?e=>this.tabs.get(e):void 0,onFeedScoop:t.isCone?(e,n)=>i.delegateToScoop(e,n,t.assistantLabel):void 0,onScoopScoop:t.isCone?async e=>{let t={...e,jid:`scoop_${e.folder}_${Date.now()}`};return await i.registerScoop(t),t}:void 0,onDropScoop:t.isCone?async e=>{await i.unregisterScoop(e)}:void 0,onMuteScoops:t.isCone?e=>i.muteScoops(e):void 0,onUnmuteScoops:t.isCone?e=>i.unmuteScoops(e):void 0,onScheduleScoopWait:t.isCone?(e,t)=>i.scheduleScoopWait(e,t):void 0,getGlobalMemory:()=>i.getGlobalMemory(),setGlobalMemory:t.isCone?e=>i.setGlobalMemory(e):void 0,appendConeMemory:t.isCone?(e,t)=>i.appendConeMemory(e,t):void 0,onSudoRequest:t.isCone?void 0:t=>i.enqueueSudoRequest(e,t),onSudoResolve:t.isCone?(e,t)=>i.resolveActionableLick(e,t):void 0,onListSudoRequests:t.isCone?()=>i.listPendingSudoRequests():void 0,getBrowserAPI:()=>n.getBrowserAPI()}}handleFatalError(e,t){let n=this.deps.getScoops();if(!n.has(e))return;let r=n.get(e);jX.error(`Fatal scoop error`,{jid:e,folder:r.folder,error:t}),zr(`error`,r.folder,t);let i=this.tabs.get(e);if(i&&(i.status=`error`,i.error=t,this.tabs.set(e,i)),this.deps.callbacks.onError(e,t),this.deps.callbacks.onStatusChange(e,`error`),this.dispatch(e,`onError`,t),this.dispatch(e,`onStatusChange`,`error`),r.isCone)return;this.deps.completionService.forgetScoop(e,`fatal-error`);let a=Array.from(n.values()).find(e=>e.isCone);if(!a)return;let o={id:`scoop-error-${e}-${Date.now()}`,chatJid:a.jid,senderId:r.folder,senderName:r.assistantLabel,content:`[@${r.assistantLabel} FAILED]: ${t}`,timestamp:new Date().toISOString(),fromAssistant:!1,channel:`scoop-error`};try{this.deps.callbacks.onIncomingMessage?.(a.jid,o)}catch(e){jX.warn(`onIncomingMessage for scoop-error threw`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})}this.deps.handleMessage(o).catch(e=>{jX.error(`Failed to route fatal error to cone`,{scoop:r.folder,error:e instanceof Error?e.message:String(e)})})}};const NX=n(`scoop-message-router`);var PX=class{deps;messageQueues=new Map;lastAgentTimestamp=new Map;pollInterval=null;constructor(e){this.deps=e}ensureQueue(e){this.messageQueues.has(e)||this.messageQueues.set(e,[])}setLastAgentTimestamp(e,t){this.lastAgentTimestamp.set(e,t)}forgetScoop(e){this.messageQueues.delete(e),this.lastAgentTimestamp.delete(e)}async handleMessage(e){if(NX.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){NX.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}`);zr(`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),NX.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);NX.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){NX.info(`routeToScoop: unregistered target`,{chatJid:e.chatJid});return}let n=e.channel===`webhook`||e.channel===`cron`||e.channel===`fswatch`||e.channel===`sprinkle`;if(!t.isCone&&t.requiresTrigger&&t.trigger&&!n&&!e.content.includes(t.trigger)){NX.info(`routeToScoop: trigger not found in content`,{chatJid:e.chatJid,trigger:t.trigger,contentPreview:e.content.slice(0,80)});return}let r=this.messageQueues.get(e.chatJid)??[];r.push(e),this.messageQueues.set(e.chatJid,r);let i=this.deps.getTabs().get(e.chatJid);if(NX.debug(`routeToScoop: queued`,{chatJid:e.chatJid,scoopName:t.name,tabStatus:i?.status??`no-tab`,queueLength:r.length}),i?.status===`error`){NX.info(`routeToScoop: tab in error state, retrying init`,{chatJid:e.chatJid});try{await this.deps.createScoopTab(e.chatJid),i=this.deps.getTabs().get(e.chatJid)}catch{NX.warn(`routeToScoop: retry init failed`,{chatJid:e.chatJid})}}i?.status===`ready`&&await this.processScoopQueue(e.chatJid)}async processScoopQueue(e){let t=this.messageQueues.get(e);if(!t||t.length===0){NX.debug(`processScoopQueue: empty queue`,{jid:e});return}let n=this.deps.getTabs().get(e);if(n?.status!==`ready`){NX.debug(`processScoopQueue: tab not ready`,{jid:e,status:n?.status??`no-tab`});return}let r=this.deps.getScoops().get(e),i=r?.assistantLabel??e,a=this.lastAgentTimestamp.get(e)??``,o=await this.deps.db.getMessagesSince(e,a,i);if(NX.debug(`processScoopQueue: DB query`,{jid:e,scoopName:r?.name,excludeName:i,since:a,dbMessageCount:o.length,queueLength:t.length}),o.length===0){NX.debug(`processScoopQueue: no messages from DB, clearing queue`,{jid:e}),this.messageQueues.set(e,[]);return}let s=o.map(e=>`[${new Date(e.timestamp).toLocaleString(`en-US`,{month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,hour12:!0})}] ${e.senderName}: ${wi(e.content,e.attachments)}`).join(`
|
|
8750
|
+
`),c=o.flatMap(e=>Ti(e.attachments));this.messageQueues.set(e,[]);let l=o[o.length-1];this.lastAgentTimestamp.set(e,l.timestamp),await this.deps.db.setState(`lastAgentTs_${e}`,l.timestamp),await this.deps.sendPrompt(e,s,l.senderId,l.senderName,c)}startMessageLoop(){this.pollInterval||=setInterval(()=>{for(let e of this.deps.getScoops().keys())this.deps.getTabs().get(e)?.status===`ready`&&this.processScoopQueue(e).catch(t=>{let n=t instanceof Error?t.message:String(t);NX.error(`Message queue processing failed`,{jid:e,error:n}),this.deps.onError(e,`Queue processing failed: ${n}`)})},2e3)}stopMessageLoop(){this.pollInterval&&=(clearInterval(this.pollInterval),null)}async clearScoopMessages(e,t){if(t){t.clearMessages();let n=this.deps.getSessionStore();if(n){let r=t.getSessionId();await n.delete(r).catch(t=>{NX.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=>{NX.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,[]),NX.info(`Scoop messages cleared`,{jid:e})}async clearAllMessages(){await this.deps.db.clearAllMessages();let e=this.deps.getSessionStore();e&&await e.clearAll().catch(e=>{NX.warn(`Failed to clear agent sessions`,{error:e instanceof Error?e.message:String(e)})});for(let e of this.deps.getContexts().values())e.clearMessages();this.lastAgentTimestamp.clear();for(let e of this.deps.getScoops().keys())this.messageQueues.set(e,[]);this.deps.resetCostTracker(),NX.info(`All messages cleared`)}async clearQueuedMessages(e){let t=this.messageQueues.get(e);if(t&&t.length>0){for(let e of t)await this.deps.db.deleteMessage(e.id);this.messageQueues.set(e,[])}}async deleteQueuedMessage(e,t){let n=this.messageQueues.get(e);if(n){let e=n.findIndex(e=>e.id===t);e!==-1&&n.splice(e,1)}await this.deps.db.deleteMessage(t)}};const FX=n(`orchestrator`);var IX=class{scoops=new Map;container;callbacks;config;scheduler=null;sharedFs=null;memoryStore=new jo({getSharedFs:()=>this.sharedFs});lickManager=null;sessionStore=null;fsWatcher=null;sudoManager=null;lifecycle;idleTimers=new Qo({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),handleMessage:e=>this.handleMessage(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t)});costTracker=new Xo({getScoops:()=>this.scoops,getContexts:()=>this.lifecycle.getContexts()});completionService=new Ko({getSharedFs:()=>this.sharedFs,getScoop:e=>this.scoops.get(e),findCone:()=>Array.from(this.scoops.values()).find(e=>e.isCone),hasScoop:e=>this.scoops.has(e),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),handleMessage:e=>this.handleMessage(e),reportError:(e,t)=>this.callbacks.onError(e,t)});processManager=null;approvalRouter=new Ro({getScoops:()=>this.scoops,getSudoManager:()=>this.sudoManager,getLickManager:()=>this.lickManager,handleMessage:e=>this.handleMessage(e),onMessageUpdate:(e,t)=>this.callbacks.onMessageUpdate?.(e,t),getMessagesForScoop:e=>De(e),saveMessage:e=>be(e)});lickRegistry=new Po({getConeShell:()=>{let e=Array.from(this.scoops.values()).find(e=>e.isCone);return e?this.lifecycle.getContext(e.jid)?.getShell()??null:null},persistLickDecision:(e,t)=>this.approvalRouter.persistLickDecision(e,t)});messageRouter=new PX({getScoops:()=>this.scoops,getTabs:()=>this.lifecycle.getTabsMap(),getContexts:()=>this.lifecycle.getContexts(),createScoopTab:e=>this.createScoopTab(e),sendPrompt:(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i??[]),notifyIncomingMessage:(e,t)=>this.callbacks.onIncomingMessage?.(e,t),onError:(e,t)=>this.callbacks.onError(e,t),getSessionStore:()=>this.sessionStore,resetCostTracker:()=>this.costTracker.reset(),db:{saveMessage:e=>be(e),deleteMessage:e=>W(e),clearMessagesForScoop:e=>Te(e),clearAllMessages:()=>Oe(),getMessagesSince:(e,t,n)=>we(e,t,n),setState:(e,t)=>je(e,t)},isExternalLickChannel:Vn});constructor(e,t,n={name:`sliccy`,triggerPattern:/^@sliccy\b/i}){this.container=e,this.callbacks=t,this.config=n,this.lifecycle=new MX({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=>Me(e),deleteScoop:e=>ye(e)},getLickManager:()=>this.lickManager,buildActiveLicksError:(e,t,n)=>et(e,t,n),messageRouter:{ensureQueue:e=>this.messageRouter.ensureQueue(e),forgetScoop:e=>this.messageRouter.forgetScoop(e)},costTracker:{snapshot:e=>this.costTracker.snapshot(e)},approvalRouter:{failScoop:e=>this.approvalRouter.failScoop(e)},cone:{delegateToScoop:(e,t,n)=>this.delegateToScoop(e,t,n),registerScoop:e=>this.registerScoop(e),unregisterScoop:e=>this.unregisterScoop(e),muteScoops:e=>this.muteScoops(e),unmuteScoops:e=>this.unmuteScoops(e),scheduleScoopWait:(e,t)=>this.scheduleScoopWait(e,t),getScoops:()=>this.getScoops(),getGlobalMemory:()=>this.getGlobalMemory(),setGlobalMemory:e=>this.setGlobalMemory(e),appendConeMemory:(e,t)=>this.appendConeMemory(e,t),enqueueSudoRequest:(e,t)=>this.enqueueSudoRequest(e,t),resolveActionableLick:(e,t)=>this.resolveActionableLick(e,t),listPendingSudoRequests:()=>this.listPendingSudoRequests()},handleMessage:e=>this.handleMessage(e)})}setProcessManager(e){this.processManager=e}getProcessManager(){return this.processManager}async init(){await Ae(),this.sharedFs=await ut.create({dbName:`slicc-fs`}),this.sessionStore=new Oi,this.fsWatcher=new lt,this.sharedFs.setWatcher(this.fsWatcher),globalThis.__slicc_fs_watcher=this.fsWatcher,await this.ensureRootStructure(),this.sudoManager=new Fa({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init();let e=await Ce();for(let t of Object.values(e)){t.isCone&&(t.trigger=void 0,t.requiresTrigger=!1,t.assistantLabel=t.assistantLabel||`sliccy`),this.migrateScoopConfig(t),this.scoops.set(t.jid,t),this.messageRouter.ensureQueue(t.jid);let e=await Se(`lastAgentTs_${t.jid}`);e&&this.messageRouter.setLastAgentTimestamp(t.jid,e)}await this.memoryStore.ensureGlobalMemory(),await this.memoryStore.migrateLegacyConeMemory(),this.scheduler=new Io({onTaskRun:async(e,t)=>{FX.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(),FX.info(`Orchestrator initialized`,{scoopCount:this.scoops.size});for(let e of this.scoops.values())try{await this.createScoopTab(e.jid)}catch(t){let n=t instanceof Error?t.message:String(t);FX.warn(`Skipping scoop whose context failed to initialize during boot`,{jid:e.jid,folder:e.folder,isCone:e.isCone,error:n}),e.isCone||this.lifecycle.markTabError(e.jid,n)}gt(()=>this.getSessionCosts()),this.messageRouter.startMessageLoop()}migrateScoopConfig(e){if(e.isCone)return;let t=e.configSchemaVersion??0;t>=2||(t<1&&(e.config={...e.config,visiblePaths:e.config?.visiblePaths??[`/workspace/`]}),t<2&&(e.config={...e.config,writablePaths:e.config?.writablePaths??[`/scoops/${e.folder}/`,`/shared/`]}),e.configSchemaVersion=2)}async ensureRootStructure(){if(this.sharedFs)for(let e of[`/workspace`,`/shared`,`/scoops`,`/home`,`/tmp`,`/mnt`])try{await this.sharedFs.mkdir(e,{recursive:!0})}catch{}}getGlobalMemory(){return this.memoryStore.getGlobalMemory()}setGlobalMemory(e){return this.memoryStore.setGlobalMemory(e)}appendConeMemory(e,t){return this.memoryStore.appendConeMemory(e,t)}getSharedFS(){return this.sharedFs}getSessionStore(){return this.sessionStore}getSudoManager(){return this.sudoManager}setLickManager(e){this.lickManager=e,e.setScoopExistenceResolver(e=>this.getScoops().some(t=>Ze(e,t.name,t.folder))),globalThis.__slicc_lick_handler=e=>{this.lickManager?.emitEvent(e)}}handleWebhookEvent(e,t,n){this.lickManager?.handleWebhookEvent(e,t,n)}handleCherryHostEvent(e,t,n){this.lickManager?.emitEvent({type:`cherry`,cherryRuntimeId:e,cherryName:t,cherryOrigin:void 0,body:n,timestamp:new Date().toISOString()})}handlePreviewLick(e){this.lickManager?.emitEvent(e)}observeScoop(e,t){return this.lifecycle.observe(e,t)}muteScoops(e){this.completionService.muteScoops(e)}unmuteScoops(e){return this.completionService.unmuteScoops(e)}isScoopMuted(e){return this.completionService.isScoopMuted(e)}waitForScoops(e,t){return this.completionService.waitForScoops(e,t)}scheduleScoopWait(e,t){return this.completionService.scheduleScoopWait(e,t)}async enqueueSudoRequest(e,t){return this.approvalRouter.enqueueSudoRequest(e,t)}resolveSudoRequest(e,t){return this.approvalRouter.resolveSudoRequest(e,t)}async resolveSudoRequestAndPersist(e,t){return this.approvalRouter.resolveSudoRequestAndPersist(e,t)}registerNavigateLick(e){return this.lickRegistry.registerNavigate(e)}registerSessionReloadLick(e){return this.lickRegistry.registerSessionReload(e)}registerUpgradeLick(e){return this.lickRegistry.registerUpgrade(e)}async resolveActionableLick(e,t){return await this.lickRegistry.resolve(e,t)||this.resolveSudoRequestAndPersist(e,t)}async resolveNavigateHandoffByHuman(e,t){return this.lickRegistry.resolveHandoffByHuman(e,t)}getConeSudoBroker(e){return this.approvalRouter.getConeSudoBroker(e)}listPendingSudoRequests(){return this.approvalRouter.listPendingSudoRequests()}registerScoop(e){return this.lifecycle.register(e)}unregisterScoop(e){return this.lifecycle.unregister(e)}getScoops(){return Array.from(this.scoops.values())}getScoop(e){return this.scoops.get(e)}async resetFilesystem(){this.lifecycle.stopAndClearAllContexts(),this.sharedFs=await ut.create({dbName:`slicc-fs`,wipe:!0}),this.fsWatcher&&this.sharedFs.setWatcher(this.fsWatcher),await this.ensureRootStructure(),await this.memoryStore.ensureGlobalMemory(),await Do(this.sharedFs).catch(e=>{FX.warn(`Failed to re-seed default skills`,{error:e instanceof Error?e.message:String(e)})}),this.sudoManager?.dispose(),this.sudoManager=new Fa({fs:this.sharedFs,watcher:this.fsWatcher}),await this.sudoManager.init(),this.costTracker.reset(),FX.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 De(e)}sendPrompt(e,t,n,r,i=[]){return this.lifecycle.sendPrompt(e,t,n,r,i)}stopMessageLoop(){this.messageRouter.stopMessageLoop()}updateModel(){this.lifecycle.updateModelOnAll()}setScoopThinkingLevel(e,t,n){return this.lifecycle.setThinkingLevel(e,t,n)}reloadAllSkills(){return this.lifecycle.reloadAllSkills()}stopScoop(e){this.lifecycle.getContext(e)?.stop()}getSessionCosts(){return this.costTracker.getSessionCosts()}getModelCosts(){return this.costTracker.getModelCosts()}getContextFills(){return this.costTracker.getContextFills()}async shutdown(){this.stopMessageLoop(),this.idleTimers.clearAll(),this.scheduler?.stop(),this.scheduler=null,this.completionService.shutdown();let e=this.approvalRouter.failAll();e>0&&FX.info(`Failed-closed pending sudo requests during shutdown`,{count:e}),await this.lifecycle.destroyAllTabs(),this.sudoManager?.dispose(),this.sudoManager=null,FX.info(`Orchestrator shutdown`)}};function LX(){try{return typeof localStorage>`u`||typeof localStorage?.getItem!=`function`||localStorage.getItem(`slicc_discovery_enabled`)!==`false`}catch{return!0}}var RX=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=BX(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=VX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);return zX.map(e=>({name:e,kind:`file`,size:this.fileSize(n,e),lastModified:this.fileMtime(n)}))}throw new L(`ENOTDIR`,`not a directory`,e)}async readFile(e){this.assertOpen(e);let t=BX(e);if(t.length!==2)throw new L(`EISDIR`,`is a directory`,e);let n=VX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!zX.includes(r))throw new L(`ENOENT`,`no such file or directory`,e);let i=this.renderProcFile(n,r);return new TextEncoder().encode(i)}async writeFile(e){throw new L(`EACCES`,`read-only filesystem`,e)}async stat(e){this.assertOpen(e);let t=BX(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};if(t.length===1){let n=VX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);return{kind:`directory`,size:0,mtime:this.fileMtime(n)}}if(t.length===2){let n=VX(t[0]);if(n===null||!this.pidExists(n))throw new L(`ENOENT`,`no such file or directory`,e);let r=t[1];if(!zX.includes(r))throw new L(`ENOENT`,`no such file or directory`,e);return{kind:`file`,size:this.fileSize(n,r),mtime:this.fileMtime(n)}}throw new L(`ENOENT`,`no such file or directory`,e)}async mkdir(e){throw new L(`EACCES`,`read-only filesystem`,e)}async remove(e){throw new L(`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 L(`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 JX(t);let n=this.pm.get(e);switch(t){case`status`:return HX(n);case`cmdline`:return UX(n);case`cwd`:return WX(n);case`stat`:return GX(n)}}};const zX=[`status`,`cmdline`,`cwd`,`stat`];function BX(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean)}function VX(e){let t=Number.parseInt(e,10);return!Number.isFinite(t)||String(t)!==e?null:t}function HX(e){let t=[`Name:\t${e.kind}`,`Pid:\t${e.pid}`,`PPid:\t${e.ppid}`,`State:\t${KX(e.status)} (${e.status})`,`Owner:\t${qX(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(`
|
|
8751
8751
|
`)+`
|
|
8752
|
-
`}function
|
|
8753
|
-
`}function
|
|
8754
|
-
`}function
|
|
8752
|
+
`}function UX(e){return e.argv.join(`\0`)+`\0`}function WX(e){return e.cwd+`
|
|
8753
|
+
`}function GX(e){return[e.pid,`(${e.kind})`,KX(e.status),e.ppid,e.exitCode??`-`,e.startedAt,e.finishedAt??`-`].join(` `)+`
|
|
8754
|
+
`}function KX(e){switch(e){case`running`:return`R`;case`pending`:return`S`;case`exited`:return`Z`;case`killed`:return`K`}}function qX(e){return e.owner.kind===`cone`?`cone`:e.owner.kind===`system`?`system`:e.owner.scoopJid?`scoop/${e.owner.scoopJid}`:`scoop`}function JX(e){switch(e){case`status`:return[`Name: kernel-host`,`Pid: 1`,`PPid: 0`,`State: R (running)`,`Owner: system`].join(`
|
|
8755
8755
|
`)+`
|
|
8756
8756
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
8757
8757
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
8758
|
-
`}}function
|
|
8759
|
-
`,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 BX(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C_bJMGw6.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 VX(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 _i(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})},HX(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function HX(e){let t=l();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>yX()}}function UX(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-BHHDw9yC.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function WX(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-DIIyklC5.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 GX(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function KX(){return S()}async function qX(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await FX(t,n,r,i);if(d?Vi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new bX(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await IX(c,e,o);d&&RX({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await zX({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;KX()&&(h=await BX(f,o,e.localLickWsUrl??null));let g=VX(n,f,o);d&&UX(d,f,o),a||await LX(c),d&&WX(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await GX(d,n,o));let y=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){y||(y=!0,await JX({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function JX(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.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)}YX({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function YX(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[Qq]}const XX=`x-bypass-llm-proxy`;function ZX(e,t,n){return t?(r,i)=>{if(!QX(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(XX)||a.set(XX,`1`),e(r,{...i,headers:a})}:e}function QX(e,t,n){if(eZ(e,t))return!0;let r=n?.()??null;return r?$X(e,r,t):!1}function $X(e,t,n){let r=tZ(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 eZ(e,t){let n=tZ(e);try{return new URL(n,t).origin===t}catch{return!0}}function tZ(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function nZ(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 rZ=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(!iZ(e)||e.source!==`panel`)return;let t=e.payload;oZ(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?aZ(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,aZ(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 iZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function aZ(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function oZ(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 sZ=class extends nY{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 cZ(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new rZ({transport:t,processManager:i,createShell:(e,a)=>new sZ(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function lZ(e){let t=new uZ(e);return t.start(),{stop:()=>t.dispose()}}var uZ=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(!dZ(e)||e.source!==`panel`)return;let t=e.payload;if(fZ(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(pZ(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 L(`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 L(`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(mZ(e.type),e.requestId,new L(`EACCES`,`vfs-rpc-host has no writable backend wired`),hZ(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 L(`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 L(`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 L(`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=gZ(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=gZ(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 dZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function fZ(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 pZ(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 mZ(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 hZ(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function gZ(e,t){return e instanceof L?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function _Z(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=ZX(e.bind(globalThis),t,vZ)}function vZ(){let e=o();if(!e)return null;try{return new URL(e).origin}catch{return null}}function yZ(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 bZ=null,xZ=null,SZ=null,CZ=null,wZ=null;const TZ=nZ(e=>EZ(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&TZ.handle(e.data)});async function EZ(e){jr(e.instanceId);try{_Z(),s(e.localApiBaseUrl??null),p(e.bridgeToken??null),r(e.extensionDelegateId??null),yZ(e.localStorageSeed??{}),Zr().catch(()=>{}),await Ge();let t=li(e.kernelPort),n=new dr(t),i=dr.createCallbacks(n),a=new ui(e.cdpPort);await a.connect();let o=new xr(a);bZ=await qX({container:{},browser:o,bridge:n,callbacks:i,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=bZ.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.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)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);wZ=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=wZ,o.setTrayTargetProvider(Dr(He));let f=await DZ({host:bZ,transport:t,browser:o,instanceId:e.instanceId});f&&(xZ=f.stopTerminalHost,SZ=f.stopVfsRpcHost,CZ=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Nr(e),e}}async function DZ(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=cZ({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=lZ({transport:e.transport,client:t,writableClient:t,logger:console}),i=await OZ(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function OZ(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-D2Pclall.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(xZ?.(),xZ=null,SZ?.(),SZ=null,CZ?.(),CZ=null,wZ?.dispose(),wZ=null,bZ?.dispose())});
|
|
8758
|
+
`}}function YX(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 XX(e){let t=IO(e.token);if(!t)return{ok:!1,errno:`EACCES`,message:`sync-fs: unknown or revoked token`};let{fs:n,cwd:r}=t;try{let t=n.resolvePath(r,e.path);switch(e.op){case`read`:return{ok:!0,kind:`bytes`,bytes:await n.readFileBuffer(t)};case`write`:return await n.writeFile(t,e.body??new Uint8Array),{ok:!0,kind:`void`};case`exists`:return{ok:!0,kind:`json`,json:await n.exists(t)};case`stat`:{let e=await n.stat(t);return{ok:!0,kind:`json`,json:{isDirectory:e.isDirectory,isFile:e.isFile,size:e.size}}}case`readdir`:return{ok:!0,kind:`json`,json:await n.readdir(t)};case`mkdir`:return await n.mkdir(t,{recursive:!0}),{ok:!0,kind:`void`};case`rm`:return await n.rm(t,{recursive:!0}),{ok:!0,kind:`void`};case`rename`:{let i=n.resolvePath(r,e.arg2??``),a=n;if(a.rename)await a.rename(t,i);else if(a.mv)await a.mv(t,i);else{let e=await n.readFileBuffer(t);await n.writeFile(i,e),await n.rm(t,{recursive:!0})}return{ok:!0,kind:`void`}}default:return{ok:!1,errno:`EINVAL`,message:`sync-fs: unknown op '${e.op}'`}}}catch(e){return YX(e)}}function ZX(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(eT(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(!IO(n.token))return;let a=i.get(n.id);if(a){r({type:tT,id:n.id}),a.result&&r({type:nT,id:n.id,...a.result});return}let o={};i.set(n.id,o),r({type:tT,id:n.id});let s=e=>{o.result=e,o.timer=setTimeout(()=>i.delete(n.id),3e4),r({type:nT,id:n.id,...e})};XX(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 QX(e){switch(e.type){case`webhook`:return e.webhookName;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchName;case`navigate`:return e.navigateUrl;case`upgrade`:return`${e.upgradeFromVersion??`unknown`}→${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`mount-recovery`;case`workflow`:return e.workflowName??e.workflowRunId??`workflow`;case`preview`:return e.previewOrigin??`preview`;case`discovery`:return e.discoveryUrl??e.discoveryOrigin;default:return e.cronName}}function $X(e){switch(e.type){case`webhook`:return e.webhookId;case`sprinkle`:return e.sprinkleName;case`fswatch`:return e.fswatchId;case`navigate`:return e.navigateUrl;case`upgrade`:return`upgrade-${e.upgradeToVersion??`unknown`}`;case`session-reload`:return`session-reload-${e.timestamp}`;case`workflow`:return`workflow-${e.workflowRunId??`unknown`}`;case`preview`:return e.previewConnId??`preview-${e.timestamp}`;case`discovery`:return e.discoveryUrl??`discovery-${e.timestamp}`;default:return e.cronId}}function eZ(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}tZ(e,t)}function tZ(e,{orchestrator:t,log:n}){e.type===`navigate`?e.lickId=t.registerNavigateLick(e):e.type===`session-reload`?e.lickId=t.registerSessionReloadLick(e):e.type===`upgrade`&&(e.lickId=t.registerUpgradeLick(e));let r=er(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=QX(e),a=$X(e),o=e.type,s=t.getScoops(),c;if(c=e.targetScoop?s.find(t=>t.name===e.targetScoop||t.folder===e.targetScoop||t.folder===`${e.targetScoop}-scoop`):s.find(e=>e.isCone),!c){n.warn(`Lick target scoop not found`,e.targetScoop);return}let l={id:`${o}-${a}-${Date.now()}`,chatJid:c.jid,senderId:o,senderName:`${o}:${i}`,content:r.content,timestamp:e.timestamp,fromAssistant:!1,channel:o,...e.lickId?{lickId:e.lickId}:{}};t.handleMessage(l)}async function nZ(e,t,n,r){let i=new Qt,a=new IX(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=Be(()=>n.emitTrayRuntimeStatus()),s=ar(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function rZ(e,t,n){let{registerSessionCostsProvider:r}=await import(`./cost-command-Cpg2Em0Q.js`).then(e=>e.t);r(()=>e.getSessionCosts());let{getLickManager:i}=await import(`./lick-manager-Ct3WOtut.js`).then(e=>e.r),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??eZ,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function iZ(e){e.getScoops().some(e=>e.isCone)||await e.registerScoop({jid:`cone_${Date.now()}`,name:`Cone`,folder:`cone`,isCone:!0,type:`cone`,requiresTrigger:!1,assistantLabel:`sliccy`,addedAt:new Date().toISOString()})}function aZ(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;bJ({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>Lk(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>OJ().slice(10,22),splitResult:(e,t)=>MJ(e,t)})}async function oZ(e){let{browser:t,lickManager:n,orchestrator:r,sharedFs:i,log:a}=e,{CdpWsPageBridge:o}=await import(`./cdp-ws-page-bridge-D_PY6ku1.js`),{WsSubscriberRegistry:s}=await import(`./ws-subscribers-Dzuxa2F7.js`),c=new o({browser:t});return{wsBridge:c,wsRegistry:new s({bridge:c,webhooks:{has:e=>n.getWebhook(e)!==void 0},dispatcher:{webhook:(e,t)=>{n.handleWebhookEvent(e,{},t)},scoop:(e,t)=>{if(!r.getScoops().find(t=>t.jid===e)){a.warn?.(`browser.websocket: scoop sink not found`,{jid:e});return}let n={id:`ws-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,chatJid:e,senderId:`browser.websocket`,senderName:`browser.websocket`,content:typeof t==`string`?t:JSON.stringify(t,null,2),timestamp:new Date().toISOString(),fromAssistant:!1,channel:`browser.websocket`};r.handleMessage(n)},vfs:async(e,t)=>{if(!i)return;let n=(typeof t==`string`?t:JSON.stringify(t))+`
|
|
8759
|
+
`,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 sZ(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-C_bJMGw6.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 cZ(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 _i(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})},lZ(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function lZ(e){let t=l();return{onDiscovery:t=>{e.emitEvent({type:`discovery`,targetScoop:void 0,timestamp:new Date().toISOString(),discoveryOrigin:t.origin,discoveryKind:t.kind,discoveryUrl:t.url,body:{origin:t.origin,kind:t.kind,url:t.url,targetId:t.targetId}})},probeFetch:async(e,n)=>{let r=t(e,{method:n?.method??`GET`}),i=n?.signal,a=i?await Promise.race([r,new Promise((e,t)=>{if(i.aborted){t(Error(`aborted`));return}i.addEventListener(`abort`,()=>t(Error(`aborted`)),{once:!0})})]):await r,o=a.headers;return{ok:a.status>=200&&a.status<300,status:a.status,headers:{get(e){return o?o[e.toLowerCase()]??o[e]??null:null}}}},isDiscoveryEnabled:()=>LX()}}function uZ(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-CTrzlrNn.js`).then(e=>e.r),{recoverMounts:i}=await import(`./mount-recovery-Cwl9npdz.js`).then(e=>e.n),a=await r();if(a.length===0)return;let{needsRecovery:o}=await i(a,e,n);if(o.length===0)return;t.emitEvent({type:`session-reload`,targetScoop:void 0,timestamp:new Date().toISOString(),body:{reason:`mount-recovery`,mounts:o}})}catch(e){n.warn(`mount recovery failed`,e)}})()}function dZ(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-B6AiyIwx.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 fZ(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await import(`./script-catalog-BYXhqRAc.js`).then(e=>e.n),i=new r({jshFs:e,bshFs:e,watcher:e.getWatcher()}),a=new n({browserAPI:t,scriptCatalog:i,fs:e});return a.start(),{bshWatchdogStop:()=>a.stop(),scriptCatalogDispose:()=>i.dispose()}}catch(e){return n.warn(`Failed to start BSH watchdog`,e),{bshWatchdogStop:null,scriptCatalogDispose:null}}}function pZ(){return S()}async function mZ(e){let{container:t,browser:n,bridge:r,callbacks:i,skipConeBootstrap:a=!1}=e,o=e.logger??console,{processManager:s,orchestrator:c,unsubLeader:l,unsubFollower:u,sharedFs:d}=await nZ(t,n,r,i);if(d?Vi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new RX(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await rZ(c,e,o);d&&aZ({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await oZ({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;pZ()&&(h=await sZ(f,o,e.localLickWsUrl??null));let g=cZ(n,f,o);d&&uZ(d,f,o),a||await iZ(c),d&&dZ(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await fZ(d,n,o));let y=null;d&&e.syncFsChannelNonce&&(y=ZX({nonce:e.syncFsChannelNonce}).dispose);let b=!1;return{orchestrator:c,browser:n,bridge:r,lickManager:f,sharedFs:d??null,processManager:s,async dispose(){b||(b=!0,await hZ({unsubLeader:l,unsubFollower:u,bshWatchdogStop:_,scriptCatalogDispose:v,lickWsBridgeStop:h,navigationWatcherStop:g,syncFsResponderDispose:y,sharedFs:d,wsRegistry:m,wsBridge:p,processManager:s,lickManager:f,browser:n,log:o}))}}}async function hZ(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)}gZ({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function gZ(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[gJ]}const _Z=`x-bypass-llm-proxy`;function vZ(e,t,n){return t?(r,i)=>{if(!yZ(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(_Z)||a.set(_Z,`1`),e(r,{...i,headers:a})}:e}function yZ(e,t,n){if(xZ(e,t))return!0;let r=n?.()??null;return r?bZ(e,r,t):!1}function bZ(e,t,n){let r=SZ(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 xZ(e,t){let n=SZ(e);try{return new URL(n,t).origin===t}catch{return!0}}function SZ(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function CZ(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 wZ=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(!TZ(e)||e.source!==`panel`)return;let t=e.payload;DZ(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?EZ(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,EZ(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 TZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function EZ(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function DZ(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 OZ=class extends bY{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 kZ(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new wZ({transport:t,processManager:i,createShell:(e,a)=>new OZ(e,t,{fs:n,cwd:a.cwd,env:a.env,browserAPI:r,processManager:i,processOwner:{kind:`system`},sudo:s}),logger:o});return{host:c,stop:c.start()}}function AZ(e){let t=new jZ(e);return t.start(),{stop:()=>t.dispose()}}var jZ=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(!MZ(e)||e.source!==`panel`)return;let t=e.payload;if(NZ(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(PZ(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 L(`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 L(`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(FZ(e.type),e.requestId,new L(`EACCES`,`vfs-rpc-host has no writable backend wired`),IZ(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 L(`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 L(`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 L(`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=LZ(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=LZ(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 MZ(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function NZ(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 PZ(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 FZ(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 IZ(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function LZ(e,t){return e instanceof L?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function RZ(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=vZ(e.bind(globalThis),t,zZ)}function zZ(){let e=o();if(!e)return null;try{return new URL(e).origin}catch{return null}}function BZ(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 VZ=null,HZ=null,UZ=null,WZ=null,GZ=null;const KZ=CZ(e=>qZ(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&KZ.handle(e.data)});async function qZ(e){jr(e.instanceId);try{RZ(),s(e.localApiBaseUrl??null),p(e.bridgeToken??null),jk(e.syncFsBridgeEnabled??!1),r(e.extensionDelegateId??null),BZ(e.localStorageSeed??{}),Zr().catch(()=>{}),await Ge();let t=li(e.kernelPort),n=new dr(t),i=dr.createCallbacks(n),a=new ui(e.cdpPort);await a.connect();let o=new xr(a);VZ=await mZ({container:{},browser:o,bridge:n,callbacks:i,logger:console,localLickWsUrl:e.localLickWsUrl??null,syncFsChannelNonce:e.syncFsChannelNonce??null});let{createSprinkleManagerProxyOverChannel:c}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),l=c({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=l;let u=VZ.sharedFs?.getWatcher();if(u){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)u.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)l.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:d}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);GZ=d({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=GZ,o.setTrayTargetProvider(Dr(He));let f=await JZ({host:VZ,transport:t,browser:o,instanceId:e.instanceId});f&&(HZ=f.stopTerminalHost,UZ=f.stopVfsRpcHost,WZ=f.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Nr(e),e}}async function JZ(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=kZ({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=AZ({transport:e.transport,client:t,writableClient:t,logger:console}),i=await YZ(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function YZ(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-D2Pclall.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-sbHa3Tte.js`).then(e=>e.a),a=i();return n({instanceId:t,ensure:t=>r({fs:e,fetch:a},t)})}self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-shutdown`&&(HZ?.(),HZ=null,UZ?.(),UZ=null,WZ?.(),WZ=null,GZ?.dispose(),GZ=null,VZ?.dispose())});
|