sliccy 5.57.0 → 5.57.1
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-CEVSQiDX.js → account-store-B70B-Xy1.js} +2 -2
- package/dist/ui/assets/{account-store-CiUrO2oO.js → account-store-BqI_bdKc.js} +1 -1
- package/dist/ui/assets/{adobe-vjUIJSuz.js → adobe-DkCnsZQc.js} +1 -1
- package/dist/ui/assets/{adobe-oauth-state-Duf65tF_.js → adobe-oauth-state-DPaR8NRp.js} +1 -1
- package/dist/ui/assets/{adobe-2u5YgpqD.js → adobe-xeGFGZpC.js} +1 -1
- package/dist/ui/assets/{agent-message-to-chat-C3cZZEnY.js → agent-message-to-chat-DzRXXJel.js} +1 -1
- package/dist/ui/assets/{apps-Xr2HxvXF.js → apps-DpqSNSYV.js} +1 -1
- package/dist/ui/assets/{azure-openai-BR4NBU1S.js → azure-openai-Bn3boHbY.js} +1 -1
- package/dist/ui/assets/{azure-openai-DQsuTqRc.js → azure-openai-DEBv7yQp.js} +1 -1
- package/dist/ui/assets/{cerebras-De8Z8J0X.js → cerebras-BwqdpIyz.js} +1 -1
- package/dist/ui/assets/{cerebras-DZlKKnms.js → cerebras-DWHxltur.js} +1 -1
- package/dist/ui/assets/clipboard-CSEDRfgj.js +1 -0
- package/dist/ui/assets/{connect-surface-COlfXpaW.js → connect-surface-D6odnHkh.js} +1 -1
- package/dist/ui/assets/dip-Bwzg4JXD.js +1 -0
- package/dist/ui/assets/{dist-DHYPyff4.js → dist-CSrZL2G5.js} +1 -1
- package/dist/ui/assets/{dist-BeXbje4K.js → dist-Dny1G18y.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-DHsIj3AZ.js → ensure-speech-assets-W5QPk6uQ.js} +1 -1
- package/dist/ui/assets/{fs-BA_NlNLk.js → fs-CnhmusOG.js} +2 -2
- package/dist/ui/assets/{fs-BR_pL1Pu.js → fs-D-5giB0a.js} +1 -1
- package/dist/ui/assets/{github-MVL2z3v8.js → github-B29ZCKQg.js} +1 -1
- package/dist/ui/assets/{github-CEe-BrWT.js → github-DzM3FtVD.js} +2 -2
- package/dist/ui/assets/{github-copilot-CTJAedD6.js → github-copilot-C7aAJAqW.js} +1 -1
- package/dist/ui/assets/{github-copilot-mJJDA6yl.js → github-copilot-n309ImF7.js} +1 -1
- package/dist/ui/assets/{hear-Co6m2SFp.js → hear-0Tswpuv7.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-YxHAWyF7.js → js-realm-worker-Bi5UIEMG.js} +1 -1
- package/dist/ui/assets/{kernel-worker-Dw-oab8q.js → kernel-worker-BCW_QlyZ.js} +25 -25
- package/dist/ui/assets/{kokoro-engine-CjStioz-.js → kokoro-engine-CRs8ZEvx.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-uE08lRKe.js → lick-ws-bridge-8McAeIbO.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-BcF8LHQF.js → lick-ws-bridge-D2LfSdTD.js} +1 -1
- package/dist/ui/assets/{local-llm-wpr_CcAM.js → local-llm-Dl9iXPsJ.js} +1 -1
- package/dist/ui/assets/{main-UdqM0h7Y.js → main-6Q7Fb4tw.js} +4 -4
- package/dist/ui/assets/{mount-DDtFtcY1.js → mount-BtjScgjq.js} +2 -2
- package/dist/ui/assets/{mount-Ce1djury.js → mount-NSmYg9GU.js} +1 -1
- package/dist/ui/assets/{new-session-Cmwle_SJ.js → new-session-CLta1Lj7.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-Cd4FYsM_.js → oauth-bootstrap-D-yvRHGz.js} +2 -2
- package/dist/ui/assets/{openai-codex-BL7lwbPQ.js → openai-codex-CB6PdYqU.js} +1 -1
- package/dist/ui/assets/{openai-codex-3RFd2dtu.js → openai-codex-ZCmj450m.js} +1 -1
- package/dist/ui/assets/{page-follower-tray-BsuMLSII.js → page-follower-tray-TKZCNKRZ.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-CFq536w-.js → panel-rpc-handlers-RRddFZTk.js} +2 -2
- package/dist/ui/assets/{provider-WwKzqYBv.js → provider-BWME-twj.js} +1 -1
- package/dist/ui/assets/{provider-BDLBACK7.js → provider-DOjCml56.js} +2 -2
- package/dist/ui/assets/{provider-settings-Co-joDtJ.js → provider-settings-B2s5vgom.js} +1 -1
- package/dist/ui/assets/provider-store-access-CjY49bAL.js +1 -0
- package/dist/ui/assets/provider-store-access-DQ3kqRuy.js +1 -0
- package/dist/ui/assets/{providers-Dq4BfZ-N.js → providers-BQomGz9R.js} +2 -2
- package/dist/ui/assets/{providers-BDH30zTY.js → providers-uyxOwwt4.js} +1 -1
- package/dist/ui/assets/{quick-llm-CV6h2NvJ.js → quick-llm-DHtKMD9z.js} +1 -1
- package/dist/ui/assets/session-freezer-D-7ulfYc.js +1 -0
- package/dist/ui/assets/{speak-MOuTGBj5.js → speak-D5G7KiTT.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-PYCDZeIj.js → sprinkle-manager-nP3g46qO.js} +1 -1
- package/dist/ui/assets/{store-BySJ73L7.js → store-BZTffu8V.js} +1 -1
- package/dist/ui/assets/{sudo-ryTLrYfY.js → sudo-CsZ2DlSz.js} +1 -1
- package/dist/ui/assets/{transformers-env-BhPFrIRH.js → transformers-env-DHJa4RCf.js} +1 -1
- package/dist/ui/assets/{tray-leader-baQbEptu.js → tray-leader-DgTG9H-w.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-BlVLa2FO.js → tray-leave-runtime-uZUZNHVX.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-Djr_fxY8.js → upgrade-detection-i5f6luyi.js} +1 -1
- package/dist/ui/assets/{voice-reply-CF7oVByb.js → voice-reply-C-3rH9oC.js} +1 -1
- package/dist/ui/assets/{wc-attach-Bfk3We4Q.js → wc-attach-BQzDqdAQ.js} +2 -2
- package/dist/ui/assets/{wc-extension-DgVa3eO9.js → wc-extension-DA4ER47a.js} +2 -2
- package/dist/ui/assets/{wc-follower-DRSZd-X5.js → wc-follower-CsQZCsua.js} +3 -3
- package/dist/ui/assets/{wc-live-Bxi8xGiv.js → wc-live-C04ItfnZ.js} +5 -5
- package/dist/ui/assets/{wc-nav-CTOBFIrg.js → wc-nav-DgqufJsO.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Blv6lYeG.js → wc-onboarding-BR7HaQPL.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-mp-DZGDr.js → wc-placeholder-D36A-bB6.js} +3 -3
- package/dist/ui/assets/{wc-settings-BoPLwHEJ.js → wc-settings-CaxJcNwg.js} +3 -3
- package/dist/ui/assets/{wc-shell-KX1I3Q0c.js → wc-shell-B7yKyiZ2.js} +3 -3
- package/dist/ui/assets/{wc-sprinkles-Ee8dnBb5.js → wc-sprinkles-j5hfmEtl.js} +2 -2
- package/dist/ui/assets/{wc-tray-Dx08dZ6k.js → wc-tray-CofjfW_1.js} +2 -2
- package/dist/ui/assets/{whisper-engine-Bu67yIcD.js → whisper-engine-rP8D81pe.js} +1 -1
- package/dist/ui/assets/{xai-grok-i1f6noj7.js → xai-grok-BPagp879.js} +1 -1
- package/dist/ui/assets/{xai-grok-CK7W826t.js → xai-grok-D80aaxGn.js} +1 -1
- package/dist/ui/index.html +3 -3
- package/dist/ui/packages/webapp/index.html +3 -3
- package/package.json +1 -1
- package/dist/ui/assets/clipboard-DqCJeCL8.js +0 -1
- package/dist/ui/assets/dip-DYiCUWEu.js +0 -1
- package/dist/ui/assets/provider-store-access-BSkCbZy7.js +0 -1
- package/dist/ui/assets/provider-store-access-CH72xTU9.js +0 -1
- package/dist/ui/assets/session-freezer-C5-2JCLc.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./rolldown-runtime-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{c as a,n as o,o as s,s as c,t as l}from"./src-BQoW5KdD.js";import{n as u,o as d,s as f}from"./tool-ui-t6ocn6AG.js";import{a as p,i as m,n as h,o as g,r as _,t as v}from"./backend-local-Xd3x-KgI.js";import{t as y}from"./runtime-env-byAg9ij-.js";import{t as b}from"./types-idfTVsM8.js";import{n as x,t as S}from"./mime-types-BqLkKWa7.js";import{a as C,i as w,n as T,r as E}from"./mount-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./rolldown-runtime-aKtaBQYM.js";import{t as i}from"./logger-LESFN7Hj.js";import{c as a,n as o,o as s,s as c,t as l}from"./src-BQoW5KdD.js";import{n as u,o as d,s as f}from"./tool-ui-t6ocn6AG.js";import{a as p,i as m,n as h,o as g,r as _,t as v}from"./backend-local-Xd3x-KgI.js";import{t as y}from"./runtime-env-byAg9ij-.js";import{t as b}from"./types-idfTVsM8.js";import{n as x,t as S}from"./mime-types-BqLkKWa7.js";import{a as C,i as w,n as T,r as E}from"./mount-NSmYg9GU.js";import{t as D}from"./mount-id-nJcx05eu.js";import{c as O,d as ee,f as te,i as ne,l as k,n as A,o as re,r as ie,s as ae,t as oe,u as se}from"./proxied-fetch-CQqrhHlW.js";import{n as ce,r as le,t as ue}from"./fetch-body-DDu_AU5I.js";import{t as de}from"./remote-cache-D59F5FOx.js";import{n as j}from"./mount-table-store-s20mtVA3.js";import{n as M,r as fe,t as pe}from"./panel-rpc-CjFVE0nK.js";import{a as me}from"./providers-uyxOwwt4.js";import{B as he,D as ge,E as _e,F as ve,I as ye,L as N,M as be,N as xe,P as Se,R as Ce,T as we,V as P,_ as Te,d as F,h as I,i as Ee,j as De,o as Oe,v as ke,z as Ae}from"./account-store-B70B-Xy1.js";import{i as je,n as Me,t as Ne}from"./path-utils-DU6QhF_k.js";import{p as Pe,u as Fe}from"./transform-messages-ZX8cvJiJ.js";import{_ as Ie,l as Le,m as Re,p as ze,x as Be}from"./bedrock-camp-Czep_VHL.js";import{t as Ve}from"./__vite-browser-external-SwrSgYTf.js";import{a as He,i as Ue,n as We,r as Ge}from"./fs-D-5giB0a.js";const Ke=`__slicc_binary__`;function qe(e){if(!e||typeof e!=`object`)return!1;let t=e;return t[Ke]===`b64`&&typeof t.data==`string`}function Je(e){if(e instanceof Uint8Array)return{[Ke]:`b64`,data:a(e)};if(Array.isArray(e))return e.map(Je);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Je(r);return t}return e}function Ye(e){if(qe(e))return c(e.data);if(Array.isArray(e))return e.map(Ye);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Ye(r);return t}return e}const Xe=i(`panel-transport`);function Ze(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function Qe(){return{onMessage:e=>{let t=(t,n,r)=>(Ze(t)&&e(Ye(t)),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:(e,t)=>{let n=Je(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)||Xe.error(`Offscreen → panel transport send failed`,{error:t})})}}}const $e=new Set([`send_message`,`list_scoops`,`list_tasks`,`sudo_request`,`list_sudo_requests`,`lick_confirm`,`lick_dismiss`]);var et=t({formatMountRecoveryPrompt:()=>it,mdInlineCode:()=>rt,recoverMounts:()=>tt,shellQuote:()=>nt});async function tt(e,t,n){let r=[],i=[];for(let a of e){let{targetPath:e,descriptor:o}=a;if(o.kind===`local`){let a=await j(o.idbHandleKey),s=typeof a?.name==`string`?a.name:``;if(!a||!(`queryPermission`in a)){i.push({kind:`local`,path:e,dirName:s});continue}let c;try{c=await a.queryPermission({mode:`readwrite`})}catch(t){n?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s});continue}if(c!==`granted`){i.push({kind:`local`,path:e,dirName:s});continue}try{let i=v.fromHandle(a,{mountId:o.mountId});await t.mount(e,i),n?.info?.(`Restored mount from previous session`,{path:e,name:s}),r.push({kind:`local`,path:e,dirName:s})}catch(t){n?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),i.push({kind:`local`,path:e,dirName:s})}continue}if(o.kind===`s3`){try{let i=new de({mountId:o.mountId,ttlMs:3e4}),a=new w({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:E(o.profile)});await t.mount(e,a),n?.info?.(`Restored S3 mount from previous session`,{path:e,source:o.source}),r.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore S3 mount`,{path:e,error:r}),i.push({kind:`s3`,path:e,source:o.source,profile:o.profile,reason:r})}continue}if(o.kind===`da`)try{let i=new de({mountId:o.mountId,ttlMs:3e4}),a=new C({source:o.source,profile:o.profile,cache:i,mountId:o.mountId,signedFetch:T()});await t.mount(e,a),n?.info?.(`Restored DA mount from previous session`,{path:e,source:o.source}),r.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:``})}catch(t){let r=t instanceof Error?t.message:String(t);n?.warn?.(`Failed to restore DA mount`,{path:e,error:r}),i.push({kind:`da`,path:e,source:o.source,profile:o.profile,reason:r})}}return{restored:r,needsRecovery:i}}function nt(e){return`'${e.replace(/'/g,`'\\''`)}'`}function rt(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function it(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${rt(t)})`:``;return`- ${rt(e)}${n}`}),i=r.map(({path:e})=>` mount ${nt(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${nt(n)}`,a=`mount --source ${nt(t)}${i} ${nt(e)}`;return`- ${rt(e)} (${rt(t)}, profile ${rt(n)}) — ${r}\n Retry: ${rt(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
|
|
2
2
|
`)}const at=new Set([`webhook`,`cron`,`sprinkle`,`fswatch`,`session-reload`,`navigate`,`upgrade`,`cherry`,`workflow`,`sudo-request`,`preview`,`discovery`]);function ot(e){return e!=null&&at.has(e)}const st={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 ct(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 lt(e,t){let n=e.body,r=e.lickId;if(n?.reason===`mount-recovery`){let e=it(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=ht(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 ut(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.`:`
|
|
3
3
|
|
|
4
4
|
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 L(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 dt(e,t){let n=e.previewOrigin??`unknown origin`;return{label:t,content:`Preview tab ${(e.previewLifecycle??`unknown`)===`connected`?`connected`:`disconnected`} from ${n}`}}function ft(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 pt(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(`
|
|
5
|
-
`)}}function mt(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 ht(e,t){let n=ct(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 gt(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return ht(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 _t(e,t){let n=ht(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 vt(e){let t=st[e.type];return e.type===`session-reload`?lt(e,t):e.type===`upgrade`?ut(e,t):e.type===`cherry`?L(e,t):e.type===`preview`?dt(e,t):e.type===`workflow`?ft(e,t):e.type===`sudo-request`?pt(e,t):e.type===`navigate`?_t(e,t):e.type===`webhook`?gt(e,t):e.type===`discovery`?mt(e,t):ht(e,t)}const yt=64*1024;function bt(e,t=yt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Tt(t)} of ${Tt(e.length)} — the agent received the full output]`}function xt(e,t=yt,n=4){if(typeof e==`string`)return bt(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=xt(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=xt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const St=()=>/<img:data:image\/[^>]+>/g;function Ct(e,t=yt){if(!e)return e;if(!St().test(e))return bt(e,t);let n=bt(e.replace(St(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function wt(e,t=yt){if(e.length<=t)return e;if(!St().test(e))return bt(e,t);let n=[],r=0;for(let i of e.matchAll(St()))n.push(bt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(bt(e.slice(r),t)),n.join(``)}function Tt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Et={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Dt(){return{...Et}}function Ot(){let e=Dt();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 kt=new Set;function At(e){return kt.add(e),()=>{kt.delete(e)}}const jt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Mt=null;function Nt(e){if(!e.objectStoreNames.contains(jt.MESSAGES)){let t=e.createObjectStore(jt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(jt.SESSIONS)||e.createObjectStore(jt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(jt.TASKS)||e.createObjectStore(jt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(jt.STATE)||e.createObjectStore(jt.STATE,{keyPath:`key`})}function Pt(e){let t=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:t?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!t&&(e.requiresTrigger??!0),isCone:t,type:t?`cone`:`scoop`,assistantLabel:t?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function Ft(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(jt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(Pt(t))};return}t.objectStoreNames.contains(jt.SCOOPS)||t.createObjectStore(jt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function It(e){e.objectStoreNames.contains(jt.WEBHOOKS)||e.createObjectStore(jt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(jt.CRONTASKS)||e.createObjectStore(jt.CRONTASKS,{keyPath:`id`})}function Lt(e){let t=e.target.result,n=e.oldVersion;n<1&&Nt(t),n<2&&Ft(e,t),n<3&&It(t)}function Rt(){if(!Mt)return null;let e=Object.values(jt).every(e=>Mt.objectStoreNames.contains(e));return Mt.version===3&&e?Mt:(Mt.close(),Mt=null,null)}function zt(e){e.onversionchange=()=>{e.close(),Mt===e&&(Mt=null)},e.onclose=()=>{Mt===e&&(Mt=null)}}async function Bt(){return Rt()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Lt,n.onsuccess=()=>{let t=n.result;zt(t),Mt=t,e(t)},n.onerror=()=>t(n.error)})}async function Vt(e,t=`readonly`){return(await Bt()).transaction(e,t).objectStore(e)}async function Ht(e){let t=await Vt(jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Ut(){let e=await Vt(jt.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function Wt(e){let t=await Vt(jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Gt(){let e=await Vt(jt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function Kt(e){let t=(await Vt(jt.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function qt(e){let t=await Vt(jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Jt(e){let t=await Vt(jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Yt(e){let t=(await Vt(jt.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}async function Xt(e,t,n){let r=(await Vt(jt.MESSAGES)).index(`chatJid_timestamp`),i=IDBKeyRange.bound([e,t],[e,``],!0,!1);return new Promise((e,t)=>{let a=r.getAll(i);a.onsuccess=()=>{let t=a.result;n&&(t=t.filter(e=>e.senderName!==n)),e(t)},a.onerror=()=>t(a.error)})}async function Zt(e){let t=await Vt(jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Qt(e){let t=await Vt(jt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function $t(){let e=await Vt(jt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function en(e){let t=await Vt(jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function tn(e){let t=await Vt(jt.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function nn(e,t){let n=await Vt(jt.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function rn(){await Bt()}async function an(e){let t=await Vt(jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function on(e){let t=await Vt(jt.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function sn(){try{let e=await Vt(jt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function cn(e){let t=await Vt(jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(e){let t=await Vt(jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function un(e){let t=await Vt(jt.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function dn(){try{let e=await Vt(jt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function fn(e){let t=await Vt(jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function pn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function mn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=pn(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const hn=`slicc.trayWorkerBaseUrl`,gn=`slicc.trayJoinUrl`,_n=s;function vn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return mn(t.toString());let i=pn(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function yn(e){let t=vn(e);return t?.joinUrl?t:null}i(`tray-leader`);let bn={state:`inactive`,session:null,error:null};function xn(){return{...bn,session:bn.session?{...bn.session}:null}}function Sn(){let e=xn();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Cn=new Set;function wn(e){return Cn.add(e),()=>{Cn.delete(e)}}const Tn=`sessions`;function En(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Tn)||e.createObjectStore(Tn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Dn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await En();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(Tn,`readwrite`);i.objectStore(Tn).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(Tn,`readonly`).objectStore(Tn).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(Tn,`readonly`).objectStore(Tn).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(Tn,`readwrite`);i.objectStore(Tn).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 On=i(`offscreen-bridge`);function kn(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 An=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||=Qe(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Dn;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-${jn()}`;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)=>{$e.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{$e.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=xt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:jn(),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=Ct(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:wt(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=xn(),t=Dt();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}-${jn()}`,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){On.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=kn(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=vt({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=>{On.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-C3cZZEnY.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){On.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:Mn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-C3cZZEnY.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:Mn(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){On.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}-${jn()}`,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`){f.markMounted(t);return}try{await f.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}),f.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 jn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Mn(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
5
|
+
`)}}function mt(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 ht(e,t){let n=ct(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 gt(e,t){let n=e.headers,r=n?.[`x-slicc-preview-conn`];if(!r)return ht(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 _t(e,t){let n=ht(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 vt(e){let t=st[e.type];return e.type===`session-reload`?lt(e,t):e.type===`upgrade`?ut(e,t):e.type===`cherry`?L(e,t):e.type===`preview`?dt(e,t):e.type===`workflow`?ft(e,t):e.type===`sudo-request`?pt(e,t):e.type===`navigate`?_t(e,t):e.type===`webhook`?gt(e,t):e.type===`discovery`?mt(e,t):ht(e,t)}const yt=64*1024;function bt(e,t=yt){return e.length<=t?e:`${e.slice(0,t)}\n… [tool output truncated for the chat transcript: showing ${Tt(t)} of ${Tt(e.length)} — the agent received the full output]`}function xt(e,t=yt,n=4){if(typeof e==`string`)return bt(e,t);if(typeof e!=`object`||!e||n<=0)return e;if(Array.isArray(e)){let r=null;for(let i=0;i<e.length;i++){let a=xt(e[i],t,n-1);a!==e[i]&&(r??=[...e],r[i]=a)}return r??e}let r=null;for(let[i,a]of Object.entries(e)){let o=xt(a,t,n-1);o!==a&&(r??={...e},r[i]=o)}return r??e}const St=()=>/<img:data:image\/[^>]+>/g;function Ct(e,t=yt){if(!e)return e;if(!St().test(e))return bt(e,t);let n=bt(e.replace(St(),``).trim(),t);return n.length>0?`${n}\n[screenshot omitted from transcript]`:`[screenshot]`}function wt(e,t=yt){if(e.length<=t)return e;if(!St().test(e))return bt(e,t);let n=[],r=0;for(let i of e.matchAll(St()))n.push(bt(e.slice(r,i.index),t)),n.push(i[0]),r=(i.index??0)+i[0].length;return n.push(bt(e.slice(r),t)),n.join(``)}function Tt(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.round(e/1024)} KB`}let Et={state:`inactive`,joinUrl:null,trayId:null,error:null,lastPingTime:null,reconnectAttempts:0,attachAttempts:0,lastAttachCode:null,connectingSince:null,lastError:null};function Dt(){return{...Et}}function Ot(){let e=Dt();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 kt=new Set;function At(e){return kt.add(e),()=>{kt.delete(e)}}const jt={SCOOPS:`scoops`,MESSAGES:`messages`,SESSIONS:`sessions`,TASKS:`tasks`,STATE:`state`,WEBHOOKS:`webhooks`,CRONTASKS:`crontasks`};let Mt=null;function Nt(e){if(!e.objectStoreNames.contains(jt.MESSAGES)){let t=e.createObjectStore(jt.MESSAGES,{keyPath:`id`});t.createIndex(`chatJid`,`chatJid`),t.createIndex(`timestamp`,`timestamp`),t.createIndex(`chatJid_timestamp`,[`chatJid`,`timestamp`])}e.objectStoreNames.contains(jt.SESSIONS)||e.createObjectStore(jt.SESSIONS,{keyPath:`groupFolder`}),e.objectStoreNames.contains(jt.TASKS)||e.createObjectStore(jt.TASKS,{keyPath:`id`}).createIndex(`groupFolder`,`groupFolder`),e.objectStoreNames.contains(jt.STATE)||e.createObjectStore(jt.STATE,{keyPath:`key`})}function Pt(e){let t=e.isMain??!1;return{jid:e.jid,name:e.name,folder:e.folder,trigger:t?void 0:e.trigger||`@${e.folder}`,requiresTrigger:!t&&(e.requiresTrigger??!0),isCone:t,type:t?`cone`:`scoop`,assistantLabel:t?`sliccy`:e.config?.assistantName||e.folder,addedAt:e.addedAt,config:e.config?{systemPromptAppend:e.config.systemPromptAppend,timeout:e.config.timeout,assistantName:e.config.assistantName}:void 0}}function Ft(e,t){if(t.objectStoreNames.contains(`groups`)){let n=e.target.transaction.objectStore(`groups`).getAll();n.onsuccess=()=>{let e=n.result;t.deleteObjectStore(`groups`);let r=t.createObjectStore(jt.SCOOPS,{keyPath:`jid`});r.createIndex(`type`,`type`);for(let t of e)r.put(Pt(t))};return}t.objectStoreNames.contains(jt.SCOOPS)||t.createObjectStore(jt.SCOOPS,{keyPath:`jid`}).createIndex(`type`,`type`)}function It(e){e.objectStoreNames.contains(jt.WEBHOOKS)||e.createObjectStore(jt.WEBHOOKS,{keyPath:`id`}),e.objectStoreNames.contains(jt.CRONTASKS)||e.createObjectStore(jt.CRONTASKS,{keyPath:`id`})}function Lt(e){let t=e.target.result,n=e.oldVersion;n<1&&Nt(t),n<2&&Ft(e,t),n<3&&It(t)}function Rt(){if(!Mt)return null;let e=Object.values(jt).every(e=>Mt.objectStoreNames.contains(e));return Mt.version===3&&e?Mt:(Mt.close(),Mt=null,null)}function zt(e){e.onversionchange=()=>{e.close(),Mt===e&&(Mt=null)},e.onclose=()=>{Mt===e&&(Mt=null)}}async function Bt(){return Rt()||new Promise((e,t)=>{let n=indexedDB.open(`slicc-groups`,3);n.onupgradeneeded=Lt,n.onsuccess=()=>{let t=n.result;zt(t),Mt=t,e(t)},n.onerror=()=>t(n.error)})}async function Vt(e,t=`readonly`){return(await Bt()).transaction(e,t).objectStore(e)}async function Ht(e){let t=await Vt(jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Ut(){let e=await Vt(jt.SCOOPS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>{let e={};for(let t of r.result)e[t.jid]=t;t(e)},r.onerror=()=>n(r.error)})}async function Wt(e){let t=await Vt(jt.SCOOPS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Gt(){let e=await Vt(jt.MESSAGES,`readwrite`);return new Promise((t,n)=>{let r=e.clear();r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}async function Kt(e){let t=(await Vt(jt.MESSAGES,`readwrite`)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.openCursor(n);i.onsuccess=()=>{let t=i.result;if(!t){e();return}t.delete(),t.continue()},i.onerror=()=>r(i.error)})}async function qt(e){let t=await Vt(jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Jt(e){let t=await Vt(jt.MESSAGES,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Yt(e){let t=(await Vt(jt.MESSAGES)).index(`chatJid_timestamp`),n=IDBKeyRange.bound([e,``],[e,``],!1,!1);return new Promise((e,r)=>{let i=t.getAll(n);i.onsuccess=()=>e(i.result),i.onerror=()=>r(i.error)})}async function Xt(e,t,n){let r=(await Vt(jt.MESSAGES)).index(`chatJid_timestamp`),i=IDBKeyRange.bound([e,t],[e,``],!0,!1);return new Promise((e,t)=>{let a=r.getAll(i);a.onsuccess=()=>{let t=a.result;n&&(t=t.filter(e=>e.senderName!==n)),e(t)},a.onerror=()=>t(a.error)})}async function Zt(e){let t=await Vt(jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function Qt(e){let t=await Vt(jt.TASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function $t(){let e=await Vt(jt.TASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}async function en(e){let t=await Vt(jt.TASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function tn(e){let t=await Vt(jt.STATE);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result?.value??null),i.onerror=()=>r(i.error)})}async function nn(e,t){let n=await Vt(jt.STATE,`readwrite`);return new Promise((r,i)=>{let a=n.put({key:e,value:t});a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async function rn(){await Bt()}async function an(e){let t=await Vt(jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function on(e){let t=await Vt(jt.WEBHOOKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function sn(){try{let e=await Vt(jt.WEBHOOKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function cn(e){let t=await Vt(jt.WEBHOOKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function ln(e){let t=await Vt(jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}async function un(e){let t=await Vt(jt.CRONTASKS);return new Promise((n,r)=>{let i=t.get(e);i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async function dn(){try{let e=await Vt(jt.CRONTASKS);return new Promise((t,n)=>{let r=e.getAll();r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)})}catch{return[]}}async function fn(e){let t=await Vt(jt.CRONTASKS,`readwrite`);return new Promise((n,r)=>{let i=t.delete(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)})}function pn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``,t.pathname!==`/`&&(t.pathname=t.pathname.replace(/\/+$/,``)||`/`);let n=t.toString();return n.endsWith(`/`)?n.slice(0,-1):n}catch{return null}}function mn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.toString(),r=t.pathname.split(`/`).filter(Boolean);if(r.length<2||r.at(-2)!==`join`)return null;let[i,a,...o]=decodeURIComponent(r.at(-1)).split(`.`);if(!i||!a||o.length>0)return null;r.splice(-2,2),t.pathname=r.length>0?`/${r.join(`/`)}`:`/`;let s=pn(t.toString());return s?{workerBaseUrl:s,trayId:i,joinUrl:n}:null}catch{return null}}const hn=`slicc.trayWorkerBaseUrl`,gn=`slicc.trayJoinUrl`,_n=s;function vn(e){if(!e)return null;try{let t=new URL(e.trim());t.search=``,t.hash=``;let n=t.pathname.split(`/`).filter(Boolean),r=null;if(n.length>=2&&n.at(-2)===`tray`)r=decodeURIComponent(n.at(-1)),n.splice(-2,2),t.pathname=n.length>0?`/${n.join(`/`)}`:`/`;else if(n.length>=2&&n.at(-2)===`join`)return mn(t.toString());let i=pn(t.toString());return i?{workerBaseUrl:i,trayId:r,joinUrl:null}:null}catch{return null}}function yn(e){let t=vn(e);return t?.joinUrl?t:null}i(`tray-leader`);let bn={state:`inactive`,session:null,error:null};function xn(){return{...bn,session:bn.session?{...bn.session}:null}}function Sn(){let e=xn();if(e.state!==`inactive`)return e;try{let e=globalThis.localStorage?.getItem(`slicc.leaderTrayStatus`);if(e){let t=JSON.parse(e);if(t?.state&&t.state!==`inactive`)return t}}catch{}return e}const Cn=new Set;function wn(e){return Cn.add(e),()=>{Cn.delete(e)}}const Tn=`sessions`;function En(){return new Promise((e,t)=>{let n=indexedDB.open(`browser-coding-agent`,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(Tn)||e.createObjectStore(Tn,{keyPath:`id`})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}var Dn=class{db=null;async init(){await this.getDb()}async getDb(){if(!this.db){let e=await En();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(Tn,`readwrite`);i.objectStore(Tn).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(Tn,`readonly`).objectStore(Tn).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(Tn,`readonly`).objectStore(Tn).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(Tn,`readwrite`);i.objectStore(Tn).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 On=i(`offscreen-bridge`);function kn(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 An=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||=Qe(),this._transport}async bind(e,t){this.orchestrator=e,this.browserAPI=t??null,this.transportUnsubscribe?.(),this.transportUnsubscribe=this.setupMessageListener();let n=new Dn;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-${jn()}`;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)=>{$e.has(n)||e.bufferToolStart(t,n,r)},onToolEnd:(t,n,r,i)=>{$e.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=xt(n),i=this.getOrCreateAssistantMsg(e);i.toolCalls||=[],i.toolCalls.push({id:jn(),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=Ct(n),e.isError=r)}}this.persistScoop(e),this.emit({type:`agent-event`,scoopJid:e,eventType:`tool_end`,toolName:t,toolResult:wt(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=xn(),t=Dt();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}-${jn()}`,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){On.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=kn(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=vt({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=>{On.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-DzRXXJel.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){On.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:Mn(i)});return}let a=this.orchestrator.getScoopContext(t);if(a){let{agentMessagesToChatMessages:n}=await import(`./agent-message-to-chat-DzRXXJel.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:Mn(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){On.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}-${jn()}`,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`){f.markMounted(t);return}try{await f.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}),f.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 jn(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function Mn(e){let t=[];for(let n of e){let e=(n.content??``).trim();e.length!==0&&t.push(`${n.role}: ${e}`)}return t.join(`
|
|
6
6
|
`)}const Nn=i(`cdp`);var Pn=class{ws=null;nextId=1;_superseded=!1;pending=new Map;listeners=new Map;_state=`disconnected`;get state(){return this._state}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:r}=e;return this._state=`connecting`,new Promise((e,i)=>{let a=setTimeout(()=>{this.cleanup(),i(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=r===void 0?new WebSocket(t):new WebSocket(t,r)}catch(e){clearTimeout(a),this._state=`disconnected`,i(e);return}this.ws.onopen=()=>{clearTimeout(a),this._state=`connected`,this._superseded=!1,Nn.info(`Connected`,{url:t}),e()},this.ws.onerror=e=>{clearTimeout(a),this._state===`connecting`&&(Nn.error(`Connection failed`,{url:t}),this.cleanup(),i(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),Nn.info(`Disconnected`)}async send(e,t,n,r=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let i=this.nextId++,a={id:i,method:e};return t&&(a.params=t),n&&(a.sessionId=n),Nn.debug(`Send`,{method:e,id:i,sessionId:n}),new Promise((t,n)=>{let o=setTimeout(()=>{this.pending.delete(i),n(Error(`CDP command timed out after ${r}ms: ${e}`))},r);this.pending.set(i,{resolve:e=>{clearTimeout(o),t(e)},reject:e=>{clearTimeout(o),n(e)}}),this.ws.send(JSON.stringify(a))})}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,t=3e4){return new Promise((n,r)=>{let i=setTimeout(()=>{this.off(e,a),r(Error(`Timed out waiting for event: ${e}`))},t),a=t=>{clearTimeout(i),this.off(e,a),n(t)};this.on(e,a)})}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;Nn.debug(`Response`,{id:e.id,hasError:!!e.error});let n=this.pending.get(e.id);n&&(this.pending.delete(e.id),e.error?(Nn.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),n.reject(Error(`CDP error: ${e.error.message} (${e.error.code})`))):n.resolve(e.result??{}));return}if(`method`in t){let e=t;Nn.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){let t=e===4001;t?(this._superseded=!0,Nn.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):Nn.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size});let n=t?`CDP connection superseded by another SLICC tab/window on this instance`:`CDP connection closed`;for(let[,e]of this.pending)e.reject(Error(n));this.cleanup()}cleanup(){this.ws=null,this._state=`disconnected`,this.pending.clear()}};const Fn=`(function() {
|
|
7
7
|
'use strict';
|
|
8
8
|
|
|
@@ -6484,13 +6484,13 @@ except BaseException:
|
|
|
6484
6484
|
`)?t:`${t}\n`);return}try{e.writeStdout(`${JSON.stringify(t,null,2)}\n`)}catch{e.writeStdout(`${String(t)}\n`)}},warn(n,i){let a=typeof i==`object`&&i&&`prefix`in i?i.prefix:void 0;e.writeStderr(r(a,t(n)))},help(t){throw e.writeStdout(t.endsWith(`
|
|
6485
6485
|
`)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const aQ={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 vme(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${aQ.reset}`:String(n);return{enabled:t,green:n(aQ.green),red:n(aQ.red),yellow:n(aQ.yellow),gray:n(aQ.gray),bold:n(aQ.bold),cyan:n(aQ.cyan),dim:n(aQ.dim)}}const yme={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function oQ(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*yme[i])}function sQ(e){return e<10?`0${e}`:String(e)}const bme={parseDuration:oQ,ago(e,t=new Date){return new Date(t.getTime()-oQ(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-oQ(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+oQ(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-oQ(e));return`${n.getFullYear()}/${sQ(n.getMonth()+1)}/${sQ(n.getDate())}`}},xme=/\u001b\[[0-9;]*m/g;function cQ(e){return e.replace(xme,``)}function lQ(e){return cQ(e).length}function uQ(e,t){let n=String(e??``);return t<=0?``:lQ(n)<=t?n:t<=1?n.slice(0,t):`${cQ(n).slice(0,t-1)}…`}function dQ(e,t){let n=String(e??``),r=lQ(n);return r===t?n:r>t?uQ(n,t):n+` `.repeat(t-r)}function Sme(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,lQ(e))}r[i]=t}return e.map(e=>r.map((t,n)=>dQ(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
|
|
6486
6486
|
`)}function Cme(e){return e instanceof Date?e:new Date(e)}function wme(e,t=`short`){let n=Cme(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()}-${sQ(n.getMonth()+1)}-${sQ(n.getDate())}`}const Tme={trunc:uQ,col:dQ,table:Sme,date:wme},Eme=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 fQ(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 pQ(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=fQ(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function Dme(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:pQ(t)}function mQ(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 hQ(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 gQ(e){let t=hQ(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function _Q(...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=fQ(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function Ome(e,t){let n=_Q(e),r=_Q(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 kme(e){let t=e.charCodeAt(0)===47?`/`:``,n=hQ(e),r=gQ(e),i=r?n.slice(0,n.length-r.length):n,a=mQ(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function Ame(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 jme={sep:`/`,delimiter:`:`,basename:hQ,dirname:mQ,extname:gQ,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:Dme,normalize:pQ,resolve:_Q,relative:Ome,parse:kme,format:Ame},vQ=65536,Mme={md5:tY.md5,sha1:nY.sha1,sha256:rY.sha256};function yQ(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 Nme(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(yQ(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function Pme(e){let t=Mme[String(e).toLowerCase().replace(`-`,``)];if(!t)throw Error(`Digest method not supported: ${e}`);let n=t.create(),r=!1,i={update(e,t){if(r)throw Error(`Digest already called`);return n.update(Nme(e,t)),i},digest(e){r=!0;let t=yQ(n.array());return e?t.toString(e):t}};return i}function bQ(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function xQ(e){return bQ().getRandomValues(e)}function SQ(e){for(let t=0;t<e.length;t+=vQ){let n=Math.min(t+vQ,e.length);xQ(e.subarray(t,n))}}function CQ(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const wQ=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function Fme(){let e=bQ();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=xQ(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${wQ[t[0]]}${wQ[t[1]]}${wQ[t[2]]}${wQ[t[3]]}-${wQ[t[4]]}${wQ[t[5]]}-${wQ[t[6]]}${wQ[t[7]]}-${wQ[t[8]]}${wQ[t[9]]}-${wQ[t[10]]}${wQ[t[11]]}${wQ[t[12]]}${wQ[t[13]]}${wQ[t[14]]}${wQ[t[15]]}`}const Ime={randomFillSync(e,t=0,n){let r=CQ(e),i=t,a=n===void 0?r.length:i+n;return SQ(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return SQ(CQ(n)),n},randomUUID:Fme,getRandomValues(e){return xQ(e)},createHash:Pme,get webcrypto(){return bQ()},get subtle(){return bQ().subtle}};var TQ=class extends Error{actual;expected;operator;generatedMessage;code;constructor(e={}){let t=!e.message;super(e.message||`${EQ(e.actual)} ${e.operator||`!=`} ${EQ(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 EQ(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 DQ(e,t){return e instanceof Error?e:typeof e==`string`?new TQ({message:e}):t()}function Lme(e,t,n,r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!OQ(e[i],t[i],n,r))return!1;return!0}function Rme(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(!OQ(i,o,n,r))return!1}return!0}function OQ(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)?Lme(e,t,n,r):Rme(i,a,n,r):!1)}function zme(e,t){try{if(e instanceof t)return!0}catch{}try{return!!t(e)}catch{return!1}}function Bme(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 Vme(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`?zme(e,t):t&&typeof t==`object`?!e||typeof e!=`object`?!1:Bme(e,t):!1}function kQ(e){let t=(e,t)=>{if(!e)throw DQ(t,()=>new TQ({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 DQ(n,()=>new TQ({actual:e,expected:t,operator:`strictEqual`}))},i=(t,n,i)=>{if(e){r(t,n,i);return}if(t!=n)throw DQ(i,()=>new TQ({actual:t,expected:n,operator:`==`}))},a=(e,t,n)=>{if(Object.is(e,t))throw DQ(n,()=>new TQ({actual:e,expected:t,operator:`notStrictEqual`}))},o=(t,n,r)=>{if(e){a(t,n,r);return}if(t==n)throw DQ(r,()=>new TQ({actual:t,expected:n,operator:`!=`}))},s=(e,t,n)=>{if(!OQ(e,t,!0,new WeakMap))throw DQ(n,()=>new TQ({actual:e,expected:t,operator:`deepStrictEqual`}))},c=(t,n,r)=>{if(e){s(t,n,r);return}if(!OQ(t,n,!1,new WeakMap))throw DQ(r,()=>new TQ({actual:t,expected:n,operator:`deepEqual`}))},l=(e,t,n)=>{if(OQ(e,t,!0,new WeakMap))throw DQ(n,()=>new TQ({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(OQ(t,n,!1,new WeakMap))throw DQ(r,()=>new TQ({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 DQ(typeof t==`string`?t:n,()=>new TQ({message:`Missing expected exception`,operator:`throws`}));if(!(typeof t==`string`||t instanceof Error)&&!Vme(r,t))throw DQ(n,()=>new TQ({message:`Got unwanted exception`,actual:r,operator:`throws`}))},n.doesNotThrow=(e,t)=>{try{e()}catch(e){throw DQ(t,()=>new TQ({message:`Got unwanted exception`,actual:e,operator:`doesNotThrow`}))}},n.fail=e=>{throw DQ(e,()=>new TQ({message:`Failed`,operator:`fail`}))},n.AssertionError=TQ,n}const AQ=kQ(!0);AQ.strict=AQ;const jQ=kQ(!1);jQ.strict=AQ;const MQ=Symbol.for(`nodejs.util.inspect.custom`),NQ=Symbol.for(`nodejs.util.promisify.custom`);function PQ(e){return`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}'`}function Hme(e){if(e===null)return`null`;let t=typeof e;if(t===`string`)return PQ(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 Ume(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 Wme(e,t,n){if(Array.isArray(e))return e.length===0?`[]`:`[ ${e.map(e=>FQ(e,t+1,n)).join(`, `)} ]`;if(e instanceof Map){let r=[...e].map(([e,r])=>`${FQ(e,t+1,n)} => ${FQ(r,t+1,n)}`);return`Map(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}if(e instanceof Set){let r=[...e].map(e=>FQ(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:PQ(r)}: ${FQ(e[r],t+1,n)}`).join(`, `)} }`}function FQ(e,t,n){let r=Hme(e);if(r!==null)return r;let i=e,a=Ume(i);if(a!==null)return a;let o=i[MQ];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 Wme(i,t,n)}finally{n.seen.delete(e)}}function IQ(e,t={}){let n=t.depth===void 0?2:t.depth;return FQ(e,0,{seen:new Set,maxDepth:n,opts:t})}function Gme(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):IQ(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++,IQ(i,{depth:4});case`%O`:return n.i++,IQ(i,{depth:null});case`%c`:return n.i++,``;default:return e}}function LQ(e,...t){let n=t[0];if(typeof n!=`string`)return t.map(e=>typeof e==`string`?e:IQ(e)).join(` `);let r={i:1},i=n.replace(/%[sdifjoOc%]/g,n=>Gme(n,t,r,e));for(;r.i<t.length;r.i++){let e=t[r.i];i+=` ${typeof e==`string`?e:IQ(e)}`}return i}function Kme(...e){return LQ({},...e)}function qme(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 Jme(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type function`);let t=e[NQ];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 RQ=IQ;RQ.custom=MQ;const zQ=Jme;zQ.custom=NQ;const Yme={format:Kme,formatWithOptions:LQ,inspect:RQ,inherits:qme,promisify:zQ};function Xme(e){return typeof e==`string`?new Uint8Array(yQ(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function Zme(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 BQ(e,t,n){return yQ(e(Xme(t),Zme(n)))}function VQ(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=BQ(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const Qme={gzipSync:(e,t)=>BQ(tQ,e,t),gunzipSync:(e,t)=>BQ(rQ,e,t),deflateSync:(e,t)=>BQ($Z,e,t),inflateSync:(e,t)=>BQ(rQ,e,t),deflateRawSync:(e,t)=>BQ(eQ,e,t),inflateRawSync:(e,t)=>BQ(iQ,e,t),gzip:(e,t,n)=>VQ(tQ,e,t,n),gunzip:(e,t,n)=>VQ(rQ,e,t,n),deflate:(e,t,n)=>VQ($Z,e,t,n),inflate:(e,t,n)=>VQ(rQ,e,t,n),deflateRaw:(e,t,n)=>VQ(eQ,e,t,n),inflateRaw:(e,t,n)=>VQ(iQ,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}},$me={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
|
|
6487
|
-
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function ehe(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 the(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const nhe={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:ehe,pathToFileURL:the};var HQ=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 rhe=Object.assign(HQ,{EventEmitter:HQ,default:HQ});var UQ=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}},WQ=class extends UQ{read(){return null}destroy(){return this}},ihe=class extends UQ{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},GQ=class extends UQ{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const ahe={Readable:WQ,Writable:ihe,Transform:GQ,PassThrough:class extends GQ{},Stream:UQ};let ohe=1;function KQ(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 qQ(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?yQ(e):yQ(e).toString(t)}function JQ(e,t){if(e.length===0)return qQ(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function YQ(e,t,n){t.length>0&&e.emit(`data`,qQ(t,n)),e.readable=!1,e.emit(`end`)}function she(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(KQ(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(KQ(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var XQ=class extends HQ{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=ohe++,this.spawnfile=n,this.spawnargs=r,this.stdout=new WQ,this.stderr=new WQ,this.stdin=she(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){YQ(this.stdout,e.stdout,t),YQ(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 che(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new XQ(o,r,i,a);return n.input!==void 0&&s.stdin.write(KQ(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,JQ(i,t),JQ(a,t))),e.once(`close`,(o,s)=>{let c=JQ(i,t),l=JQ(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${KQ(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;return t(a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i],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,NQ,{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:XQ}}function lhe(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 ZQ=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 };`)}},uhe=class{rpc;targetId;constructor(e,t){this.rpc=e,this.targetId=t}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 evaluate(e,...t){let n=typeof e==`string`?e:`(${e.toString()})(${t.map(e=>JSON.stringify(e)).join(`, `)})`;return this.rpc.call(`browser`,`evalAsync`,[this.targetId,n])}async screenshot(e){let t={};e?.fullPage!==void 0&&(t.fullPage=e.fullPage);let n=lhe(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 ZQ(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 ZQ(this.rpc,this.targetId,e,r));return n}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(){await this.rpc.call(`browser`,`closeTab`,[this.targetId])}},dhe=class{rpc;pageTargetIds=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);return this.pageTargetIds.push(t),e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]),new uhe(this.rpc,t)}async close(){let e=this.pageTargetIds.splice(0,this.pageTargetIds.length);for(let t of e)await this.rpc.call(`browser`,`closeTab`,[t])}};function fhe(e){let t=async t=>new dhe(e);return{chromium:{launch:t},firefox:{launch:t},webkit:{launch:t}}}const QQ=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`]),phe={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 mhe(e,t){let n=phe[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function hhe(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function ghe(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function $Q(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function _he(e){let t=hhe(e.argv[1]??``),n=$Q(t,`references`),r=$Q(t,`assets`),i=$Q(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)+`
|
|
6487
|
+
`,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function ehe(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 the(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const nhe={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:ehe,pathToFileURL:the};var HQ=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 rhe=Object.assign(HQ,{EventEmitter:HQ,default:HQ});var UQ=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}},WQ=class extends UQ{read(){return null}destroy(){return this}},ihe=class extends UQ{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},GQ=class extends UQ{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const ahe={Readable:WQ,Writable:ihe,Transform:GQ,PassThrough:class extends GQ{},Stream:UQ};let ohe=1;function KQ(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 qQ(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?yQ(e):yQ(e).toString(t)}function JQ(e,t){if(e.length===0)return qQ(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function YQ(e,t,n){t.length>0&&e.emit(`data`,qQ(t,n)),e.readable=!1,e.emit(`end`)}function she(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(KQ(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(KQ(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var XQ=class extends HQ{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=ohe++,this.spawnfile=n,this.spawnargs=r,this.stdout=new WQ,this.stderr=new WQ,this.stdin=she(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){YQ(this.stdout,e.stdout,t),YQ(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 che(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new XQ(o,r,i,a);return n.input!==void 0&&s.stdin.write(KQ(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,JQ(i,t),JQ(a,t))),e.once(`close`,(o,s)=>{let c=JQ(i,t),l=JQ(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${KQ(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;return t(a.shell?`${e}${i.length?` ${i.join(` `)}`:``}`:[e,...i],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,NQ,{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:XQ}}function lhe(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 ZQ=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 };`)}},uhe=class{rpc;targetId;onClose;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 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=lhe(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 ZQ(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 ZQ(this.rpc,this.targetId,e,r));return n}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(){await this.rpc.call(`browser`,`closeTab`,[this.targetId]),this.onClose?.(this.targetId)}},dhe=class{rpc;pageTargetIds=[];constructor(e){this.rpc=e}async newPage(e){let t=await this.rpc.call(`browser`,`createTab`,[`about:blank`]);return this.pageTargetIds.push(t),e?.viewport&&await this.rpc.call(`browser`,`setViewport`,[t,e.viewport.width,e.viewport.height]),new uhe(this.rpc,t,e=>{let t=this.pageTargetIds.indexOf(e);t!==-1&&this.pageTargetIds.splice(t,1)})}async close(){let e=this.pageTargetIds.splice(0,this.pageTargetIds.length);for(let t of e)await this.rpc.call(`browser`,`closeTab`,[t])}};function fhe(e){let t=async t=>new dhe(e);return{chromium:{launch:t},firefox:{launch:t},webkit:{launch:t}}}const QQ=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`]),phe={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 mhe(e,t){let n=phe[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function hhe(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function ghe(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function $Q(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function _he(e){let t=hhe(e.argv[1]??``),n=$Q(t,`references`),r=$Q(t,`assets`),i=$Q(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)+`
|
|
6488
6488
|
`),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 ${ghe(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 e$(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 t$(e){let t=e$(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function n$(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function vhe(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function yhe(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 bhe=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=e$(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=t$(e$(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=t$(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=t$(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}readFile(e){this.touched=!0;let t=e$(e),n=this.tree.get(t);if(!n||n.isDirectory)throw n$(t);if(n.truncated)throw vhe(t);return n.content}writeFile(e,t){this.touched=!0;let n=e$(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1})}exists(e){this.touched=!0;let t=e$(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=e$(e),n=this.tree.get(t);if(!n)throw n$(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.content.byteLength}}readdir(e){this.touched=!0;let t=e$(e);if(!this.tree.get(t)?.isDirectory)throw n$(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=e$(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=t$(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw n$(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0})}rm(e,t){this.touched=!0;let n=e$(e),r=this.tree.get(n);if(!r)throw n$(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=e$(e),r=this.tree.get(n);if(!r||r.isDirectory)throw n$(n);let i=e$(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1})}rename(e,t){this.touched=!0;let n=e$(e),r=this.tree.get(n);if(!r)throw n$(n);let i=e$(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=e$(e),n=this.tree.get(t);if(!n)throw n$(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=e$(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&&!yhe(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 r$(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var i$=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function a$(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function xhe(e,t){let n;try{n=await e.call(`vfs`,`snapshot`,[t])}catch{n={entries:[]}}return new bhe(n)}function She(e){return{usbBridge:age(e),serialBridge:oge(e),hidBridge:sge(e)}}async function Che(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=Ehe(i,a),{processShim:s,getDidCallProcessExit:c}=Dhe(e,i,a),l=!!e.env?.NO_COLOR,u=vme({isTTY:!l,noColor:l}),d=_me({writeStdout:i,writeStderr:a,exit:e=>{throw new i$(e)},color:u}),f=new nJ(t),p=Fhe(f,C),m=await xhe(f,e.cwd);Object.assign(p,Ihe(m,e.cwd));let h=khe(f,m,e.cwd),g=Mhe(h,{cwd:e.cwd}),_=_he({argv:e.argv,fs:p,exec:h}),v=Xhe(f),{usbBridge:y,serialBridge:b,hidBridge:x}=She(f),S=ZJ({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,Yhe(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=Nhe({exec:h,agent:g,skill:_,http:S,browser:v,usb:y,serial:b,hid:x,cli:d,color:u}),T=e.filename,E=r$(T),D=await zhe(f,e.code,e.cwd,T),O=Hhe({graph:D,fsBridge:p,processShim:s,childProcess:che(h),nodeConsole:o,sliccyModules:w,shimmedPackages:Vhe(f)}).require,ee={exports:{},filename:e.filename},te=D.entrySource!==void 0,ne=D.entrySource??e.code,k=globalThis;k.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let A=await Jhe(ne,{process:s,console:o,require:O,module:ee,exports:ee.exports,fetch:C,__dirname:E,__filename:T},a,te);await whe(f,m,a),c()||await The(f),delete k.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:A})}async function whe(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 The(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 Ehe(e,t){return{log:(...t)=>e(`${t.map(a$).join(` `)}
|
|
6489
6489
|
`),info:(...t)=>e(`${t.map(a$).join(` `)}
|
|
6490
6490
|
`),warn:(...e)=>t(`${e.map(a$).join(` `)}
|
|
6491
6491
|
`),error:(...e)=>t(`${e.map(a$).join(` `)}
|
|
6492
6492
|
`)}}function Dhe(e,t,n){let r=!!e.env?.NO_COLOR,i=Phe(e.stdin??``),a=gme(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new i$(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function Ohe(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function khe(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:Ohe(t)}),Promise.resolve(!0)),stdin:{write:e=>{!c&&!u&&o.push(e)},end:()=>m()},done:p}}});return c.exec=c,c}function Ahe(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 jhe(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`,Ahe(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 Mhe(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(jhe(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 Nhe(e){return{...e,time:bme,fmt:Tme,pool:Eme}}function Phe(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 Fhe(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 Ihe(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 Lhe(e,t){return e?.startsWith(`/`)?r$(e):t}function Rhe(e){return e.includes(`require`)||e.includes(`import`)}async function zhe(e,t,n,r){return Rhe(t)?e.call(`module`,`buildGraph`,[t,Lhe(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function Bhe(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 Vhe(e){return{playwright:fhe(e)}}function Hhe(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:Ghe(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=Uhe(t,n,r,i);if(a.hit)return a;if(QQ.has(t))throw mhe(e,t);if(xW.has(t))throw qhe(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]):Whe(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=r$(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`&&Bhe(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function Uhe(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:jme}:e===`crypto`?{hit:!0,value:Ime}: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:jQ}:e===`assert/strict`?{hit:!0,value:AQ}:e===`util`?{hit:!0,value:Yme}:e===`events`?{hit:!0,value:rhe}:e===`os`?{hit:!0,value:$me}:e===`stream`?{hit:!0,value:ahe}:e===`url`?{hit:!0,value:nhe}:e===`zlib`?{hit:!0,value:Qme}:{hit:!1}}function Whe(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 Ghe(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 Khe={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function qhe(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${Khe[t]||``}`)}async function Jhe(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";
|
|
6493
|
-
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof i$?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function Yhe(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 Xhe(e){return{findTab:t=>e.call(`browser`,`findTab`,[nge(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,rge(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[o$(t),s$(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[o$(t),s$(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[o$(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[o$(t),n]),fetch:(t,n,r={})=>tge(n,r).then(n=>e.call(`browser`,`evalAsync`,[o$(t),n])),websocket:ige(e)}}function o$(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 s$(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 c$(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 Zhe(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:c$(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Qhe(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:c$(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:c$(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:c$(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Zhe(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function $he(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 ege(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 tge(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 Qhe(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=$he(c),d=ege(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function nge(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 rge(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function ige(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=o$(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 l$(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 u$(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function d$(e){return e==null?[]:Array.isArray(e)?e:[e]}function f$(e,t){let n=t.handle,r=e=>({status:e.status,data:u$(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,l$(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,l$(r)])}}function age(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>f$(e,t)),request:async t=>f$(e,await e.call(`usb`,`request`,[d$(t)]))}}function p$(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?l$(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,l$(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function oge(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>p$(e,t)),request:async t=>p$(e,await e.call(`serial`,`request`,[d$(t)]))}}function m$(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:u$(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,l$(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,l$(r)]),receiveFeatureReport:async t=>u$((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 sge(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>m$(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[d$(t)]))[0];if(!n)throw Error(`No device selected.`);return m$(e,n)}}}function h$(){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 g$(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=h$(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&Che(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 cge(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=h$(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&pJ(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 lge=g$(),uge=cge();function _$(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?fge():uge({kind:e,ctx:t}):HK()&&typeof document<`u`?BJ(e,t):typeof Worker<`u`?dge():lge({kind:e,ctx:t})}function dge(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return v$(new Worker(new URL(`/assets/js-realm-worker-YxHAWyF7.js`,``+import.meta.url),{type:`module`}))}function fge(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return v$(new Worker(new URL(`/assets/py-realm-worker-C5_FcpVv.js`,``+import.meta.url),{type:`module`}))}function v$(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,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 pge(){if(HK()){let e=globalThis.chrome;if(e?.runtime?.getURL)return e.runtime.getURL(`pyodide/`)}if(VK())return decodeURIComponent(BK(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var y$=e(r(((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:()=>Ie,analyzeMetafileSync:()=>Be,build:()=>Me,buildSync:()=>Le,context:()=>Ne,default:()=>Je,formatMessages:()=>Fe,formatMessagesSync:()=>ze,initialize:()=>Ke,stop:()=>Ve,transform:()=>Pe,transformSync:()=>Re,version:()=>je}),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
|
|
6493
|
+
`:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof i$?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function Yhe(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 Xhe(e){return{findTab:t=>e.call(`browser`,`findTab`,[nge(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,rge(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[o$(t),s$(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[o$(t),s$(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[o$(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[o$(t),n]),fetch:(t,n,r={})=>tge(n,r).then(n=>e.call(`browser`,`evalAsync`,[o$(t),n])),websocket:ige(e)}}function o$(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 s$(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 c$(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 Zhe(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:c$(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Qhe(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:c$(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:c$(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:c$(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Zhe(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function $he(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 ege(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 tge(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 Qhe(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=$he(c),d=ege(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function nge(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 rge(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function ige(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=o$(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 l$(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 u$(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function d$(e){return e==null?[]:Array.isArray(e)?e:[e]}function f$(e,t){let n=t.handle,r=e=>({status:e.status,data:u$(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,l$(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,l$(r)])}}function age(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>f$(e,t)),request:async t=>f$(e,await e.call(`usb`,`request`,[d$(t)]))}}function p$(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?l$(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,l$(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function oge(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>p$(e,t)),request:async t=>p$(e,await e.call(`serial`,`request`,[d$(t)]))}}function m$(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:u$(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,l$(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,l$(r)]),receiveFeatureReport:async t=>u$((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 sge(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>m$(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[d$(t)]))[0];if(!n)throw Error(`No device selected.`);return m$(e,n)}}}function h$(){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 g$(){return async({kind:e})=>{if(e!==`js`)throw Error(`createInProcessJsRealmFactory: only kind:js is supported`);let{realmSide:t,hostSide:n}=h$(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`js`&&Che(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 cge(){return async({kind:e})=>{if(e!==`py`)throw Error(`createInProcessPyRealmFactory: only kind:py is supported`);let{realmSide:t,hostSide:n}=h$(),r=e=>{if(e.data?.type!==`realm-init`)return;t.removeEventListener(`message`,r);let n=e.data;n.kind===`py`&&pJ(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 lge=g$(),uge=cge();function _$(){return async({kind:e,ctx:t})=>e===`py`?typeof Worker<`u`?fge():uge({kind:e,ctx:t}):HK()&&typeof document<`u`?BJ(e,t):typeof Worker<`u`?dge():lge({kind:e,ctx:t})}function dge(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return v$(new Worker(new URL(`/assets/js-realm-worker-Bi5UIEMG.js`,``+import.meta.url),{type:`module`}))}function fge(){if(typeof Worker>`u`)throw Error(`realm-factory: Worker is not available in this runtime`);return v$(new Worker(new URL(`/assets/py-realm-worker-C5_FcpVv.js`,``+import.meta.url),{type:`module`}))}function v$(e){let t={postMessage:(t,n)=>n?e.postMessage(t,n):e.postMessage(t),addEventListener:(t,n)=>e.addEventListener(t,n),removeEventListener:(t,n)=>e.removeEventListener(t,n)},n=!1;return{controlPort:t,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 pge(){if(HK()){let e=globalThis.chrome;if(e?.runtime?.getURL)return e.runtime.getURL(`pyodide/`)}if(VK())return decodeURIComponent(BK(`pyodide/pyodide.mjs`,`../../../../../node_modules/pyodide/`).pathname)}var y$=e(r(((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:()=>Ie,analyzeMetafileSync:()=>Be,build:()=>Me,buildSync:()=>Le,context:()=>Ne,default:()=>Je,formatMessages:()=>Fe,formatMessagesSync:()=>ze,initialize:()=>Ke,stop:()=>Ve,transform:()=>Pe,transformSync:()=>Re,version:()=>je}),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
|
|
6494
6494
|
|
|
6495
6495
|
This indicates that your JavaScript environment is broken. You cannot use
|
|
6496
6496
|
esbuild in this environment because esbuild relies on this invariant. This
|
|
@@ -7185,7 +7185,7 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
7185
7185
|
`);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(`
|
|
7186
7186
|
`);e.length>1&&console.log(e.slice(0,-1).join(`
|
|
7187
7187
|
`)),s=e[e.length-1]}else throw Error(`Bad write`);return n.length};let c=[],l,u=0;n=({data:e})=>(e.length>0&&(c.push(e),l&&l()),d),o.read=(e,t,n,r,i,a)=>{if(e!==0||n!==0||r!==t.length||i!==null)throw Error(`Bad read`);if(c.length===0){l=()=>o.read(e,t,n,r,i,a);return}let s=c[0],d=Math.max(0,Math.min(r,s.length-u));t.set(s.subarray(u,u+d),n),u+=d,u===s.length&&(c.shift(),u=0),a(null,d)};let d=new r.Go;return d.argv=[``,`--service=0.28.1`],i(t,d).then(t=>{e(null),d.run(t)},t=>{e(t)}),d};function i(e,n){return t(this,null,function*(){if(e instanceof WebAssembly.Module)return WebAssembly.instantiate(e,n.importObject);let t=yield fetch(e);if(!t.ok)throw Error(`Failed to download ${JSON.stringify(e)}`);if(`instantiateStreaming`in WebAssembly&&/^application\/wasm($|;)/i.test(t.headers.get(`Content-Type`)||``))return(yield WebAssembly.instantiateStreaming(t,n.importObject)).instance;let r=yield t.arrayBuffer();return(yield WebAssembly.instantiate(r,n.importObject)).instance})}return e=>n(e)})(e=>r.onmessage({data:e})),t;r={onmessage:null,postMessage:n=>setTimeout(()=>{try{t=e({data:n})}catch(e){i(e)}}),terminate(){if(t)for(let e of t._scheduledTimeouts.values())clearTimeout(e)}}}let o,s,c=new Promise((e,t)=>{o=e,s=t});r.onmessage=({data:e})=>{r.onmessage=({data:e})=>u(e),e?s(e):o()},r.postMessage(t||new URL(e,location.href).toString());let{readFromStdout:u,service:d}=ye({writeToStdin(e){r.postMessage(e)},isSync:!1,hasFS:!1,esbuild:l});yield c,Ue=()=>{r.terminate(),He=void 0,Ue=void 0,We=void 0},We={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)})})}}),Je=l})(typeof t==`object`?t:{set exports(e){(typeof self<`u`?self:this).esbuild=e}})}))(),1);function b$(e){return WebAssembly.compile(e)}async function mge(e,t){return b$(await e(t))}const hge=y$.version;let x$=null;async function S$(e={}){return x$||=_ge(e.onProgress,e.ipk).catch(e=>{throw x$=null,e}),x$}async function gge(e){let t;try{t=await CK(`esbuild-wasm/package.json`,e.fromDir,e.reader)}catch{return null}if(t.type!==`file`)return null;let n=`${je(t.path).dir}/esbuild.wasm`;if(!await e.reader.exists(n))return null;try{return await e.readBytes(n)}catch{return null}}async function _ge(e,t){let n=e??(()=>{});if(VK())return n(`esbuild ready (node service)`),y$;if(!t)throw Error("esbuild-wasm is not available: install via `ipk add esbuild-wasm` or invoke through `ipx esbuild`");let r=await gge(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 b$(r);return await y$.initialize({wasmModule:i,worker:!HK()}),n(`esbuild ready`),y$}function C$(e){let t=e.startsWith(`/`)?e:`/${e}`;return new URL(`file://${t}`).href}function w$(e){return e instanceof Error?e.message:String(e)}function T$(e){return`${(e&&e.length>0?e:`[eval]`).replace(/\.[^./]+$/,``)}.js`}async function vge(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:T$(n),supported:{"dynamic-import":!1},define:{"import.meta.url":JSON.stringify(r)}})).code}async function yge(e,t,n,r){return(await(await e()).transform(t,{loader:`js`,format:`cjs`,sourcefile:T$(n),supported:{"dynamic-import":!1},...r?{define:{"import.meta.url":JSON.stringify(r)}}:{}})).code}const bge=/\bimport\s*\.\s*meta\s*\.\s*url\b/g,xge=/\bimport\s*\.\s*meta\b/g;function Sge(e,t){let n=JSON.stringify(t);return e.replace(bge,n).replace(xge,`({ url: ${n} })`)}async function E$(e,t,n,r){let i=await e();return i.transpileModule(Sge(t,r),{compilerOptions:{module:i.ModuleKind.CommonJS,target:i.ScriptTarget.ES2020,esModuleInterop:!0},fileName:`${n.replace(/\.[^./]+$/,``)}.ts`}).outputText}function Cge(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>S$(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>GK(t));return async({source:e,path:t,kind:i})=>{if(i!==`esm`||!yK(e))return e;let a=C$(t),o;try{return await vge(n,e,t,a)}catch(e){o=e}try{return await E$(r,e,t,a)}catch(e){throw Error(`Failed to transpile ESM module '${t}': ${w$(o)}; typescript fallback: ${w$(e)}`)}}}function wge(e={}){let{ipk:t}=e,n=e.loadEsbuild??(()=>S$(t?{ipk:t}:{})),r=e.loadTypeScript??(()=>GK(t));return async({source:e,filename:t})=>{if(!yK(e)&&!xK(e))return e;let i=typeof t==`string`&&t.startsWith(`/`),a=i?C$(t):void 0,o=i?t:`[eval].js`,s;try{return await yge(n,e,t,a)}catch(e){s=e}try{return await E$(r,e,o,a??``)}catch(e){throw Error(`Failed to transpile entry source: ${w$(s)}; typescript fallback: ${w$(e)}`)}}}function D$(e){if(!e.startsWith(`#!`))return e;let t=e.indexOf(`
|
|
7188
|
-
`);return t===-1?``:e.slice(t+1)}function Tge(e){return je(e).dir}const O$=[`node`,`require`,`default`],k$=[`node`,`import`,`default`],Ege=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,Dge=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,Oge=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,kge=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,Age=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function jge(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function A$(e){let t=vK(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!jge(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(Ege,`require`,`require`),r(Dge,`import`,`import`),r(Oge,`import`,`import`),r(kge,`import`,`export`),r(Age,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function Mge(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=D$(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 Nge(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??O$,s=e.importConditions??k$,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 Mge(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=Tge(e),p={};for(let{specifier:t,kind:i}of A$(n)){let n;try{n=await CK(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 CK(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 Pge(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||bW.has(e)||QQ.has(e))}async function Fge(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 A$(t))if(Pge(e))try{let t=await Nge({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?k$:O$,requireConditions:O$,importConditions:k$});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&&(yK(t)||xK(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 j$(){return globalThis.navigator?.hid??null}function M$(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function Ige(e,t){return e===t?!0:e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&M$(e)===M$(t)&&!!e.productName}var Lge=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(Ige(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 N$=null;function P$(){return N$||=new Lge,N$}const F$=4*1024*1024;function I$(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 L$(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function R$(e){e.opened||await e.open()}function z$(e,t){if(e>4194304)throw Error(`${t} exceeds the ${F$}-byte (4 MiB) v1 limit`)}function B$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function Rge(e,t){return(await t.getDevices()).map(t=>I$(e.register(t),t))}async function zge(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>I$(e.register(t),t))}function Bge(e,t){return I$(t,L$(e,t))}async function Vge(e,t){await L$(e,t).open()}async function Hge(e,t){await L$(e,t).close()}async function Uge(e,t,n,r){z$(r.byteLength,`send report payload`);let i=L$(e,t);await R$(i),await i.sendReport(n,r)}async function Wge(e,t,n,r){z$(r.byteLength,`send feature report payload`);let i=L$(e,t);await R$(i),await i.sendFeatureReport(n,r)}async function Gge(e,t,n){let r=L$(e,t);return await R$(r),{reportId:n,bytes:B$(await r.receiveFeatureReport(n))}}async function Kge(e,t,n){let r=L$(e,t);await R$(r);let i=e=>{n({reportId:e.reportId,bytes:B$(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const V$=6e4;function qge(){return m()}function Jge(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),V$);p(`hid-device`,e??[],void 0,{timeoutMs:V$}).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 H$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var Yge=class{registry;constructor(e){this.registry=e}hid(){let e=j$();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return Rge(this.registry,this.hid())}async request(e){if(qge()){let t=await Jge(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=>I$(this.registry.register(e),e))}return zge(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(Bge(this.registry,e))}open(e){return Vge(this.registry,e)}close(e){return Hge(this.registry,e)}sendReport(e,t,n){return Uge(this.registry,e,t,H$(n))}sendFeatureReport(e,t,n){return Wge(this.registry,e,t,H$(n))}async receiveFeatureReport(e,t){let n=await Gge(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return Kge(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},Xge=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:H$(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:H$(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 U$(e,t){return e&&j$()?new Yge(P$()):t?new Xge(t):null}function Zge(e){return async function(t,n){let r=t instanceof Request?t:null,i=Qge(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=e_e(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=n_e(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&&!t_e(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 Qge(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function $ge(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 e_e(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=$ge(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function t_e(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function n_e(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 W$(){return globalThis.navigator?.serial??null}var r_e=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 G$=null;function K$(){return G$||=new r_e,G$}const q$=4*1024*1024;function J$(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 Y$(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function i_e(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function a_e(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 o_e(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return J$(n,e.get(n))})}async function s_e(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return J$(i,e.get(i))}function c_e(e,t){return J$(t,Y$(e,t))}async function l_e(e,t,n){let r=Y$(e,t);await r.port.open(n),r.opened=!0}async function u_e(e,t){let n=Y$(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 d_e(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 f_e(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 p_e(e,t,n){let r=Y$(e,t),i=Math.min(n.maxBytes??4194304,q$),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=a_e(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=d_e(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=i_e(c,a.value);let e=u();if(e)return e}}return c}async function m_e(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${q$}-byte (4 MiB) v1 limit`);return await f_e(Y$(e,t)).write(n),n.length}async function h_e(e,t){return Y$(e,t).port.getSignals()}async function g_e(e,t,n){await Y$(e,t).port.setSignals(n)}const X$=6e4;function __e(){return m()}function v_e(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),X$);p(`serial-port`,e??[],void 0,{timeoutMs:X$}).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 Z$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var y_e=class{registry;constructor(e){this.registry=e}serial(){let e=W$();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return o_e(this.registry,this.serial())}async request(e){if(__e()){let t=await v_e(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 J$(r,this.registry.get(r))}return s_e(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(c_e(this.registry,e))}open(e,t){return l_e(this.registry,e,t)}close(e){return u_e(this.registry,e)}read(e,t){return p_e(this.registry,e,t)}write(e,t){return m_e(this.registry,e,t)}getSignals(e){return h_e(this.registry,e)}setSignals(e,t){return g_e(this.registry,e,t)}},b_e=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?Z$(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:Z$(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 Q$(e,t){return e&&W$()?new y_e(K$()):t?new b_e(t):null}function $$(){return globalThis.navigator?.usb??null}function x_e(e,t){return e===t?!0:e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var S_e=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(x_e(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 e1=null;function t1(){return e1||=new S_e,e1}const n1=4*1024*1024;function r1(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 i1(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function a1(e,t){if(e>4194304)throw Error(`${t} exceeds the ${n1}-byte (4 MiB) v1 limit`)}function o1(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function C_e(e,t){return(await t.getDevices()).map(t=>r1(e.register(t),t))}async function w_e(e,t,n){let r=await t.requestDevice({filters:n});return r1(e.register(r),r)}function T_e(e,t){return r1(t,i1(e,t))}async function E_e(e,t){await i1(e,t).open()}async function D_e(e,t){await i1(e,t).close()}async function s1(e,t,n){await i1(e,t).selectConfiguration(n)}async function O_e(e,t,n){await i1(e,t).claimInterface(n)}async function k_e(e,t,n){await i1(e,t).releaseInterface(n)}async function A_e(e,t,n,r){a1(r,`control-in length`);let i=await i1(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?o1(i.data):new ArrayBuffer(0)}}async function j_e(e,t,n,r){a1(r.byteLength,`control-out payload`);let i=await i1(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function M_e(e,t,n,r){a1(r,`transfer-in length`);let i=await i1(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?o1(i.data):new ArrayBuffer(0)}}async function N_e(e,t,n,r){a1(r.byteLength,`transfer-out payload`);let i=await i1(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function P_e(e,t){await i1(e,t).reset()}const c1=6e4;function F_e(){return m()}function I_e(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),c1);p(`usb-device`,e??[],void 0,{timeoutMs:c1}).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 l1(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var L_e=class{registry;constructor(e){this.registry=e}usb(){let e=$$();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return C_e(this.registry,this.usb())}async request(e){if(F_e()){let t=await I_e(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 r1(this.registry.register(n),n)}return w_e(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:!0))??null}info(e){return Promise.resolve(T_e(this.registry,e))}open(e){return E_e(this.registry,e)}close(e){return D_e(this.registry,e)}selectConfig(e,t){return s1(this.registry,e,t)}claim(e,t){return O_e(this.registry,e,t)}release(e,t){return k_e(this.registry,e,t)}async controlIn(e,t,n){let r=await A_e(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return j_e(this.registry,e,t,l1(n))}async transferIn(e,t,n){let r=await M_e(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return N_e(this.registry,e,t,l1(n))}reset(e){return P_e(this.registry,e)}},R_e=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:l1(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:l1(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function u1(e,t){return e&&$$()?new L_e(t1()):t?new R_e(t):null}const z_e=i(`realm-host`);function B_e(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;V_e(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 V_e(e,t,n,r,i,a){try{let o=await H_e(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=bve(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 H_e(e,t,n,r,i){switch(e.channel){case`vfs`:return q_e(e.op,e.args,t);case`exec`:return eve(e.op,e.args,t,i);case`fetch`:return ive(e.op,e.args,t);case`browser`:return cve(e.op,e.args,U_e(n),n);case`usb`:return _ve(e.op,e.args,W_e(n));case`serial`:return vve(e.op,e.args,G_e(n));case`hid`:return yve(e.op,e.args,K_e(n),r);case`module`:return ove(e.op,e.args,t);case`wasm`:return sve(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function U_e(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 d1(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 W_e(e){if(e.usbBackend)return e.usbBackend;let t=u1(fe(),M());if(!t)throw Error(`usb is not available in this runtime`);return t}function G_e(e){if(e.serialBackend)return e.serialBackend;let t=Q$(fe(),M());if(!t)throw Error(`serial is not available in this runtime`);return t}function K_e(e){if(e.hidBackend)return e.hidBackend;let t=U$(fe(),M());if(!t)throw Error(`hid is not available in this runtime`);return t}async function q_e(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 X_e(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await Z_e(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const f1=10485760;function p1(e){return e.fileCount>=500||e.totalBytes>=f1}async function J_e(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 Y_e(e,t,n,r){if(n>1048576){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0});return}if(r.totalBytes+n>f1){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 m1(e,t,n){if(p1(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(p1(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await J_e(e,t,r,n):i.isFile&&await Y_e(e,t,i.size,n)}}async function X_e(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await m1(e,t,n),t!==`/tmp`&&await m1(e,`/tmp`,n),{entries:n.entries}}async function Z_e(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 Q_e=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),$_e=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function eve(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 nve(t,n,r);if(e===`kill`)return rve(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function tve(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 nve(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??{};tve(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 rve(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Q_e.has(r)?r:`SIGTERM`;$_e.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 ive(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?Zge(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 ave(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 ove(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=ave(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return Fge({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:Cge({ipk:s}),transpileEntry:wge({ipk:s})})}async function sve(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 mge(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function cve(e,t,n,r){switch(e){case`findTab`:return uve(n,t[0]??{});case`ensureTab`:{let e=t[0];return dve(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return g1(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return g1(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return mve(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return hve(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await d1(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return d1(r).update(e,n)}case`wsClose`:{let e=t[0];return d1(r).close(e)}case`wsList`:return d1(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()=>n.screenshot(r))}case`waitForLoadState`:{let e=t[0],r=t[1];return pve(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function lve(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function h1(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=lve()?M():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){z_e.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function uve(e,t){let n=await h1(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=gve(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 dve(e,t,n){let r=await h1(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=v1(t);if(e){let t=r.find(t=>v1(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function g1(e,t,n,r){return e.withTab(t,async()=>fve(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function fve(e){if(typeof e!=`string`)return e;let t=_1(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=_1(t);if(typeof e==`object`&&e)return e}return t}return e}function _1(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 pve(e,t,n){if(n===`networkidle`)return e.withTab(t,async()=>{for(let t=0;t<20;t++){if(await e.evaluate(`(function(){
|
|
7188
|
+
`);return t===-1?``:e.slice(t+1)}function Tge(e){return je(e).dir}const O$=[`node`,`require`,`default`],k$=[`node`,`import`,`default`],Ege=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,Dge=/\bimport\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,Oge=/(?:^|[;\n}])\s*import\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,kge=/(?:^|[;\n}])\s*export\b[\s\S]*?\bfrom\s*(['"])([^'"]+)\1/g,Age=/(?:^|[;\n}])\s*import\s*(['"])([^'"]+)\1/g;function jge(e,t,n){let r=t[0].indexOf(n);return r<0?!1:e.startsWith(n,t.index+r)}function A$(e){let t=vK(e),n=new Map,r=(r,i,a)=>{r.lastIndex=0;let o;for(;(o=r.exec(e))!==null;){if(!jge(t,o,a))continue;let e=o[2];n.get(e)!==`import`&&n.set(e,i)}};return r(Ege,`require`,`require`),r(Dge,`import`,`import`),r(Oge,`import`,`import`),r(kge,`import`,`export`),r(Age,`import`,`import`),[...n].map(([e,t])=>({specifier:e,kind:t}))}async function Mge(e,t,n,r){if(n===`json`)return`module.exports = JSON.parse(${JSON.stringify(e)});\n`;let i=D$(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 Nge(e){let{entrySpecifiers:t,fromDir:n,reader:r,conditions:i,transpile:a}=e,o=e.requireConditions??O$,s=e.importConditions??k$,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 Mge(n,e,t,a);l.set(e,{path:e,source:n,cjsSource:i,kind:t});let c=Tge(e),p={};for(let{specifier:t,kind:i}of A$(n)){let n;try{n=await CK(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 CK(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 Pge(e){return!(e.startsWith(`sliccy:`)||e.startsWith(`node:`)||bW.has(e)||QQ.has(e))}async function Fge(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 A$(t))if(Pge(e))try{let t=await Nge({entrySpecifiers:[e],fromDir:n,reader:i,transpile:a,conditions:r===`import`?k$:O$,requireConditions:O$,importConditions:k$});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&&(yK(t)||xK(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 j$(){return globalThis.navigator?.hid??null}function M$(e){let t=e.collections?.[0];return t?`${t.usagePage??``}:${t.usage??``}`:``}function Ige(e,t){return e===t?!0:e.vendorId===t.vendorId&&e.productId===t.productId&&(e.productName??``)===(t.productName??``)&&M$(e)===M$(t)&&!!e.productName}var Lge=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(Ige(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 N$=null;function P$(){return N$||=new Lge,N$}const F$=4*1024*1024;function I$(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 L$(e,t){let n=e.get(t);if(!n)throw Error(`unknown hid handle '${t}'`);return n}async function R$(e){e.opened||await e.open()}function z$(e,t){if(e>4194304)throw Error(`${t} exceeds the ${F$}-byte (4 MiB) v1 limit`)}function B$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),t}async function Rge(e,t){return(await t.getDevices()).map(t=>I$(e.register(t),t))}async function zge(e,t,n){let r=await t.requestDevice({filters:n});if(r.length===0)throw Error(`No device selected.`);return r.map(t=>I$(e.register(t),t))}function Bge(e,t){return I$(t,L$(e,t))}async function Vge(e,t){await L$(e,t).open()}async function Hge(e,t){await L$(e,t).close()}async function Uge(e,t,n,r){z$(r.byteLength,`send report payload`);let i=L$(e,t);await R$(i),await i.sendReport(n,r)}async function Wge(e,t,n,r){z$(r.byteLength,`send feature report payload`);let i=L$(e,t);await R$(i),await i.sendFeatureReport(n,r)}async function Gge(e,t,n){let r=L$(e,t);return await R$(r),{reportId:n,bytes:B$(await r.receiveFeatureReport(n))}}async function Kge(e,t,n){let r=L$(e,t);await R$(r);let i=e=>{n({reportId:e.reportId,bytes:B$(e.data)})};return r.addEventListener(`inputreport`,i),()=>r.removeEventListener(`inputreport`,i)}const V$=6e4;function qge(){return m()}function Jge(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),V$);p(`hid-device`,e??[],void 0,{timeoutMs:V$}).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 H$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var Yge=class{registry;constructor(e){this.registry=e}hid(){let e=j$();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}list(){return Rge(this.registry,this.hid())}async request(e){if(qge()){let t=await Jge(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=>I$(this.registry.register(e),e))}return zge(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(Bge(this.registry,e))}open(e){return Vge(this.registry,e)}close(e){return Hge(this.registry,e)}sendReport(e,t,n){return Uge(this.registry,e,t,H$(n))}sendFeatureReport(e,t,n){return Wge(this.registry,e,t,H$(n))}async receiveFeatureReport(e,t){let n=await Gge(this.registry,e,t);return{reportId:n.reportId,bytes:new Uint8Array(n.bytes)}}async subscribeInputReports(e,t){return Kge(this.registry,e,e=>t({reportId:e.reportId,bytes:new Uint8Array(e.bytes)}))}},Xge=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:H$(n)})}async sendFeatureReport(e,t,n){await this.rpc.call(`hid-send-feature-report`,{handle:e,reportId:t,bytes:H$(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 U$(e,t){return e&&j$()?new Yge(P$()):t?new Xge(t):null}function Zge(e){return async function(t,n){let r=t instanceof Request?t:null,i=Qge(t),a=(n?.method??r?.method??`GET`).toUpperCase(),o=e_e(r?.headers,n?.headers),s,c;if(n&&`body`in n&&n.body!==void 0)s=n_e(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&&!t_e(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 Qge(e){return typeof e==`string`?e:e instanceof URL?e.toString():e.url}function $ge(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 e_e(e,t){let n={};e&&e.forEach((e,t)=>{n[t]=e});let r=$ge(t);if(r)for(let[e,t]of Object.entries(r))n[e]=t;return n}function t_e(e,t){let n=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===n)return!0;return!1}function n_e(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 W$(){return globalThis.navigator?.serial??null}var r_e=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 G$=null;function K$(){return G$||=new r_e,G$}const q$=4*1024*1024;function J$(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 Y$(e,t){let n=e.get(t);if(!n)throw Error(`unknown serial handle '${t}'`);return n}function i_e(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function a_e(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 o_e(e,t){return(await t.getPorts()).map(t=>{let n=e.register(t);return J$(n,e.get(n))})}async function s_e(e,t,n){let r=await t.requestPort(n.length?{filters:n}:{}),i=e.register(r);return J$(i,e.get(i))}function c_e(e,t){return J$(t,Y$(e,t))}async function l_e(e,t,n){let r=Y$(e,t);await r.port.open(n),r.opened=!0}async function u_e(e,t){let n=Y$(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 d_e(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 f_e(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 p_e(e,t,n){let r=Y$(e,t),i=Math.min(n.maxBytes??4194304,q$),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=a_e(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=d_e(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=i_e(c,a.value);let e=u();if(e)return e}}return c}async function m_e(e,t,n){if(n.length>4194304)throw Error(`serial write payload exceeds the ${q$}-byte (4 MiB) v1 limit`);return await f_e(Y$(e,t)).write(n),n.length}async function h_e(e,t){return Y$(e,t).port.getSignals()}async function g_e(e,t,n){await Y$(e,t).port.setSignals(n)}const X$=6e4;function __e(){return m()}function v_e(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),X$);p(`serial-port`,e??[],void 0,{timeoutMs:X$}).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 Z$(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var y_e=class{registry;constructor(e){this.registry=e}serial(){let e=W$();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}list(){return o_e(this.registry,this.serial())}async request(e){if(__e()){let t=await v_e(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 J$(r,this.registry.get(r))}return s_e(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(c_e(this.registry,e))}open(e,t){return l_e(this.registry,e,t)}close(e){return u_e(this.registry,e)}read(e,t){return p_e(this.registry,e,t)}write(e,t){return m_e(this.registry,e,t)}getSignals(e){return h_e(this.registry,e)}setSignals(e,t){return g_e(this.registry,e,t)}},b_e=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?Z$(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:Z$(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 Q$(e,t){return e&&W$()?new y_e(K$()):t?new b_e(t):null}function $$(){return globalThis.navigator?.usb??null}function x_e(e,t){return e===t?!0:e.vendorId===t.vendorId&&e.productId===t.productId&&(e.serialNumber??``)===(t.serialNumber??``)&&!!e.serialNumber}var S_e=class{byHandle=new Map;counter=0;register(e){for(let[t,n]of this.byHandle)if(x_e(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 e1=null;function t1(){return e1||=new S_e,e1}const n1=4*1024*1024;function r1(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 i1(e,t){let n=e.get(t);if(!n)throw Error(`unknown usb handle '${t}'`);return n}function a1(e,t){if(e>4194304)throw Error(`${t} exceeds the ${n1}-byte (4 MiB) v1 limit`)}function o1(e){return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}async function C_e(e,t){return(await t.getDevices()).map(t=>r1(e.register(t),t))}async function w_e(e,t,n){let r=await t.requestDevice({filters:n});return r1(e.register(r),r)}function T_e(e,t){return r1(t,i1(e,t))}async function E_e(e,t){await i1(e,t).open()}async function D_e(e,t){await i1(e,t).close()}async function s1(e,t,n){await i1(e,t).selectConfiguration(n)}async function O_e(e,t,n){await i1(e,t).claimInterface(n)}async function k_e(e,t,n){await i1(e,t).releaseInterface(n)}async function A_e(e,t,n,r){a1(r,`control-in length`);let i=await i1(e,t).controlTransferIn(n,r);return{status:i.status??`ok`,bytes:i.data?o1(i.data):new ArrayBuffer(0)}}async function j_e(e,t,n,r){a1(r.byteLength,`control-out payload`);let i=await i1(e,t).controlTransferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function M_e(e,t,n,r){a1(r,`transfer-in length`);let i=await i1(e,t).transferIn(n,r);return{status:i.status??`ok`,bytes:i.data?o1(i.data):new ArrayBuffer(0)}}async function N_e(e,t,n,r){a1(r.byteLength,`transfer-out payload`);let i=await i1(e,t).transferOut(n,r);return{status:i.status??`ok`,bytesWritten:i.bytesWritten}}async function P_e(e,t){await i1(e,t).reset()}const c1=6e4;function F_e(){return m()}function I_e(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,clearTimeout(i),t(e))},i=setTimeout(()=>r({cancelled:!0}),c1);p(`usb-device`,e??[],void 0,{timeoutMs:c1}).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 l1(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}var L_e=class{registry;constructor(e){this.registry=e}usb(){let e=$$();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}list(){return C_e(this.registry,this.usb())}async request(e){if(F_e()){let t=await I_e(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 r1(this.registry.register(n),n)}return w_e(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:!0))??null}info(e){return Promise.resolve(T_e(this.registry,e))}open(e){return E_e(this.registry,e)}close(e){return D_e(this.registry,e)}selectConfig(e,t){return s1(this.registry,e,t)}claim(e,t){return O_e(this.registry,e,t)}release(e,t){return k_e(this.registry,e,t)}async controlIn(e,t,n){let r=await A_e(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}controlOut(e,t,n){return j_e(this.registry,e,t,l1(n))}async transferIn(e,t,n){let r=await M_e(this.registry,e,t,n);return{status:r.status,bytes:new Uint8Array(r.bytes)}}transferOut(e,t,n){return N_e(this.registry,e,t,l1(n))}reset(e){return P_e(this.registry,e)}},R_e=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:l1(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:l1(n)})}async reset(e){await this.rpc.call(`usb-reset`,{handle:e})}};function u1(e,t){return e&&$$()?new L_e(t1()):t?new R_e(t):null}const z_e=i(`realm-host`);function B_e(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;V_e(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 V_e(e,t,n,r,i,a){try{let o=await H_e(t,n,r,i,a),s={type:`realm-rpc-res`,id:t.id,result:o},c=bve(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 H_e(e,t,n,r,i){switch(e.channel){case`vfs`:return q_e(e.op,e.args,t);case`exec`:return eve(e.op,e.args,t,i);case`fetch`:return ive(e.op,e.args,t);case`browser`:return cve(e.op,e.args,U_e(n),n);case`usb`:return _ve(e.op,e.args,W_e(n));case`serial`:return vve(e.op,e.args,G_e(n));case`hid`:return yve(e.op,e.args,K_e(n),r);case`module`:return ove(e.op,e.args,t);case`wasm`:return sve(e.op,e.args,t);default:throw Error(`realm-host: unknown channel '${e.channel}'`)}}function U_e(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 d1(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 W_e(e){if(e.usbBackend)return e.usbBackend;let t=u1(fe(),M());if(!t)throw Error(`usb is not available in this runtime`);return t}function G_e(e){if(e.serialBackend)return e.serialBackend;let t=Q$(fe(),M());if(!t)throw Error(`serial is not available in this runtime`);return t}function K_e(e){if(e.hidBackend)return e.hidBackend;let t=U$(fe(),M());if(!t)throw Error(`hid is not available in this runtime`);return t}async function q_e(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 X_e(n,typeof t[0]==`string`?t[0]:n.cwd);case`flushWrites`:{let e=t[0];return await Z_e(n,e),!0}default:throw Error(`realm-host: unknown vfs op '${e}'`)}}const f1=10485760;function p1(e){return e.fileCount>=500||e.totalBytes>=f1}async function J_e(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 Y_e(e,t,n,r){if(n>1048576){r.entries.push({path:t,content:new Uint8Array,isDirectory:!1,truncated:!0});return}if(r.totalBytes+n>f1){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 m1(e,t,n){if(p1(n)||!await e.fs.exists(t))return;let r=[t];for(;r.length>0;){if(p1(n))return;let t=r.pop(),i;try{i=await e.fs.stat(t)}catch{continue}i.isDirectory?await J_e(e,t,r,n):i.isFile&&await Y_e(e,t,i.size,n)}}async function X_e(e,t){let n={entries:[],totalBytes:0,fileCount:0};return await m1(e,t,n),t!==`/tmp`&&await m1(e,`/tmp`,n),{entries:n.entries}}async function Z_e(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 Q_e=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`,`SIGSTOP`,`SIGCONT`]),$_e=new Set([`SIGINT`,`SIGTERM`,`SIGKILL`]);async function eve(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 nve(t,n,r);if(e===`kill`)return rve(t,r);throw Error(`realm-host: unknown exec op '${e}'`)}function tve(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 nve(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??{};tve(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 rve(e,t){let[n,r]=e,i=t.spawns.get(n);if(!i)return!1;let a=typeof r==`string`&&Q_e.has(r)?r:`SIGTERM`;$_e.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 ive(e,t,n){if(e!==`request`)throw Error(`realm-host: unknown fetch op '${e}'`);let[r,i]=t,a=await(n.fetch?Zge(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 ave(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 ove(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=ave(n),s={reader:o,readBytes:e=>n.fs.readFileBuffer(e),fromDir:i};return Fge({entryCode:r,fromDir:i,entryFilename:a,reader:o,transpile:Cge({ipk:s}),transpileEntry:wge({ipk:s})})}async function sve(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 mge(e=>n.fs.readFileBuffer(e),n.fs.resolvePath(n.cwd,r))}async function cve(e,t,n,r){switch(e){case`findTab`:return uve(n,t[0]??{});case`ensureTab`:{let e=t[0];return dve(n,e,t[1]??{})}case`eval`:{let e=t[0],r=t[1];return g1(n,e,r,!1)}case`evalAsync`:{let e=t[0],r=t[1];return g1(n,e,r,!0)}case`cookie`:{let e=t[0],r=t[1];return mve(n,e,r)}case`localStorage`:{let e=t[0],r=t[1];return hve(n,e,r)}case`wsObserve`:{let e={...t[0],scoopJid:r.scoopJid};return await d1(r).observe(e)}case`wsUpdate`:{let e=t[0],n=t[1]??{};return d1(r).update(e,n)}case`wsClose`:{let e=t[0];return d1(r).close(e)}case`wsList`:return d1(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 pve(n,e,r)}default:throw Error(`realm-host: unknown browser op '${e}'`)}}function lve(){try{let e=globalThis.localStorage;return e?!!(e.getItem(`slicc.trayWorkerBaseUrl`)||e.getItem(`slicc.trayJoinUrl`)):!1}catch{return!1}}async function h1(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=lve()?M():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){z_e.debug(`panel-rpc list-remote-targets failed`,{err:String(e)})}return t}async function uve(e,t){let n=await h1(e);if(t.domain){let e=t.domain.toLowerCase();for(let t of n){let n=gve(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 dve(e,t,n){let r=await h1(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=v1(t);if(e){let t=r.find(t=>v1(t.url)===e);if(t)return t}}return{targetId:await e.createPage(t),url:t,title:``}}async function g1(e,t,n,r){return e.withTab(t,async()=>fve(await e.evaluate(n,{awaitPromise:r,returnByValue:!0})))}function fve(e){if(typeof e!=`string`)return e;let t=_1(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=_1(t);if(typeof e==`object`&&e)return e}return t}return e}function _1(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 pve(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(){
|
|
7189
7189
|
try {
|
|
7190
7190
|
var entries = performance.getEntriesByType('resource');
|
|
7191
7191
|
var now = performance.now();
|
|
@@ -7198,7 +7198,7 @@ ${n}:${r}:${i}: ERROR: ${e.pluginName?`[plugin: ${e.pluginName}] `:``}${e.text}`
|
|
|
7198
7198
|
} catch (e) {
|
|
7199
7199
|
return true;
|
|
7200
7200
|
}
|
|
7201
|
-
})()`,{returnByValue:!0}))return
|
|
7201
|
+
})()`,{returnByValue:!0}))return})}async function mve(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 hve(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 gve(e){try{return new URL(e).hostname}catch{return null}}function v1(e){try{return new URL(e).origin}catch{return null}}async function _ve(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 vve(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 yve(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 bve(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 y1(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=B_e(r.controlPort,e.ctx,{...e.owner.scoopJid===void 0?{}:{scoopJid:e.owner.scoopJid},pm:e.pm,owner:e.owner,ppid:n.pid});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+`
|
|
7202
7202
|
`,exitCode:1},1)}},c=e=>{d({stdout:``,stderr:(e.message??`realm error`)+`
|
|
7203
7203
|
`,exitCode:1},1)},l=()=>{d({stdout:``,stderr:`realm-runner: worker message could not be deserialized
|
|
7204
7204
|
`,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 xve=new TextDecoder(`utf-8`,{fatal:!1});new TextEncoder;function b1(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 xve.decode(n)}function x1(e){return e}async function Sve(e,t,n,r,i={}){return await n.fs.exists(e)?S1(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 S1(e,t,n,r,i={}){let a=i.realmFactory??Cve(),o=r?.processManager??Tve()??wve(),s=r?.owner??{kind:`system`},c=i.filename??t[1]??`<eval>`;return await y1({pm:o,realmFactory:a,owner:s,kind:`js`,code:e,argv:t,env:Object.fromEntries(n.env.entries()),cwd:n.cwd,filename:c,stdin:x1(n.stdin),ctx:n,ppid:r?.getParentPid?.()})}function Cve(){return typeof Worker<`u`||typeof document<`u`?_$():g$()}let C1=null;function wve(){return C1||=new vW,C1}function Tve(){let e=globalThis.__slicc_pm;return e&&typeof e==`object`&&typeof e.spawn==`function`&&typeof e.onSignal==`function`?e:null}function Eve(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}const Dve=[`/workspace`,`/shared`];async function Ove(e){let t=[],n=new Set;for(let r of Dve)await e.exists(r)&&await kve(e,r,t,n);return t}async function kve(e,t,n,r){for await(let i of e.walk(t)){if(!i.endsWith(`.bsh`)||r.has(i))continue;r.add(i);let t=Ave(i);if(!t)continue;let a=await e.readFile(i,{encoding:`utf-8`}),o=jve(typeof a==`string`?a:new TextDecoder().decode(a));n.push({path:i,hostnamePattern:t,matchPatterns:o})}}function Ave(e){let t=e.split(`/`).pop()??``;if(!t.endsWith(`.bsh`))return null;let n=t.slice(0,-4);return n?n.startsWith(`-.`)?`*`+n.slice(1):n:null}function jve(e){let t=e.split(`
|
|
@@ -7917,8 +7917,8 @@ Options:
|
|
|
7917
7917
|
`;case`idle`:return`enhanced engine: not downloaded (run hear --warmup)
|
|
7918
7918
|
`;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 l6(e){return{stdout:``,stderr:`hear: ${e}\n`,exitCode:1}}function u6(e){return e instanceof Error?e.message:String(e)}function d6(e){let t=e.map((e,t)=>`${e.deviceId}\t${e.label||`Microphone ${t+1}`}`);return t.join(`
|
|
7919
7919
|
`)+(t.length?`
|
|
7920
|
-
`:``)}async function Nwe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:d6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:l6(`device enumeration unavailable`):{stdout:d6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return l6(u6(e))}}async function Pwe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-
|
|
7921
|
-
`,stderr:``,exitCode:0}}catch(e){return l6(`transcription failed: ${u6(e)}`)}}async function Iwe(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-
|
|
7920
|
+
`:``)}async function Nwe(e){try{return e.local?navigator.mediaDevices?.enumerateDevices?{stdout:d6((await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)),stderr:``,exitCode:0}:l6(`device enumeration unavailable`):{stdout:d6((await e.panelRpc.call(`enumerate-media-devices`,void 0)).audioinputs),stderr:``,exitCode:0}}catch(e){return l6(u6(e))}}async function Pwe(e,t){try{if(e.local){let{hearStatus:e,hearWarmup:n}=await import(`./hear-0Tswpuv7.js`);return{stdout:c6(t?n():e()),stderr:``,exitCode:0}}return{stdout:c6(t?await e.panelRpc.call(`hear-warmup`,void 0):await e.panelRpc.call(`hear-status`,void 0)),stderr:``,exitCode:0}}catch(e){return l6(u6(e))}}async function Fwe(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 l6(`cannot open ${r}: No such file`)}let o=PK(i);if(!o.startsWith(`audio/`)&&!o.startsWith(`video/`))return l6(`${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-0Tswpuv7.js`)).hearTranscribe(s,t.lang):await e.panelRpc.call(`hear-transcribe`,{bytes:s,lang:t.lang},{timeoutMs:6e5})).transcript+`
|
|
7921
|
+
`,stderr:``,exitCode:0}}catch(e){return l6(`transcription failed: ${u6(e)}`)}}async function Iwe(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-0Tswpuv7.js`)).hearCapture(r):await e.panelRpc.call(`hear-capture`,r,{timeoutMs:n+3e4});return i.transcript?{stdout:i.transcript+`
|
|
7922
7922
|
`,stderr:``,exitCode:0}:{stdout:``,stderr:`hear: no speech detected
|
|
7923
7923
|
`,exitCode:1}}catch(e){return l6(u6(e))}}function Lwe(){return AO(`hear`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return kwe();let n=Mwe(e);if(`exitCode`in n)return n;let r={local:fe(),panelRpc:M()};return!r.local&&!r.panelRpc?l6(`speech recognition unavailable in this environment`):n.devices?Nwe(r):n.status||n.warmup?Pwe(r,n.warmup):n.inputFile?Fwe(r,n,t):Iwe(r,n)})}const f6=[`playwright-cli`,`playwright`,`puppeteer`],p6=new WeakMap;function Rwe(e,t){let n=p6.get(e);n||(n=new WeakMap,p6.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 m6(e){let t=e.match(/^(f[0-9]+)(e[0-9]+)$/);return t?{framePrefix:t[1],isIframe:!0}:{framePrefix:``,isIframe:!1}}const h6=c,zwe=new Set([`click`,`dblclick`,`fill`,`type`,`press`,`goto`,`navigate`,`select`,`check`,`uncheck`,`drag`,`dialog-accept`,`dialog-dismiss`,`drop`]);function g6(e){return e.toISOString().replace(/:/g,`-`)}function Bwe(e){return e instanceof b||typeof e==`object`&&e&&`code`in e?e.code===`EEXIST`:e instanceof Error&&e.message.includes(`EEXIST`)}const _6=`function(text) {
|
|
7924
7924
|
const el = this;
|
|
@@ -8583,7 +8583,7 @@ Common base URLs:
|
|
|
8583
8583
|
llama.cpp http://localhost:8080/v1
|
|
8584
8584
|
vLLM http://localhost:8000/v1
|
|
8585
8585
|
Jan http://localhost:1337/v1
|
|
8586
|
-
`}function NOe(){return AO(b5,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:MOe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-
|
|
8586
|
+
`}function NOe(){return AO(b5,async e=>{if(e.includes(`--help`)||e.includes(`-h`))return{stdout:MOe(),stderr:``,exitCode:0};let{getApiKeyForProvider:t,getRawApiKeyForProvider:n,getBaseUrlForProvider:r,addAccount:i}=await import(`./provider-settings-B2s5vgom.js`),{verifyConnection:a}=await Promise.resolve().then(()=>l5),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(b5);if(!s)return{stdout:``,stderr:`Local LLM is not configured. Open Settings → Providers → Local LLM and set a base URL.
|
|
8587
8587
|
`,exitCode:1};let c=await a(s,t(b5)??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(`
|
|
8588
8588
|
`)+`
|
|
8589
8589
|
`,exitCode:1}}return o===`discover`?(i(b5,n(b5)??``,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(`
|
|
@@ -8630,20 +8630,20 @@ authorization-code flow, stores the access token, and retries.
|
|
|
8630
8630
|
On success, the server is persisted to /workspace/.mcp/servers.json and
|
|
8631
8631
|
an alias shim is written to /workspace/.mcp/aliases/<name>.jsh so the
|
|
8632
8632
|
short name resolves on the PATH.
|
|
8633
|
-
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return A5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return A5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return A5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-
|
|
8633
|
+
`);let n=e.filter(e=>!e.startsWith(`--`));if(n.length<2)return A5(`mcp add: expected <url> <name>`);let[r,i]=n;if(!/^https?:\/\//i.test(r))return A5(`mcp add: invalid URL "${r}" (must start with http:// or https://)`);if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(i))return A5(`mcp add: invalid name "${i}" (letters, digits, _ and - only; must start with a letter)`);let{getServer:a,setServer:o}=await import(`./store-BZTffu8V.js`).then(e=>e.r);if(await a(i,t.fs))return A5(`mcp add: a server named "${i}" already exists`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>x5),l=new s({url:r,fetchImpl:t.fetchImpl}),u;try{await l.initialize()}catch(e){if(!(e instanceof c))throw e;u=await WOe(r,i,e.resourceMetadataUrl,t),l=new s({url:r,fetchImpl:t.fetchImpl,getAuthHeader:()=>P5(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 uke(i,t);let m=await L5(i,f,t);if(u){let{registerMcpProvider:e}=await import(`./provider-BWME-twj.js`);e({name:i,serverUrl:r,auth:u})}return k5([`Added MCP server "${i}" → ${r}`,` tools: ${d.length}, apps: ${f.length} (${m} sprinkle${m===1?``:`s`})`,` alias: ${O5}/${i}.jsh`,u?` auth: oauth (provider mcp:${i})`:` auth: none`].join(`
|
|
8634
8634
|
`)+`
|
|
8635
|
-
`)}async function WOe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-
|
|
8636
|
-
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-
|
|
8635
|
+
`)}async function WOe(e,t,n,r){let{discoverAuth:i,dynamicRegister:a,runAuthFlow:o}=await import(`./oauth-Czw-MuuR.js`),{saveOAuthAccount:s}=await import(`./provider-settings-B2s5vgom.js`),c=await cke(r.oauthFetchImpl),l=r.oauthLauncher??await F5(),u=await i(e,n,c);D5.debug(`MCP OAuth discovery succeeded`,{name:t,serverUrl:e,discoveryPath:u.discoveryPath,issuer:u.issuer});let d=await ske(),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 GOe(e,t){if(e.includes(`--help`)||e.includes(`-h`))return k5(`usage: mcp list
|
|
8636
|
+
`);let{ensureAllMcpProvidersRegistered:n}=await import(`./provider-BWME-twj.js`);await n();let{listServers:r}=await import(`./store-BZTffu8V.js`).then(e=>e.r),i=await r(t.fs),a=Object.keys(i).sort();if(a.length===0)return k5("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 k5(j5(o))}function j5(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(`
|
|
8637
8637
|
`)+`
|
|
8638
8638
|
`}async function KOe(e,t){if(e[0]===`--help`||e[0]===`-h`)return k5(`usage: mcp search <query>
|
|
8639
8639
|
|
|
8640
8640
|
Case-insensitive substring search across the cached tools of every
|
|
8641
8641
|
registered MCP server. Matches tool name OR description and prints a
|
|
8642
8642
|
table of (server, tool, description, match-field) rows.
|
|
8643
|
-
`);if(e.length===0)return A5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-
|
|
8644
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-
|
|
8643
|
+
`);if(e.length===0)return A5(`mcp search: expected <query>`);let n=e[0],r=n.toLowerCase(),{ensureAllMcpProvidersRegistered:i}=await import(`./provider-BWME-twj.js`);await i();let{listServers:a}=await import(`./store-BZTffu8V.js`).then(e=>e.r),o=await a(t.fs),s=Object.keys(o).sort();if(s.length===0)return k5("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 k5(`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,qOe(e.description),e.match]);return k5(j5(l))}function qOe(e){if(!e)return``;let t=e.replace(/\s+/g,` `).trim();return t.length<=60?t:t.slice(0,59)+`…`}async function JOe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?A5(`mcp delete: expected <name>`):k5(`usage: mcp delete <name>
|
|
8644
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r,removeMcpProvider:i}=await import(`./provider-BWME-twj.js`);await r(n);let{deleteServer:a}=await import(`./store-BZTffu8V.js`).then(e=>e.r),o=await a(n,t.fs);await dke(n,t),await fke(n,t);let s=`mcp:${n}`,c=!1;try{let{removeAccount:e,getAccounts:t}=await import(`./provider-settings-B2s5vgom.js`);t().some(e=>e.providerId===s)&&(await e(s),c=!0)}catch(e){D5.warn(`mcp delete: OAuth removal failed`,{providerId:s,error:e instanceof Error?e.message:String(e)})}let l=i(n);return!o&&!c&&!l?A5(`mcp delete: no server, alias, or account found for "${n}"`):k5([`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(`
|
|
8645
8645
|
`)+`
|
|
8646
|
-
`)}async function YOe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?A5(`mcp invoke: expected <name>`):k5(ZOe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-
|
|
8646
|
+
`)}async function YOe(e,t){if(e.length===0||e[0]===`--help`||e[0]===`-h`)return e.length===0?A5(`mcp invoke: expected <name>`):k5(ZOe());let n=e[0],r=e.slice(1),{ensureMcpProviderRegistered:i}=await import(`./provider-BWME-twj.js`);await i(n);let{getServer:a}=await import(`./store-BZTffu8V.js`).then(e=>e.r),o=await a(n,t.fs);if(!o)return A5(`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 k5(QOe(n,o,s));let c=r[0],l=s.find(e=>e.name===c);if(!l)return A5(`mcp invoke: unknown tool "${c}" on "${n}" (run \`${n}\` to list tools)`);let{timeoutMs:u,remaining:d,warnings:f}=XOe(r.slice(1));if(d.includes(`--help`)||d.includes(`-h`))return k5($Oe(n,l));let p=eke(d,l.inputSchema);if(!p.ok)return A5(`mcp invoke: ${p.error}`);let{McpClient:m}=await Promise.resolve().then(()=>x5),h=new m({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>P5(n):void 0,...u===void 0?{}:{timeoutMs:u}});await h.initialize();let g=ike(await h.toolsCall(c,p.value));return f.length>0&&(g.stderr=f.map(e=>`${e}\n`).join(``)+g.stderr),g}function XOe(e){let t=[],n=[],r,i=0;for(;i<e.length;){let a=e[i];if(a.startsWith(`--timeout=`)){let e=M5(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=M5(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 M5(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 ZOe(){return`usage: mcp invoke <name> [tool] [--timeout <seconds>] [--flag value …]
|
|
8647
8647
|
|
|
8648
8648
|
mcp invoke <name> List tools on <name>.
|
|
8649
8649
|
mcp invoke <name> <tool> --help Show flags for <tool>.
|
|
@@ -8673,7 +8673,7 @@ Arguments are coerced according to the tool's JSON Schema:
|
|
|
8673
8673
|
|
|
8674
8674
|
Re-fetches the tool catalog and \`apps/list\` for <name>. Does NOT refresh
|
|
8675
8675
|
OAuth tokens — for OAuth token refresh use \`mcp auth <name>\`.
|
|
8676
|
-
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-
|
|
8676
|
+
`);let n=e[0],{ensureMcpProviderRegistered:r}=await import(`./provider-BWME-twj.js`);await r(n);let{getServer:i,setServer:a}=await import(`./store-BZTffu8V.js`).then(e=>e.r),o=await i(n,t.fs);if(!o)return A5(`mcp refresh: unknown server "${n}"`);let{McpClient:s,McpAuthRequiredError:c}=await Promise.resolve().then(()=>x5),l=new s({url:o.url,fetchImpl:t.fetchImpl,headers:o.headers,getAuthHeader:o.auth?()=>P5(n):void 0});try{await l.initialize()}catch(e){if(e instanceof c)return A5(`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 L5(n,d,t);return k5(`Refreshed "${n}" — tools: ${u.length}, apps: ${d.length} (${f} sprinkle${f===1?``:`s`})\n`)}async function oke(e,t){if(e.includes(`--help`)||e.includes(`-h`))return k5(`usage: mcp auth <name> [--silent | --interactive]
|
|
8677
8677
|
|
|
8678
8678
|
Re-authenticate an existing MCP server. By default, attempts a silent
|
|
8679
8679
|
token renewal using the persisted refresh_token; if that returns no
|
|
@@ -8685,7 +8685,7 @@ Options:
|
|
|
8685
8685
|
-i, --interactive Skip silent renewal and open the OAuth popup
|
|
8686
8686
|
directly. Use after revoking a refresh token or
|
|
8687
8687
|
when the AS no longer accepts the cached one.
|
|
8688
|
-
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return A5(`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 A5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-
|
|
8688
|
+
`);let n=e.filter(e=>!e.startsWith(`-`));if(n.length===0)return A5(`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 A5(`mcp auth: --silent and --interactive are mutually exclusive`);let{ensureMcpProviderRegistered:o}=await import(`./provider-BWME-twj.js`),s=await o(r),{getServer:c}=await import(`./store-BZTffu8V.js`).then(e=>e.r),l=await c(r,t.fs);if(!l)return A5(`mcp auth: unknown server "${r}" (run \`mcp list\` to see configured servers)`);if(!l.auth)return A5(`mcp auth: server "${r}" does not use OAuth`);if(!s)return A5(`mcp auth: failed to register provider for "${r}"`);let u=`mcp:${r}`,{getRegisteredProviderConfig:d}=await import(`./providers-uyxOwwt4.js`).then(e=>e.r),f=d(u);if(!f)return A5(`mcp auth: provider "${u}" is not registered`);if(a)return await N5(r,f,t);if(!f.onSilentRenew)return i?A5(`mcp auth: provider "${u}" does not support silent renewal; retry without --silent`):await N5(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 A5(`mcp auth: silent renewal for "${r}" failed (${t}); retry without --silent to run the interactive flow`);D5.debug(`mcp auth: silent renewal threw, falling back to interactive`,{name:r,error:t})}return p?k5(`Re-authenticated "${r}" via silent renewal (provider ${u})\n`):i?A5(`mcp auth: silent renewal for "${r}" returned no token; retry without --silent to run the interactive flow`):await N5(r,f,t)}async function N5(e,t,n){if(!t.onOAuthLogin)return A5(`mcp auth: provider "${t.id}" does not support interactive OAuth login`);let r=n.oauthLauncher??await F5(),i=!1;return await t.onOAuthLogin(r,()=>{i=!0}),i?k5(`Re-authenticated "${e}" via interactive login (provider ${t.id})\n`):A5(`mcp auth: interactive login for "${e}" did not complete`)}async function P5(e){let t=`mcp:${e}`,{getOAuthAccountInfo:n}=await import(`./provider-settings-B2s5vgom.js`),r=n(t);if(!r)return null;if(r.expired){try{let{getRegisteredProviderConfig:e}=await import(`./providers-uyxOwwt4.js`).then(e=>e.r),n=await e(t)?.onSilentRenew?.();if(n)return`Bearer ${n}`}catch(e){D5.debug(`silent renewal threw`,{providerId:t,error:e instanceof Error?e.message:String(e)})}return null}return`Bearer ${r.token}`}async function F5(){let{createOAuthLauncher:e}=await import(`./oauth-service-Cf0jA8F5.js`);return e()}async function ske(){if(y()){let e=chrome;return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`}let{getOAuthPageOrigin:e}=await import(`./oauth-service-Cf0jA8F5.js`),{origin:t}=await e();return`${t}/auth/callback`}async function cke(e){if(e)return e;let{createProxiedFetch:t}=await import(`./proxied-fetch-CQqrhHlW.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 I5(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-D-5giB0a.js`).then(e=>e.t),{GLOBAL_FS_DB_NAME:n}=await Promise.resolve().then(()=>_V);return await t.create({dbName:n})}function lke(e){return`// MCP alias for "${e}" — forwards args to \`mcp invoke ${e}\`.
|
|
8689
8689
|
// Auto-generated by \`mcp add ${e}\`; do not edit by hand.
|
|
8690
8690
|
const argv = Array.isArray(process.argv) ? process.argv.slice(2) : [];
|
|
8691
8691
|
const escape = (s) => {
|
|
@@ -8699,7 +8699,7 @@ const r = await exec(cmd);
|
|
|
8699
8699
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
8700
8700
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
8701
8701
|
process.exit(r.exitCode || 0);
|
|
8702
|
-
`}async function uke(e,t){let n=await I5(t.fs);await n.mkdir(O5,{recursive:!0}),await n.writeFile(`${O5}/${e}.jsh`,lke(e)),t.scriptCatalog?.invalidateJsh()}async function dke(e,t){let n=await I5(t.fs),r=`${O5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){D5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function fke(e,t){let{removeAppSprinkles:n}=await import(`./apps-
|
|
8702
|
+
`}async function uke(e,t){let n=await I5(t.fs);await n.mkdir(O5,{recursive:!0}),await n.writeFile(`${O5}/${e}.jsh`,lke(e)),t.scriptCatalog?.invalidateJsh()}async function dke(e,t){let n=await I5(t.fs),r=`${O5}/${e}.jsh`;try{await n.exists(r)&&await n.rm(r)}catch(e){D5.debug(`alias removal failed`,{path:r,error:e instanceof Error?e.message:String(e)})}t.scriptCatalog?.invalidateJsh()}async function fke(e,t){let{removeAppSprinkles:n}=await import(`./apps-DpqSNSYV.js`);await n(e,t.fs)}async function L5(e,t,n){try{let{materializeAppSprinkles:r}=await import(`./apps-DpqSNSYV.js`);return(await r(e,t,n.fs)).length}catch(t){return D5.warn(`mcp: failed to materialize app sprinkles`,{name:e,error:t instanceof Error?t.message:String(t)}),0}}const R5=`/.cache/artificial-analysis.json`;async function pke(e,t=!1){if(e&&!t)try{let t=await e.readFile(R5),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=A(),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(R5,JSON.stringify(t))}catch{}}return s}function z5(e){return e.toLowerCase().replace(/\./g,`-`).replace(/-\d{8}$/,``).replace(/-\d{4}$/,``)}function mke(e,t){let n=e.toLowerCase(),r=t.find(e=>e.slug===n);if(r)return r;let i=z5(e),a=t.find(e=>z5(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 hke(){return`models - list available LLM models
|
|
8703
8703
|
|
|
8704
8704
|
Usage: models [options]
|
|
8705
8705
|
|
|
@@ -8713,7 +8713,7 @@ Options:
|
|
|
8713
8713
|
-h, --help Show this help message
|
|
8714
8714
|
`}function gke(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`.replace(`.0M`,`M`):e>=1e3?`${(e/1e3).toFixed(0)}K`:`${e}`}function B5(e){return`$${e.toFixed(2)}`}const _ke=/\b(embedding|embed|tts|whisper|dall-e|image-gen|audio|vision-preview)\b/i;function vke(e){let t=`${e.id} ${e.name??``}`;return!_ke.test(t)}function yke(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 bke(e){let t=new Map;for(let n of e){let e=yke(n.id);(!t.has(e)||n.selected)&&t.set(e,n)}return[...t.values()]}function xke(e,t,n,r,i){let a=i?mke(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 Ske(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=`${B5(e.cost.input)} / ${B5(e.cost.output)}`,a=`${gke(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(`
|
|
8715
8715
|
`)+`
|
|
8716
|
-
`}function Cke(e){return AO(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-
|
|
8716
|
+
`}function Cke(e){return AO(`models`,async t=>{let{getAccounts:n,getAvailableProviders:r,getProviderConfig:i,getProviderModels:a,getSelectedProvider:o,getSelectedModelId:s,resolveCurrentModel:c}=await import(`./provider-settings-B2s5vgom.js`);if(t.includes(`--help`)||t.includes(`-h`))return{stdout:hke(),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.
|
|
8717
8717
|
`,exitCode:1};let y=c(),b=y.id,x=y.provider,S;p||(S=await pke(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(vke);if(t.length===0){if(!u)return{stdout:``,stderr:`No models available for provider ${e}.\n`,exitCode:1};continue}let n=t.map(t=>xke(t,e,b,x,S)).sort((e,t)=>t.cost.input-e.cost.input);if(d||(n=bke(n)),w.push(...n),!l){let t=i(e);T.push(Ske(t.name,e,n,!!S))}}if(l)return{stdout:JSON.stringify(w,null,2)+`
|
|
8718
8718
|
`,stderr:``,exitCode:0};!d&&!l&&T.push(`Showing latest versions only. Use --all-versions to see all.
|
|
8719
8719
|
`);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(`
|
|
@@ -8754,7 +8754,7 @@ Examples:
|
|
|
8754
8754
|
oauth-domain add adobe '*.da.live'
|
|
8755
8755
|
oauth-domain list adobe
|
|
8756
8756
|
oauth-domain remove adobe admin.da.live
|
|
8757
|
-
`}function jke(){return AO(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:V5(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-
|
|
8757
|
+
`}function jke(){return AO(`oauth-domain`,async e=>{if(e.length===0||e.includes(`--help`)||e.includes(`-h`))return{stdout:V5(),stderr:``,exitCode:0};let{getExtraOAuthDomains:t,setExtraOAuthDomainsAsync:n,getAllExtraOAuthDomains:r}=await import(`./provider-settings-B2s5vgom.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(`
|
|
8758
8758
|
`)+`
|
|
8759
8759
|
`,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)
|
|
8760
8760
|
`,stderr:``,exitCode:0}:{stdout:n.map(([e,t])=>`${e}: ${t.join(`, `)}`).join(`
|
|
@@ -8812,11 +8812,11 @@ Examples:
|
|
|
8812
8812
|
--authorize-url 'https://auth.x.ai/oauth2/auth?...' \\
|
|
8813
8813
|
--redirect-pattern 'http://127.0.0.1:56121/*'
|
|
8814
8814
|
curl -H "Authorization: Bearer $(oauth-token github)" https://api.github.com/user
|
|
8815
|
-
`}function Nke(){return AO(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-
|
|
8815
|
+
`}function Nke(){return AO(`oauth-token`,async(e,t)=>{let{getOAuthAccountInfo:n,getSelectedProvider:r,getAccounts:i}=await import(`./provider-settings-B2s5vgom.js`),{getRegisteredProviderConfig:a,getRegisteredProviderIds:o}=await import(`./providers-uyxOwwt4.js`).then(e=>e.r);if(e.includes(`--help`)||e.includes(`-h`))return{stdout:Mke(),stderr:``,exitCode:0};if(e.includes(`--list`))return Ike(i,o,a,n);if(e.includes(`--renew`))return Pke(e);if(e.includes(`--from-file`)||e.includes(`--intercept`))return Fke(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
|
|
8816
8816
|
`,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
|
|
8817
8817
|
`,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
|
|
8818
8818
|
`,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-Cf0jA8F5.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-Cf0jA8F5.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
|
|
8819
|
-
`,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 Pke(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-
|
|
8819
|
+
`,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 Pke(e){let{getSelectedProvider:t,getOAuthAccountInfo:n}=await import(`./provider-settings-B2s5vgom.js`),{getRegisteredProviderConfig:r,getRegisteredProviderIds:i}=await import(`./providers-uyxOwwt4.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 W5(`oauth-token --renew: no provider supports silent renewal`);let o=r(a);if(!o)return W5(`oauth-token --renew: unknown provider "${a}"`);if(!o.onSilentRenew)return W5(`oauth-token --renew: provider "${a}" has no onSilentRenew hook`);let s=n(a),c=s?.token,l=[`oauth-token --renew ${a}`];l.push(` before: ${H5(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: ${H5(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(`
|
|
8820
8820
|
`)+`
|
|
8821
8821
|
`,stderr:``,exitCode:+!u}}function H5(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 Fke(e,t){let{parseInterceptOAuthConfig:n}=await import(`./intercepted-oauth-CaCw-rJ5.js`).then(e=>e.n),{createInterceptingOAuthLauncherForCurrentRuntime:r}=await import(`./oauth-service-Cf0jA8F5.js`),i,a=e.indexOf(`--from-file`);if(a>=0){let n=e[a+1];if(!n)return W5(`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 W5(`oauth-token: failed to read ${n}: ${e instanceof Error?e.message:String(e)}`)}}else{let t=U5(e,`--authorize-url`),n=U5(e,`--redirect-pattern`);if(!t)return W5(`oauth-token: --authorize-url is required`);if(!n)return W5(`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 W5(`oauth-token: --rewrite requires a value`);let i=n.split(`=`);if(i.length<3)return W5(`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 W5(`oauth-token: invalid intercept config: ${o.error}`);let s=await r();if(!s)return W5(`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}:W5(`oauth-token: intercept timed out or was cancelled`)}function U5(e,t){let n=e.indexOf(t);if(n<0)return;let r=e[n+1];if(!(!r||r.startsWith(`--`)))return r}function W5(e){return{stdout:``,stderr:`${e}\n`,exitCode:1}}function Ike(e,t,n,r){let i=t().filter(e=>n(e)?.isOAuth);if(i.length===0)return{stdout:`No OAuth providers configured.
|
|
8822
8822
|
`,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(`
|
|
@@ -8960,11 +8960,11 @@ Examples:
|
|
|
8960
8960
|
`,stderr:``,exitCode:0}}function p7(e){switch(e.state){case`ready`:return`voice engine: ready
|
|
8961
8961
|
`;case`failed`:return`voice engine: failed (re-run say --warmup to retry)
|
|
8962
8962
|
`;case`idle`:return`voice engine: not downloaded (run say --warmup)
|
|
8963
|
-
`;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 m7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function h7(e){return e instanceof Error?e.message:String(e)}let g7=!1,_7=null;function v7(){return g7?Promise.resolve(speechSynthesis.getVoices()):(_7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){g7=!0,e(t);return}let n=()=>{g7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),g7=!0,e(speechSynthesis.getVoices())},1e3)}),_7)}const y7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function RAe(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 zAe(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 y7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return m7(`${i} requires ${y7[i]}`);let a=RAe(t,i,n);if(a)return m7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return m7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function b7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function BAe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-
|
|
8963
|
+
`;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 m7(e){return{stdout:``,stderr:`say: ${e}\n`,exitCode:1}}function h7(e){return e instanceof Error?e.message:String(e)}let g7=!1,_7=null;function v7(){return g7?Promise.resolve(speechSynthesis.getVoices()):(_7||=new Promise(e=>{let t=speechSynthesis.getVoices();if(t.length>0){g7=!0,e(t);return}let n=()=>{g7=!0,speechSynthesis.removeEventListener(`voiceschanged`,n),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,n),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,n),g7=!0,e(speechSynthesis.getVoices())},1e3)}),_7)}const y7={"-v":`a voice name`,"-r":`a rate value`,"-l":`a language tag`,"-o":`an output file path`,"--out":`an output file path`};function RAe(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 zAe(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 y7){let n=r+1<e.length&&!e[r+1].startsWith(`-`)?e[++r]:null;if(n==null)return m7(`${i} requires ${y7[i]}`);let a=RAe(t,i,n);if(a)return m7(a)}else if(i.startsWith(`-`)&&i!==`--list`)return m7(`unknown option: ${i}`);else i.startsWith(`-`)||n.push(i)}return t.text=n.join(` `),t}function b7(e){let t=e.onDevice?`[kokoro]`:`[web speech]`;return`${e.name} (${e.lang}) ${t}${e.default?` [default]`:``}`}async function BAe(e){if(e.local){let{kokoroVoicesIfReady:e}=await import(`./speak-D5G7KiTT.js`),t=e().map(e=>b7({name:e.id,lang:e.lang,onDevice:e.onDevice})),n=(await v7()).map(e=>b7({name:e.name,lang:e.lang,onDevice:!1,default:e.default}));return{stdout:[...t,...n].join(`
|
|
8964
8964
|
`)+`
|
|
8965
8965
|
`,stderr:``,exitCode:0}}try{return{stdout:(await e.panelRpc.call(`list-voices`,void 0)).voices.map(e=>b7(e)).join(`
|
|
8966
8966
|
`)+`
|
|
8967
|
-
`,stderr:``,exitCode:0}}catch(e){return m7(h7(e))}}async function VAe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-
|
|
8967
|
+
`,stderr:``,exitCode:0}}catch(e){return m7(h7(e))}}async function VAe(e){if(!e.local)return(await e.panelRpc.call(`list-voices`,void 0)).voices;let{kokoroVoicesIfReady:t}=await import(`./speak-D5G7KiTT.js`),n=t().map(e=>({name:e.id})),r=(await v7()).map(e=>({name:e.name}));return[...n,...r]}async function HAe(e,t){let n=(await VAe(e)).find(e=>e.name.toLowerCase().includes(t.toLowerCase()));return n?{resolved:n.name}:{error:m7(`voice "${t}" not found. Use --list to see available voices.`)}}async function x7(e,t){try{if(e.local){let{kokoroStatus:e,kokoroWarmup:n}=await import(`./speak-D5G7KiTT.js`);return{stdout:p7(t?n():e()),stderr:``,exitCode:0}}return{stdout:p7(t?await e.panelRpc.call(`speak-warmup`,void 0):await e.panelRpc.call(`speak-status`,void 0)),stderr:``,exitCode:0}}catch(e){return m7(h7(e))}}async function UAe(e,t){return t.includes(`--list`)?BAe(e):t.includes(`--status`)?x7(e,!1):t.includes(`--warmup`)?x7(e,!0):null}async function WAe(e){try{let{speak:t}=await import(`./speak-D5G7KiTT.js`);return await t(e),{stdout:``,stderr:``,exitCode:0}}catch(e){return m7(`speech synthesis error: ${h7(e)}`)}}async function GAe(e,t){try{return await e.panelRpc.call(`speak-text`,t,{timeoutMs:5*6e4}),{stdout:``,stderr:``,exitCode:0}}catch(e){return m7(h7(e))}}async function KAe(e){let{synthesizeToWav:t}=await import(`./speak-D5G7KiTT.js`);try{return{bytes:await t(e)}}catch(e){return m7(h7(e))}}async function qAe(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 m7(h7(e))}}async function JAe(e,t,n,r){let i=e.local?await KAe(r):await qAe(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 m7(`failed to write ${n}: ${h7(e)}`)}return{stdout:`wrote ${Math.max(1,Math.round(i.bytes.byteLength/1024))} KB to ${a}\n`,stderr:``,exitCode:0}}function YAe(){return AO(`say`,async(e,t)=>{if(e.includes(`--help`)||e.includes(`-h`))return f7();let n={local:typeof window<`u`&&typeof speechSynthesis<`u`,panelRpc:M()};if(!n.local&&!n.panelRpc)return m7(`Web Speech API unavailable in this environment`);let r=await UAe(n,e);if(r)return r;let i=zAe(e);if(`exitCode`in i)return i;if(!i.text)return f7();if(!i.lang)return m7(`-l language tag is required`);let a;if(i.voiceName){let{resolved:e,error:t}=await HAe(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?JAe(n,t,i.outFile,o):n.local?WAe(o):GAe(n,o)})}function XAe(){return{stdout:`screencapture - capture screen, window, or tab using browser screen sharing
|
|
8968
8968
|
|
|
8969
8969
|
Usage: screencapture [options] <output-file>
|
|
8970
8970
|
|
|
@@ -10441,4 +10441,4 @@ ${t}
|
|
|
10441
10441
|
`;case`cmdline`:return`kernel-host\0`;case`cwd`:return`/
|
|
10442
10442
|
`;case`stat`:return`1 (kernel-host) R 0 - 0 -
|
|
10443
10443
|
`}}function zFe(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 BFe(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 VFe(e,t){if(e.type===`sudo-request`){t.log.debug?.(`sudo-request lick: UI-chip-only path; orchestrator owns delivery`,{lickId:e.lickId});return}HFe(e,t)}function HFe(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=vt(e);if(r===null){n.debug?.(`dropping lick event with no renderable content`,{type:e.type});return}let i=zFe(e),a=BFe(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 UFe(e,t,n,r){let i=new vW,a=new AFe(e,{...r,getBrowserAPI:()=>t});a.setProcessManager(i),globalThis.__slicc_pm=i,globalThis.__slicc_browser=t,await n.bind(a,t);let o=wn(()=>n.emitTrayRuntimeStatus()),s=At(()=>n.emitTrayRuntimeStatus());return await a.init(),await n.seedBuffersFromAgentState(),{processManager:i,orchestrator:a,unsubLeader:o,unsubFollower:s,sharedFs:a.getSharedFS()}}async function WFe(e,t,n){let{registerSessionCostsProvider:r}=await Promise.resolve().then(()=>Qce);r(()=>e.getSessionCosts());let{getLickManager:i}=await Promise.resolve().then(()=>xde),a=i();await a.init(),e.setLickManager(a);let o=t.lickEventHandler??VFe,s={orchestrator:e,lickManager:a,log:n};return a.setEventHandler(e=>o(e,s)),a}async function GFe(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 KFe(e){let{orchestrator:t,processManager:n,lickManager:r,sharedFs:i}=e;HNe({sharedFs:i,getConeJid:()=>t.getScoops().find(e=>e.isCone)?.jid,fireLick:e=>r.emitEvent(e),processManager:n,runRealm:(e,t,n)=>S1(e,t,n,void 0,{filename:t[1]}),makeRunId:()=>p9().slice(10,22),splitResult:(e,t)=>m9(e,t)})}async function qFe(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))+`
|
|
10444
|
-
`,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 JFe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-uE08lRKe.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 YFe(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 ai(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})},XFe(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function XFe(e){let t=A();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:()=>jFe()}}function ZFe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-s20mtVA3.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>et),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 QFe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-Djr_fxY8.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 $Fe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>Hve),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 eIe(){return he()}async function tIe(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 UFe(t,n,r,i);if(d?xi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new MFe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await WFe(c,e,o);d&&KFe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await qFe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;eIe()&&(h=await JFe(f,o,e.localLickWsUrl??null));let g=YFe(n,f,o);d&&ZFe(d,f,o),a||await GFe(c),d&&QFe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await $Fe(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 nIe({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 nIe(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)}rIe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function rIe(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[u9]}const G9=`x-bypass-llm-proxy`;function iIe(e,t,n){return t?(r,i)=>{if(!aIe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function aIe(e,t,n){if(sIe(e,t))return!0;let r=n?.()??null;return r?oIe(e,r,t):!1}function oIe(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function sIe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function cIe(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 lIe=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(!uIe(e)||e.source!==`panel`)return;let t=e.payload;dIe(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function uIe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function dIe(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 fIe=class extends w9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function pIe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new lIe({transport:t,processManager:i,createShell:(e,a)=>new fIe(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 mIe(e){let t=new hIe(e);return t.start(),{stop:()=>t.dispose()}}var hIe=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(!gIe(e)||e.source!==`panel`)return;let t=e.payload;if(_Ie(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(vIe(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 b(`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 b(`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(yIe(e.type),e.requestId,new b(`EACCES`,`vfs-rpc-host has no writable backend wired`),bIe(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 b(`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 b(`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 b(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function gIe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _Ie(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 vIe(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 yIe(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 bIe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof b?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function xIe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=iIe(e.bind(globalThis),t,SIe)}function SIe(){let e=ne();if(!e)return null;try{return new URL(e).origin}catch{return null}}function CIe(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const wIe=cIe(e=>TIe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&wIe.handle(e.data)});async function TIe(e){Xn(e.instanceId);try{xIe(),k(e.localApiBaseUrl??null),ae(e.bridgeToken??null),O(e.extensionDelegateId??null),CIe(e.localStorageSeed??{}),gr().catch(()=>{}),await me();let t=Or(e.kernelPort),n=new An(t),r=An.createCallbacks(n),i=new kr(e.cdpPort);await i.connect();let a=new Bn(i);Y9=await tIe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),s=o({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=s;let c=Y9.sharedFs?.getWatcher();if(c){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)c.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)s.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:l}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=l({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(Kn(M));let u=await EIe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});u&&(X9=u.stopTerminalHost,Z9=u.stopVfsRpcHost,Q9=u.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Qn(e),e}}async function EIe(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=pIe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=mIe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await DIe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function DIe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-DHsIj3AZ.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CQqrhHlW.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`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});export{xt as C,bt as S,xn as _,J8 as a,tn as b,Bxe as c,dH as d,vV as f,Sn as g,BN as h,l5 as i,PK as l,JF as m,r9 as n,m8 as o,YF as p,n9 as r,f8 as s,vNe as t,LK as u,_n as v,$e as w,nn as x,hn as y};
|
|
10444
|
+
`,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 JFe(e,t,n){try{let{startLickWsBridge:t}=await import(`./lick-ws-bridge-8McAeIbO.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 YFe(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 ai(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})},XFe(t));return e.start(),()=>e.stop()}catch(e){return n.warn(`Failed to start NavigationWatcher`,e),null}}function XFe(e){let t=A();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:()=>jFe()}}function ZFe(e,t,n){(async()=>{try{let{getAllMountEntries:r}=await import(`./mount-table-store-s20mtVA3.js`).then(e=>e.r),{recoverMounts:i}=await Promise.resolve().then(()=>et),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 QFe(e,t){(async()=>{try{let{detectUpgrade:t,recordVersionSeen:n}=await import(`./upgrade-detection-i5f6luyi.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 $Fe(e,t,n){try{let{BshWatchdog:n}=await import(`./bsh-watchdog-cTkGOVHJ.js`),{ScriptCatalog:r}=await Promise.resolve().then(()=>Hve),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 eIe(){return he()}async function tIe(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 UFe(t,n,r,i);if(d?xi(c,d,c.getSessionStore()):o.warn(`AgentBridge not published — orchestrator.getSharedFS() returned null`),d)try{await d.mountInternal(`/proc`,new MFe(s))}catch(e){o.warn(`Failed to mount /proc`,e)}let f=await WFe(c,e,o);d&&KFe({orchestrator:c,processManager:s,lickManager:f,sharedFs:d}),globalThis.__slicc_lickManager=f;let{wsBridge:p,wsRegistry:m}=await qFe({browser:n,lickManager:f,orchestrator:c,sharedFs:d,log:o});globalThis.__slicc_wsSubscribers=m;let h=null;eIe()&&(h=await JFe(f,o,e.localLickWsUrl??null));let g=YFe(n,f,o);d&&ZFe(d,f,o),a||await GFe(c),d&&QFe(f,o);let _=null,v=null;d&&({bshWatchdogStop:_,scriptCatalogDispose:v}=await $Fe(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 nIe({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 nIe(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)}rIe({processManager:i,lickManager:a,browser:o,wsRegistry:n})}function rIe(e){let t=globalThis;t.__slicc_pm===e.processManager&&delete t.__slicc_pm,t.__slicc_lickManager===e.lickManager&&delete t.__slicc_lickManager,e.browser&&t.__slicc_browser===e.browser&&delete t.__slicc_browser,e.wsRegistry&&t.__slicc_wsSubscribers===e.wsRegistry&&delete t.__slicc_wsSubscribers,delete t[u9]}const G9=`x-bypass-llm-proxy`;function iIe(e,t,n){return t?(r,i)=>{if(!aIe(r,t,n))return e(r,i);let a=new Headers(i?.headers);return a.has(G9)||a.set(G9,`1`),e(r,{...i,headers:a})}:e}function aIe(e,t,n){if(sIe(e,t))return!0;let r=n?.()??null;return r?oIe(e,r,t):!1}function oIe(e,t,n){let r=K9(e),i,a;try{i=new URL(r,n),a=new URL(t)}catch{return!1}return i.origin===a.origin&&i.pathname.startsWith(`/api/`)}function sIe(e,t){let n=K9(e);try{return new URL(n,t).origin===t}catch{return!0}}function K9(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function cIe(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 lIe=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(!uIe(e)||e.source!==`panel`)return;let t=e.payload;dIe(t)&&this.handleControl(t).catch(e=>{this.log.warn(`[terminal-session-host] handler error`,e)})}),()=>this.dispose()}dispose(){this.unsubscribe?.(),this.unsubscribe=null;for(let[,e]of this.sessions)e.currentProcess&&this.pm?(this.pm.signal(e.currentProcess.pid,`SIGTERM`),this.pm.exit(e.currentProcess.pid,null)):e.currentExec?.abort(),e.shell.dispose?.();this.sessions.clear()}async handleControl(e){switch(e.type){case`terminal-open`:return this.handleOpen(e);case`terminal-close`:return this.handleClose(e);case`terminal-exec`:return this.handleExec(e);case`terminal-signal`:return this.handleSignal(e);case`terminal-stdin`:case`terminal-resize`:return}}async handleOpen(e){if(this.sessions.has(e.sid)){this.emitStatus(e.sid,`error`,`session already open`);return}try{let t=this.createShell(e.sid,{cwd:e.cwd,env:e.env});this.sessions.set(e.sid,{shell:t,currentExec:null,currentProcess:null}),this.emitStatus(e.sid,`opened`)}catch(t){this.emitStatus(e.sid,`error`,t instanceof Error?t.message:String(t))}}async handleClose(e){let t=this.sessions.get(e.sid);t&&(t.currentProcess&&this.pm?(this.pm.signal(t.currentProcess.pid,`SIGTERM`),this.pm.exit(t.currentProcess.pid,null)):t.currentExec?.abort(),t.shell.dispose?.(),this.sessions.delete(e.sid),this.emitStatus(e.sid,`closed`))}emitExit(e,t){this.emit({type:`terminal-exit`,sid:e.sid,execId:e.execId,exitCode:t})}emitStream(e,t,n){this.emit({type:`terminal-output`,sid:e.sid,execId:e.execId,stream:t,data:n})}async handleExec(e){let t=this.sessions.get(e.sid);if(!t){this.emitExit(e,127),this.log.warn(`[terminal-session-host] exec on unknown session`,e.sid);return}if(t.currentExec){this.emitExit(e,130);return}let n=new AbortController;t.currentExec=n;let r=this.pm?this.pm.spawn({kind:`shell`,argv:[e.command],cwd:t.shell.getCwd?.()??void 0,owner:this.defaultOwner,adoptAbort:n}):null;t.currentProcess=r;try{let i=await t.shell.executeCommand(e.command,n.signal,r?.pid);await this.emitExecSuccess(e,i,n,r)}catch(t){this.emitExecError(e,t,n,r)}finally{t.currentExec===n&&(t.currentExec=null,t.currentProcess=null)}}async emitExecSuccess(e,t,n,r){let i=n.signal.aborted?q9(r?.terminatedBy??`SIGINT`):t.exitCode;n.signal.aborted||(r&&await r.gate.wait(),t.stdout&&this.emitStream(e,`stdout`,t.stdout),t.stderr&&this.emitStream(e,`stderr`,t.stderr)),this.emitExit(e,i),r&&this.pm&&this.pm.exit(r.pid,n.signal.aborted?null:t.exitCode)}emitExecError(e,t,n,r){if(n.signal.aborted){this.emitExit(e,q9(r?.terminatedBy??`SIGINT`)),r&&this.pm&&this.pm.exit(r.pid,null);return}let i=t instanceof Error?t.message:String(t);this.emitStream(e,`stderr`,`Error: ${i}\n`),this.emitExit(e,1),r&&this.pm&&this.pm.exit(r.pid,1)}async handleSignal(e){let t=this.sessions.get(e.sid);if(!t){this.log.warn(`[terminal-session-host] signal on unknown session`,e.sid);return}(e.signal===`SIGINT`||e.signal===`SIGTERM`||e.signal===`SIGKILL`)&&(t.currentProcess&&this.pm?this.pm.signal(t.currentProcess.pid,e.signal):t.currentExec?.abort())}emit(e){this.transport.send(e)}emitStatus(e,t,n){let r=n?{type:`terminal-status`,sid:e,state:t,error:n}:{type:`terminal-status`,sid:e,state:t};this.emit(r)}};function uIe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function q9(e){switch(e){case`SIGINT`:return 130;case`SIGTERM`:return 143;case`SIGKILL`:return 137;case`SIGSTOP`:case`SIGCONT`:return 130}}function dIe(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 fIe=class extends w9{sid;transport;constructor(e,t,n){super(n),this.sid=e,this.transport=t}async renderMediaPreview(e){for(let t of e){let e=``,n=t.bytes,r=8192;for(let t=0;t<n.length;t+=r)e+=String.fromCharCode(...n.subarray(t,t+r));let i={type:`terminal-media-preview`,sid:this.sid,path:t.path,mediaType:t.mimeType,data:btoa(e)};this.transport.send(i)}}};function pIe(e){let{transport:t,fs:n,browser:r,processManager:i,sudoManager:a}=e,o=e.logger??console,s=a?.getShellConfig({transparentGating:!1}),c=new lIe({transport:t,processManager:i,createShell:(e,a)=>new fIe(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 mIe(e){let t=new hIe(e);return t.start(),{stop:()=>t.dispose()}}var hIe=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(!gIe(e)||e.source!==`panel`)return;let t=e.payload;if(_Ie(t)){this.handleRequest(t).catch(e=>{this.log.warn(`[vfs-rpc-host] handler unexpectedly threw`,e)});return}if(vIe(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 b(`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 b(`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(yIe(e.type),e.requestId,new b(`EACCES`,`vfs-rpc-host has no writable backend wired`),bIe(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 b(`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 b(`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 b(`EACCES`,`vfs-rpc-host has no mount-aware backend wired`),``);return}try{let n=await t.listMountPoints(),r={type:`vfs-list-mount-points-result`,requestId:e.requestId,ok:!0,mountPoints:n};this.transport.send(r)}catch(t){this.emitWriteError(`vfs-list-mount-points-result`,e.requestId,t,``)}}emitError(e,t,n,r){let i=J9(n,r);switch(e){case`vfs-read-dir-result`:{let e={type:`vfs-read-dir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-read-file-result`:{let e={type:`vfs-read-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-stat-result`:{let e={type:`vfs-stat-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}emitWriteError(e,t,n,r){let i=J9(n,r);switch(r===``&&i.path===``&&delete i.path,e){case`vfs-write-file-result`:{let e={type:`vfs-write-file-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-mkdir-result`:{let e={type:`vfs-mkdir-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-rm-result`:{let e={type:`vfs-rm-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-flush-result`:{let e={type:`vfs-flush-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}case`vfs-list-mount-points-result`:{let e={type:`vfs-list-mount-points-result`,requestId:t,ok:!1,error:i};this.transport.send(e);return}}}};function gIe(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function _Ie(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 vIe(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 yIe(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 bIe(e){return e.type===`vfs-flush`||e.type===`vfs-list-mount-points`?``:e.path}function J9(e,t){return e instanceof b?{code:e.code,message:e.message,path:e.path??t}:{code:`EIO`,message:e instanceof Error?e.message:String(e),path:t}}function xIe(){let e=globalThis.fetch;if(!e)return;let t=self?.location?self.location.origin:void 0;globalThis.fetch=iIe(e.bind(globalThis),t,SIe)}function SIe(){let e=ne();if(!e)return null;try{return new URL(e).origin}catch{return null}}function CIe(e){let t=new Map(Object.entries(e));Object.defineProperty(globalThis,"localStorage",{value:{get length(){return t.size},key(e){return Array.from(t.keys())[e]??null},getItem(e){return t.has(e)?t.get(e):null},setItem(e,n){t.set(e,n)},removeItem(e){t.delete(e)},clear(){t.clear()}},configurable:!0,writable:!0})}let Y9=null,X9=null,Z9=null,Q9=null,$9=null;const wIe=cIe(e=>TIe(e));self.addEventListener(`message`,e=>{e.data?.type===`kernel-worker-init`&&wIe.handle(e.data)});async function TIe(e){Xn(e.instanceId);try{xIe(),k(e.localApiBaseUrl??null),ae(e.bridgeToken??null),O(e.extensionDelegateId??null),CIe(e.localStorageSeed??{}),gr().catch(()=>{}),await me();let t=Or(e.kernelPort),n=new An(t),r=An.createCallbacks(n),i=new kr(e.cdpPort);await i.connect();let a=new Bn(i);Y9=await tIe({container:{},browser:a,bridge:n,callbacks:r,logger:console,localLickWsUrl:e.localLickWsUrl??null});let{createSprinkleManagerProxyOverChannel:o}=await import(`./sprinkle-bridge-channel-14cdGa6x.js`),s=o({instanceId:e.instanceId});globalThis.__slicc_sprinkleManager=s;let c=Y9.sharedFs?.getWatcher();if(c){let e=[`/workspace`,`/shared`,`/scoops`],t=null,n=new Set;for(let r of e)c.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)s.reload(e).catch(()=>{});n.clear()},300)})}let{createPanelRpcClient:l}=await import(`./panel-rpc-CjFVE0nK.js`).then(e=>e.i);$9=l({instanceId:e.instanceId}),globalThis.__slicc_panelRpc=$9,a.setTrayTargetProvider(Kn(M));let u=await EIe({host:Y9,transport:t,browser:a,instanceId:e.instanceId});u&&(X9=u.stopTerminalHost,Z9=u.stopVfsRpcHost,Q9=u.stopSpeechAssetsResponder),e.kernelPort.postMessage({type:`kernel-worker-ready`})}catch(e){throw Qn(e),e}}async function EIe(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=pIe({transport:e.transport,fs:t,browser:e.browser,processManager:e.host.processManager,sudoManager:e.host.orchestrator.getSudoManager(),logger:console}),r=mIe({transport:e.transport,client:t,writableClient:t,logger:console}),i=await DIe(t,e.instanceId);return{stopTerminalHost:n.stop,stopVfsRpcHost:r.stop,stopSpeechAssetsResponder:i}}async function DIe(e,t){let{installSpeechAssetsResponder:n}=await import(`./speech-assets-bridge-BUDIvdid.js`),{ensureSpeechAssetsStaged:r}=await import(`./ensure-speech-assets-W5QPk6uQ.js`),{createProxiedFetch:i}=await import(`./proxied-fetch-CQqrhHlW.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`&&(X9?.(),X9=null,Z9?.(),Z9=null,Q9?.(),Q9=null,$9?.dispose(),$9=null,Y9?.dispose())});export{xt as C,bt as S,xn as _,J8 as a,tn as b,Bxe as c,dH as d,vV as f,Sn as g,BN as h,l5 as i,PK as l,JF as m,r9 as n,m8 as o,YF as p,n9 as r,f8 as s,vNe as t,LK as u,_n as v,$e as w,nn as x,hn as y};
|