sliccy 5.56.8 → 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.
Files changed (81) hide show
  1. package/dist/ui/assets/{account-store-B_6sgB_G.js → account-store-B70B-Xy1.js} +2 -2
  2. package/dist/ui/assets/{account-store-BVzFpOQT.js → account-store-BqI_bdKc.js} +1 -1
  3. package/dist/ui/assets/adobe-DkCnsZQc.js +2 -0
  4. package/dist/ui/assets/{adobe-oauth-state-sN6uxAOS.js → adobe-oauth-state-DPaR8NRp.js} +1 -1
  5. package/dist/ui/assets/adobe-xeGFGZpC.js +1 -0
  6. package/dist/ui/assets/{agent-message-to-chat-D6HthbQr.js → agent-message-to-chat-DzRXXJel.js} +1 -1
  7. package/dist/ui/assets/{apps-DcWHkrpY.js → apps-DpqSNSYV.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-BccWVN8L.js → azure-openai-Bn3boHbY.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-BvWvE5gG.js → azure-openai-DEBv7yQp.js} +1 -1
  10. package/dist/ui/assets/{cerebras-BXZMseO_.js → cerebras-BwqdpIyz.js} +1 -1
  11. package/dist/ui/assets/{cerebras-CJJNaE9Z.js → cerebras-DWHxltur.js} +1 -1
  12. package/dist/ui/assets/clipboard-CSEDRfgj.js +1 -0
  13. package/dist/ui/assets/{connect-surface-lefN623J.js → connect-surface-D6odnHkh.js} +1 -1
  14. package/dist/ui/assets/dip-Bwzg4JXD.js +1 -0
  15. package/dist/ui/assets/{dist-esuLqSSO.js → dist-CSrZL2G5.js} +1 -1
  16. package/dist/ui/assets/{dist-CnwXGuua.js → dist-Dny1G18y.js} +1 -1
  17. package/dist/ui/assets/{ensure-speech-assets-DO44VksG.js → ensure-speech-assets-W5QPk6uQ.js} +1 -1
  18. package/dist/ui/assets/{fs-DWSNMb0S.js → fs-CnhmusOG.js} +2 -2
  19. package/dist/ui/assets/{fs-D0h4dNPC.js → fs-D-5giB0a.js} +1 -1
  20. package/dist/ui/assets/{github-CiAxdS22.js → github-B29ZCKQg.js} +1 -1
  21. package/dist/ui/assets/{github-Bk_fe3oA.js → github-DzM3FtVD.js} +2 -2
  22. package/dist/ui/assets/{github-copilot-mTEYLacV.js → github-copilot-C7aAJAqW.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-yyjZmPtH.js → github-copilot-n309ImF7.js} +1 -1
  24. package/dist/ui/assets/{hear-CMoDolu7.js → hear-0Tswpuv7.js} +1 -1
  25. package/dist/ui/assets/{js-realm-worker-BWzwOrHy.js → js-realm-worker-Bi5UIEMG.js} +7 -7
  26. package/dist/ui/assets/{kernel-worker-KXgcrnNz.js → kernel-worker-BCW_QlyZ.js} +805 -792
  27. package/dist/ui/assets/{kokoro-engine-BeyQv5aZ.js → kokoro-engine-CRs8ZEvx.js} +1 -1
  28. package/dist/ui/assets/{lick-ws-bridge-B-qla4ur.js → lick-ws-bridge-8McAeIbO.js} +1 -1
  29. package/dist/ui/assets/{lick-ws-bridge-Bmm2ohhU.js → lick-ws-bridge-D2LfSdTD.js} +1 -1
  30. package/dist/ui/assets/{local-llm-DdWZ_U16.js → local-llm-Dl9iXPsJ.js} +1 -1
  31. package/dist/ui/assets/{main-CgGZFToi.js → main-6Q7Fb4tw.js} +4 -4
  32. package/dist/ui/assets/{mount-zk3PcnJA.js → mount-BtjScgjq.js} +2 -2
  33. package/dist/ui/assets/{mount-BEqTOy7L.js → mount-NSmYg9GU.js} +1 -1
  34. package/dist/ui/assets/{new-session-BVDZBrHC.js → new-session-CLta1Lj7.js} +2 -2
  35. package/dist/ui/assets/{oauth-bootstrap-C8T3aiE5.js → oauth-bootstrap-D-yvRHGz.js} +2 -2
  36. package/dist/ui/assets/{openai-codex-DfCTfpUQ.js → openai-codex-CB6PdYqU.js} +1 -1
  37. package/dist/ui/assets/{openai-codex-CtbzSvcx.js → openai-codex-ZCmj450m.js} +1 -1
  38. package/dist/ui/assets/{page-follower-tray-BjX_OueJ.js → page-follower-tray-TKZCNKRZ.js} +1 -1
  39. package/dist/ui/assets/{panel-rpc-handlers-CnYoWay-.js → panel-rpc-handlers-RRddFZTk.js} +2 -2
  40. package/dist/ui/assets/{provider-DQvmH2g9.js → provider-BWME-twj.js} +1 -1
  41. package/dist/ui/assets/{provider-B36OIqyO.js → provider-DOjCml56.js} +2 -2
  42. package/dist/ui/assets/{provider-settings-BB2h2Pxv.js → provider-settings-B2s5vgom.js} +1 -1
  43. package/dist/ui/assets/provider-store-access-CjY49bAL.js +1 -0
  44. package/dist/ui/assets/provider-store-access-DQ3kqRuy.js +1 -0
  45. package/dist/ui/assets/{providers-DQsPscgD.js → providers-BQomGz9R.js} +2 -2
  46. package/dist/ui/assets/{providers-BNf-yTBw.js → providers-uyxOwwt4.js} +1 -1
  47. package/dist/ui/assets/{quick-llm-Dx_kO8Hs.js → quick-llm-DHtKMD9z.js} +1 -1
  48. package/dist/ui/assets/session-freezer-D-7ulfYc.js +1 -0
  49. package/dist/ui/assets/{speak-B0YHJp_z.js → speak-D5G7KiTT.js} +1 -1
  50. package/dist/ui/assets/{sprinkle-manager-BlB0LVWE.js → sprinkle-manager-nP3g46qO.js} +1 -1
  51. package/dist/ui/assets/{store-DAMbmmgk.js → store-BZTffu8V.js} +1 -1
  52. package/dist/ui/assets/{sudo-Big6SjrO.js → sudo-CsZ2DlSz.js} +1 -1
  53. package/dist/ui/assets/{transformers-env-B6aaGJH9.js → transformers-env-DHJa4RCf.js} +1 -1
  54. package/dist/ui/assets/{tray-leader-D78f0qGp.js → tray-leader-DgTG9H-w.js} +1 -1
  55. package/dist/ui/assets/{tray-leave-runtime-BrKjo3Av.js → tray-leave-runtime-uZUZNHVX.js} +1 -1
  56. package/dist/ui/assets/{upgrade-detection-NcWWnHD8.js → upgrade-detection-i5f6luyi.js} +1 -1
  57. package/dist/ui/assets/{voice-reply-DJ9ci3mi.js → voice-reply-C-3rH9oC.js} +1 -1
  58. package/dist/ui/assets/{wc-attach-CrGpxE4G.js → wc-attach-BQzDqdAQ.js} +2 -2
  59. package/dist/ui/assets/{wc-extension-M0Ybp0nn.js → wc-extension-DA4ER47a.js} +2 -2
  60. package/dist/ui/assets/{wc-follower-DyLwT42W.js → wc-follower-CsQZCsua.js} +3 -3
  61. package/dist/ui/assets/{wc-live-DT-qdStE.js → wc-live-C04ItfnZ.js} +5 -5
  62. package/dist/ui/assets/{wc-nav-Bc3QC001.js → wc-nav-DgqufJsO.js} +2 -2
  63. package/dist/ui/assets/{wc-onboarding-BukOhg6Q.js → wc-onboarding-BR7HaQPL.js} +2 -2
  64. package/dist/ui/assets/{wc-placeholder-B-OO1YnE.js → wc-placeholder-D36A-bB6.js} +3 -3
  65. package/dist/ui/assets/{wc-settings-B0hc9U7u.js → wc-settings-CaxJcNwg.js} +3 -3
  66. package/dist/ui/assets/{wc-shell-D0qLh-11.js → wc-shell-B7yKyiZ2.js} +3 -3
  67. package/dist/ui/assets/{wc-sprinkles-Ca6QSq5v.js → wc-sprinkles-j5hfmEtl.js} +2 -2
  68. package/dist/ui/assets/{wc-tray-D3FcTg1d.js → wc-tray-CofjfW_1.js} +2 -2
  69. package/dist/ui/assets/{whisper-engine-C-VhzWSm.js → whisper-engine-rP8D81pe.js} +1 -1
  70. package/dist/ui/assets/{xai-grok-CT_K_Jq0.js → xai-grok-BPagp879.js} +1 -1
  71. package/dist/ui/assets/{xai-grok-BqxBYvjX.js → xai-grok-D80aaxGn.js} +1 -1
  72. package/dist/ui/index.html +3 -3
  73. package/dist/ui/packages/webapp/index.html +3 -3
  74. package/package.json +1 -1
  75. package/dist/ui/assets/adobe-B7acY4xO.js +0 -2
  76. package/dist/ui/assets/adobe-CY2vYuxA.js +0 -1
  77. package/dist/ui/assets/clipboard-BW_q83C8.js +0 -1
  78. package/dist/ui/assets/dip-BtpCGUDT.js +0 -1
  79. package/dist/ui/assets/provider-store-access-BG0vIOuh.js +0 -1
  80. package/dist/ui/assets/provider-store-access-CERp1HWf.js +0 -1
  81. package/dist/ui/assets/session-freezer-BEFr-_ob.js +0 -1
@@ -1,2 +1,2 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/clipboard-DuHpK59o.js","assets/rolldown-runtime-aKtaBQYM.js"])))=>i.map(i=>d[i]);
2
- import{s as e}from"./models-ByRUWfA-.js";import{t}from"./preload-helper-CZgWQFsJ.js";import{a as n,c as r,f as i,l as a,n as o,o as s,p as c,r as l,u}from"./compat-FrhC6T45.js";import{R as d,d as f}from"./account-store-BVzFpOQT.js";import"./main-CgGZFToi.js";var p=`github-copilot`,m=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),h=`https://github.com/login/device/code`,g=`https://github.com/login/oauth/access_token`,_=`https://api.github.com/copilot_internal/v2/token`,v={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},y={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},b=`https://github.com/login/device/success*`;function x(){return f().find(e=>e.providerId===p)}async function S(){let e=await fetch(h,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function C(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await w(Math.ceil(r*i),t);let n=await fetch(g,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function w(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function T(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function E(e){let t=await fetch(_,{headers:{...v,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-300*1e3,apiBaseUrl:T(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var D=`github-copilot.models.v1`;function O(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function k(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:O(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function A(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...v,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return k(await t.json())}function j(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(D);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function M(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(D,JSON.stringify(e))}catch{}}function N(e){return j().find(t=>t.id===e)??null}async function P(e){let t;try{t=await A(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}M(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...v,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),M(t)}async function F(e,t){await d({providerId:p,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function I(){let e=x();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await E(e.refreshToken);return await F(n,e.userName),n.copilotToken}var L=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function R(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!L.some(e=>t.some(t=>t.includes(e)))}function z(){if(!x()?.accessToken)return[];let e=j();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>R(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=l(`github-copilot`)}catch{return[]}return t.filter(e=>R({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function B(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:p,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var V={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function H(e){let t=x(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=N(e);if(r)return{api:r.api,baseUrl:n,headers:{...V}};try{let n=o(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...V}}}catch{return null}}function U(e,t){let n=j(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},M(n))}function W(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function G(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function K(e,t){return e===`anthropic-messages`?t?u:s:e===`openai-responses`?t?c:a:t?i:r}function q(e,t,n){let r=G(n);if(r&&/model_not_supported/i.test(r)){U(t.id,`model_not_supported`);let n=W(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(B(t,Error(n))),e.end(),!0}return e.push(n),!1}function J(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(U(t.id,`model_not_supported`),i=Error(W(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(B(t,i)),e.end()}async function Y(e,t,n,r,i){try{let a=await I(),o=H(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=K(o.api,i)(s,n,c);for await(let n of l)if(q(e,t,n))return;e.end()}catch(n){J(e,t,n)}}function X(t){return(n,r,i={})=>{let a=e();return Y(a,n,r,i,t),a}}var Z=X(!1),Q=X(!0),$=({userCode:e,verificationUrl:n})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${n} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(n=>{let r=document.createElement(`div`);r.setAttribute(`data-slicc-overlay`,`github-copilot-device`),r.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let i=document.createElement(`div`);i.textContent=`GitHub Copilot — verification code`,i.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let a=document.createElement(`div`);a.textContent=e,a.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let o=document.createElement(`div`);o.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,o.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let s=document.createElement(`div`);s.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{r.remove()}catch{}};c.addEventListener(`click`,()=>{u(),n(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:n}=await t(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-DuHpK59o.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await n(e)}catch{}u(),n(`continue`)})()}),s.appendChild(c),s.appendChild(l),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(s),document.body.appendChild(r)}),ee={id:p,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:z,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await S(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??$)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:b,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await C(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await E(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await F(c,l),await P(c),t()},onOAuthLogout:async()=>{await d({providerId:p,accessToken:``})},onSilentRenew:async()=>{let e=x();if(!e?.refreshToken)return null;try{let t=await E(e.refreshToken);return await F(t,e.userName),await P(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function te(){n({api:`github-copilot-anthropic`,stream:Z,streamSimple:Q}),n({api:`github-copilot-openai`,stream:Z,streamSimple:Q})}export{ee as config,R as isCopilotConeCompatible,te as register};
2
+ import{s as e}from"./models-ByRUWfA-.js";import{t}from"./preload-helper-CZgWQFsJ.js";import{a as n,c as r,f as i,l as a,n as o,o as s,p as c,r as l,u}from"./compat-FrhC6T45.js";import{R as d,d as f}from"./account-store-BqI_bdKc.js";import"./main-6Q7Fb4tw.js";var p=`github-copilot`,m=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),h=`https://github.com/login/device/code`,g=`https://github.com/login/oauth/access_token`,_=`https://api.github.com/copilot_internal/v2/token`,v={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},y={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},b=`https://github.com/login/device/success*`;function x(){return f().find(e=>e.providerId===p)}async function S(){let e=await fetch(h,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function C(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await w(Math.ceil(r*i),t);let n=await fetch(g,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function w(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function T(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function E(e){let t=await fetch(_,{headers:{...v,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-300*1e3,apiBaseUrl:T(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var D=`github-copilot.models.v1`;function O(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function k(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:O(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function A(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...v,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return k(await t.json())}function j(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(D);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function M(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(D,JSON.stringify(e))}catch{}}function N(e){return j().find(t=>t.id===e)??null}async function P(e){let t;try{t=await A(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}M(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...v,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),M(t)}async function F(e,t){await d({providerId:p,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function I(){let e=x();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await E(e.refreshToken);return await F(n,e.userName),n.copilotToken}var L=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function R(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!L.some(e=>t.some(t=>t.includes(e)))}function z(){if(!x()?.accessToken)return[];let e=j();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>R(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=l(`github-copilot`)}catch{return[]}return t.filter(e=>R({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function B(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:p,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var V={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function H(e){let t=x(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=N(e);if(r)return{api:r.api,baseUrl:n,headers:{...V}};try{let n=o(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...V}}}catch{return null}}function U(e,t){let n=j(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},M(n))}function W(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function G(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function K(e,t){return e===`anthropic-messages`?t?u:s:e===`openai-responses`?t?c:a:t?i:r}function q(e,t,n){let r=G(n);if(r&&/model_not_supported/i.test(r)){U(t.id,`model_not_supported`);let n=W(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(B(t,Error(n))),e.end(),!0}return e.push(n),!1}function J(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(U(t.id,`model_not_supported`),i=Error(W(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(B(t,i)),e.end()}async function Y(e,t,n,r,i){try{let a=await I(),o=H(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=K(o.api,i)(s,n,c);for await(let n of l)if(q(e,t,n))return;e.end()}catch(n){J(e,t,n)}}function X(t){return(n,r,i={})=>{let a=e();return Y(a,n,r,i,t),a}}var Z=X(!1),Q=X(!0),$=({userCode:e,verificationUrl:n})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${n} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(n=>{let r=document.createElement(`div`);r.setAttribute(`data-slicc-overlay`,`github-copilot-device`),r.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let i=document.createElement(`div`);i.textContent=`GitHub Copilot — verification code`,i.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let a=document.createElement(`div`);a.textContent=e,a.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let o=document.createElement(`div`);o.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,o.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let s=document.createElement(`div`);s.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{r.remove()}catch{}};c.addEventListener(`click`,()=>{u(),n(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:n}=await t(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-DuHpK59o.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await n(e)}catch{}u(),n(`continue`)})()}),s.appendChild(c),s.appendChild(l),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(s),document.body.appendChild(r)}),ee={id:p,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:z,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await S(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??$)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:b,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await C(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await E(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await F(c,l),await P(c),t()},onOAuthLogout:async()=>{await d({providerId:p,accessToken:``})},onSilentRenew:async()=>{let e=x();if(!e?.refreshToken)return null;try{let t=await E(e.refreshToken);return await F(t,e.userName),await P(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function te(){n({api:`github-copilot-anthropic`,stream:Z,streamSimple:Q}),n({api:`github-copilot-openai`,stream:Z,streamSimple:Q})}export{ee as config,R as isCopilotConeCompatible,te as register};
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./wc-permissions-registry-C7PhTX3c.js";import{i as n,n as r,r as i}from"./whisper-engine-C-VhzWSm.js";const a=16e3;async function o(e){if(typeof AudioContext>`u`||typeof OfflineAudioContext>`u`)throw Error(`audio decoding requires a window/page realm (AudioContext unavailable)`);let t=new AudioContext,n;try{n=await t.decodeAudioData(e.slice(0))}finally{await t.close().catch(()=>{})}let r=Math.max(1,Math.ceil(n.duration*a)),i=new OfflineAudioContext(1,r,a),o=i.createBufferSource();return o.buffer=n,o.connect(i.destination),o.start(),(await i.startRendering()).getChannelData(0).slice(0)}e(`speech:whisper-session`);function s(e){return e?.split(`-`)[0]?.toLowerCase()||void 0}const c=e(`speech:hear`);let l={};function u(){return l.getPermissionSurface?l.getPermissionSurface():t()||null}function d(){if(typeof window>`u`)return null;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var f=class extends Error{code;constructor(e){super(p(e)),this.name=`SpeechRecognitionError`,this.code=e}};function p(e){switch(e){case`network`:case`service-not-allowed`:return"builtin speech recognition is unsupported in this browser (no Web Speech cloud backend) — use `hear --engine enhanced`";case`not-allowed`:return`microphone permission denied for builtin speech recognition`;case`audio-capture`:return`no microphone available for builtin speech recognition`;case`no-speech`:return`no speech detected`;case`aborted`:return`speech recognition aborted`;default:return`speech recognition error: ${e}`}}function m(e){return e instanceof f&&(e.code===`network`||e.code===`service-not-allowed`)}function h(e,t){let n=d();return n?new Promise((r,i)=>{let a=Date.now(),o=()=>Date.now()-a,s=new n;s.continuous=!1,s.interimResults=!1,e&&(s.lang=e),c.debug(`builtinOnce: recognizer constructed`,{lang:e??`(browser default)`,timeoutMs:t});let l=``,u=!1,d=setTimeout(()=>{c.debug(`builtinOnce: timeout reached — stopping recognizer`,{elapsedMs:o()});try{s.stop()}catch{}},t);s.onstart=()=>c.debug(`builtinOnce: onstart (recognition service active)`,{elapsedMs:o()}),s.onaudiostart=()=>c.debug(`builtinOnce: onaudiostart (capturing audio)`,{elapsedMs:o()}),s.onspeechstart=()=>c.debug(`builtinOnce: onspeechstart (speech detected)`,{elapsedMs:o()}),s.onspeechend=()=>c.debug(`builtinOnce: onspeechend (speech ended)`,{elapsedMs:o()}),s.onnomatch=()=>c.debug(`builtinOnce: onnomatch (no recognizable speech)`,{elapsedMs:o()}),s.onresult=e=>{let t=[];for(let n=0;n<e.results.length;n++)t.push(e.results[n][0]?.transcript??``);l=t.join(` `).trim(),c.debug(`builtinOnce: onresult`,{elapsedMs:o(),resultCount:e.results.length,transcriptLength:l.length})},s.onerror=e=>{if(e.error===`no-speech`||e.error===`aborted`){c.debug(`builtinOnce: onerror (non-fatal — ends with empty transcript)`,{elapsedMs:o(),code:e.error});return}u=!0,clearTimeout(d),c.error(`builtinOnce: onerror (fatal)`,{elapsedMs:o(),code:e.error}),i(new f(e.error))},s.onend=()=>{clearTimeout(d),u?c.debug(`builtinOnce: onend after fatal error (already rejected)`,{elapsedMs:o()}):(c.debug(`builtinOnce: onend — resolving`,{elapsedMs:o(),transcriptLength:l.length,empty:l.length===0}),r(l))},c.debug(`builtinOnce: calling recognizer.start()`,{elapsedMs:o()}),s.start()}):Promise.reject(Error(`speech recognition unavailable in this environment`))}async function g(e){let t={audio:e?{deviceId:{exact:e}}:!0},n=u();if(n){c.debug(`acquireMicrophoneStream: requesting microphone via permission surface`,{hasDeviceId:!!e});let r=await n.prompt({kinds:[`microphone`],description:`The hear command needs your microphone to transcribe speech.`,requestOptions:{microphone:{constraints:t}},skipIfGranted:!0});if(r.status!==`granted`){c.error(`acquireMicrophoneStream: microphone permission not granted`,{status:r.status,reason:r.reason});let e=r.message?`: ${r.message}`:``;throw Error(`microphone permission ${r.reason??r.status}${e}`)}let i=r.grants.find(e=>e.kind===`microphone`);if(!i)throw c.error(`acquireMicrophoneStream: permission granted without a microphone stream`),Error(`microphone permission granted without a stream`);return c.debug(`acquireMicrophoneStream: microphone stream acquired via surface`),i.stream}if(!navigator.mediaDevices?.getUserMedia)throw c.error(`acquireMicrophoneStream: getUserMedia unavailable in this realm`),Error(`microphone capture unavailable in this realm`);c.debug(`acquireMicrophoneStream: no permission surface; calling getUserMedia directly`);try{let e=await navigator.mediaDevices.getUserMedia(t);return c.debug(`acquireMicrophoneStream: getUserMedia succeeded (direct)`),e}catch(e){throw c.error(`acquireMicrophoneStream: getUserMedia failed (direct)`,e),e}}async function _(e){let t=await g(e),n=new MediaRecorder(t),r=[];n.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},n.start(500);let i=()=>{for(let e of t.getTracks())e.stop()};return{stop:()=>new Promise(e=>{n.onstop=()=>{i(),e(r.length?new Blob(r,{type:n.mimeType||`audio/webm`}):null)};try{n.stop()}catch{i(),e(null)}}),cancel:()=>{try{n.stop()}catch{}i()}}}async function v(e){if(!u())return c.debug(`primeBuiltinPermission: no permission surface; recognizer drives its own prompt`),null;c.debug(`primeBuiltinPermission: priming microphone grant via permission surface`,{hasDeviceId:!!e});let t=await g(e);return c.debug(`primeBuiltinPermission: microphone primed; holding stream open for recognizer`),t}function y(e){if(e){for(let t of e.getTracks())t.stop();c.debug(`primeBuiltinPermission: released primed microphone stream`)}}async function b(e,t){let n=await _(e.deviceId),i=``;try{i=await h(e.lang,t)}catch(e){c.warn(`builtin endpointing failed; transcribing captured audio anyway`,e)}let a=await n.stop();if(!a)return{transcript:i,engine:`builtin`};try{let t=await r(),n=await o(await a.arrayBuffer()),i=await t.transcribe(n,{language:s(e.lang)});if(i)return{transcript:i,engine:`enhanced`}}catch(e){c.warn(`whisper transcription failed; falling back to builtin text`,e)}return{transcript:i,engine:`builtin`}}async function x(e={}){let t=e.timeoutMs??3e4,r=e.engine??`auto`,i=n()===`ready`;if(r===`enhanced`&&!i)throw c.error(`hearCapture: enhanced engine requested but whisper is not ready`),Error("enhanced engine not ready — run `hear --warmup` (check progress with `hear --status`)");let a=r!==`builtin`&&i;if(c.debug(`hearCapture: engine dispatch`,{requested:r,enhancedReady:i,resolved:a?`enhanced`:`builtin`}),a)return b(e,t);let o=await v(e.deviceId);try{let n=await h(e.lang,t);return c.debug(`hearCapture: builtin recognition produced a transcript`),{transcript:n,engine:`builtin`}}catch(n){if(!m(n))throw c.error(`hearCapture: builtin recognition failed`,n),n;if(i)return c.debug(`hearCapture: builtin unsupported in this browser; falling back to enhanced whisper`),y(o),o=null,b(e,t);throw c.error(`hearCapture: builtin unsupported and whisper not ready`,{code:n.code}),n}finally{y(o)}}async function S(e,t){let n=await r(),i=await o(e);return{transcript:await n.transcribe(i,{language:s(t)}),engine:`enhanced`}}function C(){let e=i();return{state:n(),...e?{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}:{}}}function w(){return r().catch(()=>{}),C()}export{x as hearCapture,C as hearStatus,S as hearTranscribe,w as hearWarmup};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./wc-permissions-registry-C7PhTX3c.js";import{i as n,n as r,r as i}from"./whisper-engine-rP8D81pe.js";const a=16e3;async function o(e){if(typeof AudioContext>`u`||typeof OfflineAudioContext>`u`)throw Error(`audio decoding requires a window/page realm (AudioContext unavailable)`);let t=new AudioContext,n;try{n=await t.decodeAudioData(e.slice(0))}finally{await t.close().catch(()=>{})}let r=Math.max(1,Math.ceil(n.duration*a)),i=new OfflineAudioContext(1,r,a),o=i.createBufferSource();return o.buffer=n,o.connect(i.destination),o.start(),(await i.startRendering()).getChannelData(0).slice(0)}e(`speech:whisper-session`);function s(e){return e?.split(`-`)[0]?.toLowerCase()||void 0}const c=e(`speech:hear`);let l={};function u(){return l.getPermissionSurface?l.getPermissionSurface():t()||null}function d(){if(typeof window>`u`)return null;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var f=class extends Error{code;constructor(e){super(p(e)),this.name=`SpeechRecognitionError`,this.code=e}};function p(e){switch(e){case`network`:case`service-not-allowed`:return"builtin speech recognition is unsupported in this browser (no Web Speech cloud backend) — use `hear --engine enhanced`";case`not-allowed`:return`microphone permission denied for builtin speech recognition`;case`audio-capture`:return`no microphone available for builtin speech recognition`;case`no-speech`:return`no speech detected`;case`aborted`:return`speech recognition aborted`;default:return`speech recognition error: ${e}`}}function m(e){return e instanceof f&&(e.code===`network`||e.code===`service-not-allowed`)}function h(e,t){let n=d();return n?new Promise((r,i)=>{let a=Date.now(),o=()=>Date.now()-a,s=new n;s.continuous=!1,s.interimResults=!1,e&&(s.lang=e),c.debug(`builtinOnce: recognizer constructed`,{lang:e??`(browser default)`,timeoutMs:t});let l=``,u=!1,d=setTimeout(()=>{c.debug(`builtinOnce: timeout reached — stopping recognizer`,{elapsedMs:o()});try{s.stop()}catch{}},t);s.onstart=()=>c.debug(`builtinOnce: onstart (recognition service active)`,{elapsedMs:o()}),s.onaudiostart=()=>c.debug(`builtinOnce: onaudiostart (capturing audio)`,{elapsedMs:o()}),s.onspeechstart=()=>c.debug(`builtinOnce: onspeechstart (speech detected)`,{elapsedMs:o()}),s.onspeechend=()=>c.debug(`builtinOnce: onspeechend (speech ended)`,{elapsedMs:o()}),s.onnomatch=()=>c.debug(`builtinOnce: onnomatch (no recognizable speech)`,{elapsedMs:o()}),s.onresult=e=>{let t=[];for(let n=0;n<e.results.length;n++)t.push(e.results[n][0]?.transcript??``);l=t.join(` `).trim(),c.debug(`builtinOnce: onresult`,{elapsedMs:o(),resultCount:e.results.length,transcriptLength:l.length})},s.onerror=e=>{if(e.error===`no-speech`||e.error===`aborted`){c.debug(`builtinOnce: onerror (non-fatal — ends with empty transcript)`,{elapsedMs:o(),code:e.error});return}u=!0,clearTimeout(d),c.error(`builtinOnce: onerror (fatal)`,{elapsedMs:o(),code:e.error}),i(new f(e.error))},s.onend=()=>{clearTimeout(d),u?c.debug(`builtinOnce: onend after fatal error (already rejected)`,{elapsedMs:o()}):(c.debug(`builtinOnce: onend — resolving`,{elapsedMs:o(),transcriptLength:l.length,empty:l.length===0}),r(l))},c.debug(`builtinOnce: calling recognizer.start()`,{elapsedMs:o()}),s.start()}):Promise.reject(Error(`speech recognition unavailable in this environment`))}async function g(e){let t={audio:e?{deviceId:{exact:e}}:!0},n=u();if(n){c.debug(`acquireMicrophoneStream: requesting microphone via permission surface`,{hasDeviceId:!!e});let r=await n.prompt({kinds:[`microphone`],description:`The hear command needs your microphone to transcribe speech.`,requestOptions:{microphone:{constraints:t}},skipIfGranted:!0});if(r.status!==`granted`){c.error(`acquireMicrophoneStream: microphone permission not granted`,{status:r.status,reason:r.reason});let e=r.message?`: ${r.message}`:``;throw Error(`microphone permission ${r.reason??r.status}${e}`)}let i=r.grants.find(e=>e.kind===`microphone`);if(!i)throw c.error(`acquireMicrophoneStream: permission granted without a microphone stream`),Error(`microphone permission granted without a stream`);return c.debug(`acquireMicrophoneStream: microphone stream acquired via surface`),i.stream}if(!navigator.mediaDevices?.getUserMedia)throw c.error(`acquireMicrophoneStream: getUserMedia unavailable in this realm`),Error(`microphone capture unavailable in this realm`);c.debug(`acquireMicrophoneStream: no permission surface; calling getUserMedia directly`);try{let e=await navigator.mediaDevices.getUserMedia(t);return c.debug(`acquireMicrophoneStream: getUserMedia succeeded (direct)`),e}catch(e){throw c.error(`acquireMicrophoneStream: getUserMedia failed (direct)`,e),e}}async function _(e){let t=await g(e),n=new MediaRecorder(t),r=[];n.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},n.start(500);let i=()=>{for(let e of t.getTracks())e.stop()};return{stop:()=>new Promise(e=>{n.onstop=()=>{i(),e(r.length?new Blob(r,{type:n.mimeType||`audio/webm`}):null)};try{n.stop()}catch{i(),e(null)}}),cancel:()=>{try{n.stop()}catch{}i()}}}async function v(e){if(!u())return c.debug(`primeBuiltinPermission: no permission surface; recognizer drives its own prompt`),null;c.debug(`primeBuiltinPermission: priming microphone grant via permission surface`,{hasDeviceId:!!e});let t=await g(e);return c.debug(`primeBuiltinPermission: microphone primed; holding stream open for recognizer`),t}function y(e){if(e){for(let t of e.getTracks())t.stop();c.debug(`primeBuiltinPermission: released primed microphone stream`)}}async function b(e,t){let n=await _(e.deviceId),i=``;try{i=await h(e.lang,t)}catch(e){c.warn(`builtin endpointing failed; transcribing captured audio anyway`,e)}let a=await n.stop();if(!a)return{transcript:i,engine:`builtin`};try{let t=await r(),n=await o(await a.arrayBuffer()),i=await t.transcribe(n,{language:s(e.lang)});if(i)return{transcript:i,engine:`enhanced`}}catch(e){c.warn(`whisper transcription failed; falling back to builtin text`,e)}return{transcript:i,engine:`builtin`}}async function x(e={}){let t=e.timeoutMs??3e4,r=e.engine??`auto`,i=n()===`ready`;if(r===`enhanced`&&!i)throw c.error(`hearCapture: enhanced engine requested but whisper is not ready`),Error("enhanced engine not ready — run `hear --warmup` (check progress with `hear --status`)");let a=r!==`builtin`&&i;if(c.debug(`hearCapture: engine dispatch`,{requested:r,enhancedReady:i,resolved:a?`enhanced`:`builtin`}),a)return b(e,t);let o=await v(e.deviceId);try{let n=await h(e.lang,t);return c.debug(`hearCapture: builtin recognition produced a transcript`),{transcript:n,engine:`builtin`}}catch(n){if(!m(n))throw c.error(`hearCapture: builtin recognition failed`,n),n;if(i)return c.debug(`hearCapture: builtin unsupported in this browser; falling back to enhanced whisper`),y(o),o=null,b(e,t);throw c.error(`hearCapture: builtin unsupported and whisper not ready`,{code:n.code}),n}finally{y(o)}}async function S(e,t){let n=await r(),i=await o(e);return{transcript:await n.transcribe(i,{language:s(t)}),engine:`enhanced`}}function C(){let e=i();return{state:n(),...e?{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}:{}}}function w(){return r().catch(()=>{}),C()}export{x as hearCapture,C as hearStatus,S as hearTranscribe,w as hearWarmup};
@@ -39,10 +39,10 @@ let r=t(),i=n(),a=typeof Symbol==`function`&&typeof Symbol.for==`function`?Symbo
39
39
  `)?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(`
40
40
  `)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const cr={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 lr(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${cr.reset}`:String(n);return{enabled:t,green:n(cr.green),red:n(cr.red),yellow:n(cr.yellow),gray:n(cr.gray),bold:n(cr.bold),cyan:n(cr.cyan),dim:n(cr.dim)}}const ur={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function dr(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*ur[i])}function fr(e){return e<10?`0${e}`:String(e)}const pr={parseDuration:dr,ago(e,t=new Date){return new Date(t.getTime()-dr(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-dr(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+dr(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-dr(e));return`${n.getFullYear()}/${fr(n.getMonth()+1)}/${fr(n.getDate())}`}},mr=/\u001b\[[0-9;]*m/g;function hr(e){return e.replace(mr,``)}function gr(e){return hr(e).length}function _r(e,t){let n=String(e??``);return t<=0?``:gr(n)<=t?n:t<=1?n.slice(0,t):`${hr(n).slice(0,t-1)}…`}function vr(e,t){let n=String(e??``),r=gr(n);return r===t?n:r>t?_r(n,t):n+` `.repeat(t-r)}function yr(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,gr(e))}r[i]=t}return e.map(e=>r.map((t,n)=>vr(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
41
41
  `)}function br(e){return e instanceof Date?e:new Date(e)}function xr(e,t=`short`){let n=br(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()}-${fr(n.getMonth()+1)}-${fr(n.getDate())}`}const Sr={trunc:_r,col:vr,table:yr,date:xr},Cr=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 wr(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 Tr(e){if(e.length===0)return`.`;let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=wr(e.split(`/`),!t).join(`/`);return r.length===0&&!t&&(r=`.`),r.length>0&&n&&(r+=`/`),(t?`/`:``)+r}function Er(...e){let t=e.filter(e=>typeof e==`string`&&e.length>0).join(`/`);return t.length===0?`.`:Tr(t)}function Dr(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 Or(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 kr(e){let t=Or(e),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n)}function Ar(...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=wr(t.split(`/`),!1).join(`/`);return r.length>0?`/${r}`:`/`}function jr(e,t){let n=Ar(e),r=Ar(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 Mr(e){let t=e.charCodeAt(0)===47?`/`:``,n=Or(e),r=kr(e),i=r?n.slice(0,n.length-r.length):n,a=Dr(e);return a===`.`&&t===``&&(a=``),{root:t,dir:a,base:n,ext:r,name:i}}function Nr(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 Pr={sep:`/`,delimiter:`:`,basename:Or,dirname:Dr,extname:kr,isAbsolute:e=>e.length>0&&e.charCodeAt(0)===47,join:Er,normalize:Tr,resolve:Ar,relative:jr,parse:Mr,format:Nr},Fr=65536,Ir={md5:y.md5,sha1:b.sha1,sha256:x.sha256};function Lr(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 Rr(e,t){return typeof e==`string`?t===`hex`||t===`base64`||t===`base64url`||t===`latin1`||t===`binary`?new Uint8Array(Lr(e,t===`binary`?`latin1`:t)):e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function zr(e){let t=Ir[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(Rr(e,t)),i},digest(e){r=!0;let t=Lr(n.array());return e?t.toString(e):t}};return i}function Br(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto: globalThis.crypto is unavailable in this environment`);return e}function Vr(e){return Br().getRandomValues(e)}function Hr(e){for(let t=0;t<e.length;t+=Fr){let n=Math.min(t+Fr,e.length);Vr(e.subarray(t,n))}}function Ur(e){return e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const X=Array.from({length:256},(e,t)=>(t+256).toString(16).slice(1));function Wr(){let e=Br();if(typeof e.randomUUID==`function`)return e.randomUUID();let t=Vr(new Uint8Array(16));return t[6]=t[6]&15|64,t[8]=t[8]&63|128,`${X[t[0]]}${X[t[1]]}${X[t[2]]}${X[t[3]]}-${X[t[4]]}${X[t[5]]}-${X[t[6]]}${X[t[7]]}-${X[t[8]]}${X[t[9]]}-${X[t[10]]}${X[t[11]]}${X[t[12]]}${X[t[13]]}${X[t[14]]}${X[t[15]]}`}const Gr={randomFillSync(e,t=0,n){let r=Ur(e),i=t,a=n===void 0?r.length:i+n;return Hr(r.subarray(i,a)),e},randomBytes(e){let t=globalThis.Buffer,n=t&&typeof t.allocUnsafe==`function`?t.allocUnsafe(e):new Uint8Array(e);return Hr(Ur(n)),n},randomUUID:Wr,getRandomValues(e){return Vr(e)},createHash:zr,get webcrypto(){return Br()},get subtle(){return Br().subtle}};var Z=class extends Error{actual;expected;operator;generatedMessage;code;constructor(e={}){let t=!e.message;super(e.message||`${Kr(e.actual)} ${e.operator||`!=`} ${Kr(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 Kr(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 Q(e,t){return e instanceof Error?e:typeof e==`string`?new Z({message:e}):t()}function qr(e,t,n,r){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!Yr(e[i],t[i],n,r))return!1;return!0}function Jr(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(!Yr(i,o,n,r))return!1}return!0}function Yr(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)?qr(e,t,n,r):Jr(i,a,n,r):!1)}function Xr(e,t){try{if(e instanceof t)return!0}catch{}try{return!!t(e)}catch{return!1}}function Zr(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 Qr(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`?Xr(e,t):t&&typeof t==`object`?!e||typeof e!=`object`?!1:Zr(e,t):!1}function $r(e){let t=(e,t)=>{if(!e)throw Q(t,()=>new Z({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 Q(n,()=>new Z({actual:e,expected:t,operator:`strictEqual`}))},i=(t,n,i)=>{if(e){r(t,n,i);return}if(t!=n)throw Q(i,()=>new Z({actual:t,expected:n,operator:`==`}))},a=(e,t,n)=>{if(Object.is(e,t))throw Q(n,()=>new Z({actual:e,expected:t,operator:`notStrictEqual`}))},o=(t,n,r)=>{if(e){a(t,n,r);return}if(t==n)throw Q(r,()=>new Z({actual:t,expected:n,operator:`!=`}))},s=(e,t,n)=>{if(!Yr(e,t,!0,new WeakMap))throw Q(n,()=>new Z({actual:e,expected:t,operator:`deepStrictEqual`}))},c=(t,n,r)=>{if(e){s(t,n,r);return}if(!Yr(t,n,!1,new WeakMap))throw Q(r,()=>new Z({actual:t,expected:n,operator:`deepEqual`}))},l=(e,t,n)=>{if(Yr(e,t,!0,new WeakMap))throw Q(n,()=>new Z({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(Yr(t,n,!1,new WeakMap))throw Q(r,()=>new Z({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 Q(typeof t==`string`?t:n,()=>new Z({message:`Missing expected exception`,operator:`throws`}));if(!(typeof t==`string`||t instanceof Error)&&!Qr(r,t))throw Q(n,()=>new Z({message:`Got unwanted exception`,actual:r,operator:`throws`}))},n.doesNotThrow=(e,t)=>{try{e()}catch(e){throw Q(t,()=>new Z({message:`Got unwanted exception`,actual:e,operator:`doesNotThrow`}))}},n.fail=e=>{throw Q(e,()=>new Z({message:`Failed`,operator:`fail`}))},n.AssertionError=Z,n}const ei=$r(!0);ei.strict=ei;const ti=$r(!1);ti.strict=ei;const ni=Symbol.for(`nodejs.util.inspect.custom`),ri=Symbol.for(`nodejs.util.promisify.custom`);function ii(e){return`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}'`}function ai(e){if(e===null)return`null`;let t=typeof e;if(t===`string`)return ii(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 oi(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 si(e,t,n){if(Array.isArray(e))return e.length===0?`[]`:`[ ${e.map(e=>ci(e,t+1,n)).join(`, `)} ]`;if(e instanceof Map){let r=[...e].map(([e,r])=>`${ci(e,t+1,n)} => ${ci(r,t+1,n)}`);return`Map(${e.size}) {${r.length?` ${r.join(`, `)} `:``}}`}if(e instanceof Set){let r=[...e].map(e=>ci(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:ii(r)}: ${ci(e[r],t+1,n)}`).join(`, `)} }`}function ci(e,t,n){let r=ai(e);if(r!==null)return r;let i=e,a=oi(i);if(a!==null)return a;let o=i[ni];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 si(i,t,n)}finally{n.seen.delete(e)}}function li(e,t={}){let n=t.depth===void 0?2:t.depth;return ci(e,0,{seen:new Set,maxDepth:n,opts:t})}function ui(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):li(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++,li(i,{depth:4});case`%O`:return n.i++,li(i,{depth:null});case`%c`:return n.i++,``;default:return e}}function di(e,...t){let n=t[0];if(typeof n!=`string`)return t.map(e=>typeof e==`string`?e:li(e)).join(` `);let r={i:1},i=n.replace(/%[sdifjoOc%]/g,n=>ui(n,t,r,e));for(;r.i<t.length;r.i++){let e=t[r.i];i+=` ${typeof e==`string`?e:li(e)}`}return i}function fi(...e){return di({},...e)}function pi(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 mi(e){if(typeof e!=`function`)throw TypeError(`The "original" argument must be of type function`);let t=e[ri];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 hi=li;hi.custom=ni;const gi=mi;gi.custom=ri;const _i={format:fi,formatWithOptions:di,inspect:hi,inherits:pi,promisify:gi};function vi(e){return typeof e==`string`?new Uint8Array(Lr(e,`utf8`)):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function yi(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 bi(e,t,n){return Lr(e(vi(t),yi(n)))}function xi(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=bi(e,t,a)}catch(e){queueMicrotask(()=>i(e instanceof Error?e:Error(String(e))));return}queueMicrotask(()=>i(null,o))}const Si={gzipSync:(e,t)=>bi($n,e,t),gunzipSync:(e,t)=>bi(rr,e,t),deflateSync:(e,t)=>bi(Zn,e,t),inflateSync:(e,t)=>bi(rr,e,t),deflateRawSync:(e,t)=>bi(Qn,e,t),inflateRawSync:(e,t)=>bi(ir,e,t),gzip:(e,t,n)=>xi($n,e,t,n),gunzip:(e,t,n)=>xi(rr,e,t,n),deflate:(e,t,n)=>xi(Zn,e,t,n),inflate:(e,t,n)=>xi(rr,e,t,n),deflateRaw:(e,t,n)=>xi(Qn,e,t,n),inflateRaw:(e,t,n)=>xi(ir,e,t,n),constants:{Z_NO_FLUSH:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1}},Ci={tmpdir:()=>`/tmp`,homedir:()=>`/home/user`,platform:()=>`linux`,arch:()=>`x64`,EOL:`
42
- `,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function wi(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 Ti(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const Ei={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:wi,pathToFileURL:Ti};var Di=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 Oi=Object.assign(Di,{EventEmitter:Di,default:Di});var ki=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}},Ai=class extends ki{read(){return null}destroy(){return this}},ji=class extends ki{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},Mi=class extends ki{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const Ni={Readable:Ai,Writable:ji,Transform:Mi,PassThrough:class extends Mi{},Stream:ki};let Pi=1;function Fi(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 Ii(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?Lr(e):Lr(e).toString(t)}function Li(e,t){if(e.length===0)return Ii(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function Ri(e,t,n){t.length>0&&e.emit(`data`,Ii(t,n)),e.readable=!1,e.emit(`end`)}function zi(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(Fi(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(Fi(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var Bi=class extends Di{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=Pi++,this.spawnfile=n,this.spawnargs=r,this.stdout=new Ai,this.stderr=new Ai,this.stdin=zi(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){Ri(this.stdout,e.stdout,t),Ri(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 Vi(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new Bi(o,r,i,a);return n.input!==void 0&&s.stdin.write(Fi(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,Li(i,t),Li(a,t))),e.once(`close`,(o,s)=>{let c=Li(i,t),l=Li(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${Fi(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,ri,{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:Bi}}const Hi=new Set([`child_process`,`events`,`fs`,`fs/promises`,`os`,`path`,`stream`,`url`,`crypto`,`process`,`buffer`,`assert`,`assert/strict`,`util`]),Ui=new Set([...new Set(`assert.assert/strict.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.dns/promises.domain.events.fs.fs/promises.http.http2.https.inspector.inspector/promises.module.net.os.path.path/posix.path/win32.perf_hooks.process.punycode.querystring.readline.readline/promises.repl.stream.stream/consumers.stream/promises.stream/web.string_decoder.sys.timers.timers/promises.tls.trace_events.tty.url.util.util/types.v8.vm.wasi.worker_threads.zlib`.split(`.`))].filter(e=>!Hi.has(e)));var Wi=class{port;nextId=1;pending=new Map;eventSubscribers=new Map;handler;disposed=!1;constructor(e){this.port=e,this.handler=e=>{let t=e.data;if(t?.type===`realm-rpc-res`){let t=e.data,n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),typeof t.error==`string`?n.reject(Error(t.error)):n.resolve(t.result);return}if(t?.type===`realm-event`){let t=e.data,n=this.eventSubscribers.get(t.channel);if(!n)return;for(let e of[...n])try{e(t.payload)}catch{}}},e.addEventListener(`message`,this.handler),e.start?.()}get pendingCount(){return this.pending.size}call(e,t,n=[]){if(this.disposed)return Promise.reject(Error(`realm-rpc: client disposed`));let r=this.nextId++,i={type:`realm-rpc-req`,id:r,channel:e,op:t,args:n};return new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t}),this.port.postMessage(i)})}onEvent(e,t){if(this.disposed)return()=>{};let n=this.eventSubscribers.get(e);return n||(n=new Set,this.eventSubscribers.set(e,n)),n.add(t),()=>{let n=this.eventSubscribers.get(e);n&&(n.delete(t),n.size===0&&this.eventSubscribers.delete(e))}}dispose(){if(this.disposed)return;this.disposed=!0,this.port.removeEventListener(`message`,this.handler);let e=Error(`realm-rpc: client disposed`);for(let t of this.pending.values())t.reject(e);this.pending.clear(),this.eventSubscribers.clear()}};const Gi=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`]),Ki={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 qi(e,t){let n=Ki[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function Ji(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function Yi(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function Xi(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function Zi(e){let t=Ji(e.argv[1]??``),n=Xi(t,`references`),r=Xi(t,`assets`),i=Xi(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)+`
43
- `),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 ${Yi(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){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 Qi(e){let t=$(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function $i(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function ea(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function ta(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 na=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=$(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=Qi($(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=Qi(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=Qi(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}readFile(e){this.touched=!0;let t=$(e),n=this.tree.get(t);if(!n||n.isDirectory)throw $i(t);if(n.truncated)throw ea(t);return n.content}writeFile(e,t){this.touched=!0;let n=$(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1})}exists(e){this.touched=!0;let t=$(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=$(e),n=this.tree.get(t);if(!n)throw $i(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.content.byteLength}}readdir(e){this.touched=!0;let t=$(e);if(!this.tree.get(t)?.isDirectory)throw $i(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);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=Qi(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw $i(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0})}rm(e,t){this.touched=!0;let n=$(e),r=this.tree.get(n);if(!r)throw $i(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),r=this.tree.get(n);if(!r||r.isDirectory)throw $i(n);let i=$(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1})}rename(e,t){this.touched=!0;let n=$(e),r=this.tree.get(n);if(!r)throw $i(n);let i=$(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),n=this.tree.get(t);if(!n)throw $i(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+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&&!ta(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 ra(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var ia=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function aa(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function oa(e,t){let n;try{n=await e.call(`vfs`,`snapshot`,[t])}catch{n={entries:[]}}return new na(n)}function sa(e){return{usbBridge:Xa(e),serialBridge:Qa(e),hidBridge:eo(e)}}async function ca(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=da(i,a),{processShim:s,getDidCallProcessExit:c}=fa(e,i,a),l=!!e.env?.NO_COLOR,u=lr({isTTY:!l,noColor:l}),d=sr({writeStdout:i,writeStderr:a,exit:e=>{throw new ia(e)},color:u}),f=new Wi(t),p=ba(f,w),h=await oa(f,e.cwd);Object.assign(p,xa(h,e.cwd));let g=ma(f,h,e.cwd),_=_a(g,{cwd:e.cwd}),v=Zi({argv:e.argv,fs:p,exec:g}),y=Pa(f),{usbBridge:b,serialBridge:x,hidBridge:S}=sa(f),C=m({fetch:w});async function w(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,Na(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 T=va({exec:g,agent:_,skill:v,http:C,browser:y,usb:b,serial:x,hid:S,cli:d,color:u}),E=e.filename,D=ra(E),O=await wa(f,e.code,e.cwd,E),k=Ea({graph:O,fsBridge:p,processShim:s,childProcess:Vi(g),nodeConsole:o,sliccyModules:T}).require,A={exports:{},filename:e.filename},j=O.entrySource!==void 0,ee=O.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let te=await Ma(ee,{process:s,console:o,require:k,module:A,exports:A.exports,fetch:w,__dirname:D,__filename:E},a,j);await la(f,h,a),c()||await ua(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:te})}async function la(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 ua(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 da(e,t){return{log:(...t)=>e(`${t.map(aa).join(` `)}
44
- `),info:(...t)=>e(`${t.map(aa).join(` `)}
45
- `),warn:(...e)=>t(`${e.map(aa).join(` `)}
46
- `),error:(...e)=>t(`${e.map(aa).join(` `)}
47
- `)}}function fa(e,t,n){let r=!!e.env?.NO_COLOR,i=ya(e.stdin??``),a=or(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new ia(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function pa(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function ma(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:pa(t)}),Promise.resolve(!0)),stdin:{write:e=>{!c&&!u&&o.push(e)},end:()=>m()},done:p}}});return c.exec=c,c}function ha(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 ga(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`,ha(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 _a(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(ga(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 va(e){return{...e,time:pr,fmt:Sr,pool:Cr}}function ya(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 ba(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 xa(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 Sa(e,t){return e?.startsWith(`/`)?ra(e):t}function Ca(e){return e.includes(`require`)||e.includes(`import`)}async function wa(e,t,n,r){return Ca(t)?e.call(`module`,`buildGraph`,[t,Sa(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function Ta(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 Ea(e){let{graph:t,fsBridge:n,processShim:r,childProcess:i,nodeConsole:a,sliccyModules:o}=e,s=new Map(t.files.map(e=>[e.path,e.cjsSource])),c=new Map(t.files.map(e=>[e.path,e.kind])),l=new Map,u=e=>{if(typeof e==`string`&&e.startsWith(`sliccy:`))return{hit:!0,value:ka(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=Da(t,n,r,i);if(a.hit)return a;if(Gi.has(t))throw qi(e,t);if(Ui.has(t))throw ja(e,t);return{hit:!1}},d=(e,n)=>{let r=u(n);if(r.hit)return r.value;let i=e?.[n];if(i)return f(i);throw n in t.errors?Error(t.errors[n]):Oa(n)};function f(e){let n=l.get(e);if(n)return n.exports;let i=s.get(e);if(i===void 0)throw Error(`Cannot find module '${e}'`);let o={exports:{}};l.set(e,o);let u=n=>d(t.edges[e],n),f=ra(e);return Function(`module`,`exports`,`require`,`__dirname`,`__filename`,`process`,`console`,`Buffer`,`global`,i)(o,o.exports,u,f,e,r,a,globalThis.Buffer,globalThis),c.get(e)===`cjs`&&Ta(o.exports),o.exports}return{require:e=>d(t.entryMap,e)}}function Da(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:Pr}:e===`crypto`?{hit:!0,value:Gr}: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:ti}:e===`assert/strict`?{hit:!0,value:ei}:e===`util`?{hit:!0,value:_i}:e===`events`?{hit:!0,value:Oi}:e===`os`?{hit:!0,value:Ci}:e===`stream`?{hit:!0,value:Ni}:e===`url`?{hit:!0,value:Ei}:e===`zlib`?{hit:!0,value:Si}:{hit:!1}}function Oa(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 ka(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 Aa={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function ja(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${Aa[t]||``}`)}async function Ma(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";
48
- `:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof ia?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function Na(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 Pa(e){return{findTab:t=>e.call(`browser`,`findTab`,[Ua(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,Wa(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Fa(t),Ia(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Fa(t),Ia(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Fa(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Fa(t),n]),fetch:(t,n,r={})=>Ha(n,r).then(n=>e.call(`browser`,`evalAsync`,[Fa(t),n])),websocket:Ga(e)}}function Fa(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 Ia(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 La(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 Ra(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:La(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function za(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:La(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:La(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:La(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Ra(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Ba(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 Va(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 Ha(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 za(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=Ba(c),d=Va(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function Ua(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 Wa(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function Ga(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=Fa(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 Ka(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 qa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ja(e){return e==null?[]:Array.isArray(e)?e:[e]}function Ya(e,t){let n=t.handle,r=e=>({status:e.status,data:qa(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,Ka(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,Ka(r)])}}function Xa(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>Ya(e,t)),request:async t=>Ya(e,await e.call(`usb`,`request`,[Ja(t)]))}}function Za(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?Ka(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,Ka(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function Qa(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>Za(e,t)),request:async t=>Za(e,await e.call(`serial`,`request`,[Ja(t)]))}}function $a(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:qa(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,Ka(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,Ka(r)]),receiveFeatureReport:async t=>qa((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 eo(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>$a(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[Ja(t)]))[0];if(!n)throw Error(`No device selected.`);return $a(e,n)}}}const to={postMessage:(e,t)=>t?self.postMessage(e,t):self.postMessage(e),addEventListener:(e,t)=>self.addEventListener(e,t),removeEventListener:(e,t)=>self.removeEventListener(e,t)};self.addEventListener(`message`,e=>{if(e.data?.type!==`realm-init`)return;let t=e.data;t.kind===`js`&&ca(t,to).catch(e=>{let t={type:`realm-error`,message:e instanceof Error?e.message:String(e)};self.postMessage(t)})});
42
+ `,cpus:()=>[{model:`virtual`,speed:0}],hostname:()=>`slicc`,type:()=>`Linux`,release:()=>`0.0.0`};function wi(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 Ti(e){let t=e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`);return new URL(`file://${t}`)}const Ei={URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams,fileURLToPath:wi,pathToFileURL:Ti};var Di=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 Oi=Object.assign(Di,{EventEmitter:Di,default:Di});var ki=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}},Ai=class extends ki{read(){return null}destroy(){return this}},ji=class extends ki{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}destroy(){return this}},Mi=class extends ki{write(e,t,n){return n&&queueMicrotask(n),!0}end(e){return e&&queueMicrotask(e),this}read(){return null}destroy(){return this}};const Ni={Readable:Ai,Writable:ji,Transform:Mi,PassThrough:class extends Mi{},Stream:ki};let Pi=1;function Fi(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 Ii(e,t){return t===void 0||t===`utf8`||t===`utf-8`?e:t===`buffer`||t===null?Lr(e):Lr(e).toString(t)}function Li(e,t){if(e.length===0)return Ii(``,t);if(typeof e[0]==`string`)return e.join(``);let n=globalThis.Buffer;return n?n.concat(e):e[0]}function Ri(e,t,n){t.length>0&&e.emit(`data`,Ii(t,n)),e.readable=!1,e.emit(`end`)}function zi(e){let t=e=>{typeof e==`function`&&queueMicrotask(e)};return{writable:!0,write(n,r,i){return e.stdin.write(Fi(n)),t(typeof r==`function`?r:i),!0},end(n,r,i){n!==void 0&&typeof n!=`function`&&e.stdin.write(Fi(n)),e.stdin.end(),this.writable=!1,t(typeof n==`function`?n:typeof r==`function`?r:i)}}}var Bi=class extends Di{stdout;stderr;stdin;pid;exitCode=null;signalCode=null;killed=!1;spawnfile;spawnargs;handle;constructor(e,t,n,r){super(),this.handle=e,this.pid=Pi++,this.spawnfile=n,this.spawnargs=r,this.stdout=new Ai,this.stderr=new Ai,this.stdin=zi(e),e.done.then(e=>this.finish(e,t),e=>this.emit(`error`,e instanceof Error?e:Error(String(e))))}finish(e,t){Ri(this.stdout,e.stdout,t),Ri(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 Vi(e){let t=(t,n,r,i,a)=>{let o=e.start(t),s=new Bi(o,r,i,a);return n.input!==void 0&&s.stdin.write(Fi(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,Li(i,t),Li(a,t))),e.once(`close`,(o,s)=>{let c=Li(i,t),l=Li(a,t);if(o===0){r(null,c,l);return}r(Object.assign(Error(`Command failed: ${n}\n${Fi(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,ri,{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:Bi}}const Hi=new Set([`child_process`,`events`,`fs`,`fs/promises`,`os`,`path`,`stream`,`url`,`crypto`,`process`,`buffer`,`assert`,`assert/strict`,`util`]),Ui=new Set([...new Set(`assert.assert/strict.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.dns/promises.domain.events.fs.fs/promises.http.http2.https.inspector.inspector/promises.module.net.os.path.path/posix.path/win32.perf_hooks.process.punycode.querystring.readline.readline/promises.repl.stream.stream/consumers.stream/promises.stream/web.string_decoder.sys.timers.timers/promises.tls.trace_events.tty.url.util.util/types.v8.vm.wasi.worker_threads.zlib`.split(`.`))].filter(e=>!Hi.has(e)));function Wi(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 Gi=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 };`)}},Ki=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=Wi(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 Gi(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 Gi(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)}},qi=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 Ki(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 Ji(e){let t=async t=>new qi(e);return{chromium:{launch:t},firefox:{launch:t},webkit:{launch:t}}}var Yi=class{port;nextId=1;pending=new Map;eventSubscribers=new Map;handler;disposed=!1;constructor(e){this.port=e,this.handler=e=>{let t=e.data;if(t?.type===`realm-rpc-res`){let t=e.data,n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),typeof t.error==`string`?n.reject(Error(t.error)):n.resolve(t.result);return}if(t?.type===`realm-event`){let t=e.data,n=this.eventSubscribers.get(t.channel);if(!n)return;for(let e of[...n])try{e(t.payload)}catch{}}},e.addEventListener(`message`,this.handler),e.start?.()}get pendingCount(){return this.pending.size}call(e,t,n=[]){if(this.disposed)return Promise.reject(Error(`realm-rpc: client disposed`));let r=this.nextId++,i={type:`realm-rpc-req`,id:r,channel:e,op:t,args:n};return new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t}),this.port.postMessage(i)})}onEvent(e,t){if(this.disposed)return()=>{};let n=this.eventSubscribers.get(e);return n||(n=new Set,this.eventSubscribers.set(e,n)),n.add(t),()=>{let n=this.eventSubscribers.get(e);n&&(n.delete(t),n.size===0&&this.eventSubscribers.delete(e))}}dispose(){if(this.disposed)return;this.disposed=!0,this.port.removeEventListener(`message`,this.handler);let e=Error(`realm-rpc: client disposed`);for(let t of this.pending.values())t.reject(e);this.pending.clear(),this.eventSubscribers.clear()}};const Xi=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`]),Zi={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 Qi(e,t){let n=Zi[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function $i(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function ea(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function ta(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function na(e){let t=$i(e.argv[1]??``),n=ta(t,`references`),r=ta(t,`assets`),i=ta(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)+`
43
+ `),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 ${ea(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){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 ra(e){let t=$(e);if(t===`/`)return`/`;let n=t.lastIndexOf(`/`);return n===0?`/`:t.slice(0,n)}function ia(e){return Object.assign(Error(`ENOENT: no such file or directory, '${e}'`),{code:`ENOENT`})}function aa(e){return Object.assign(Error(`ENOSYNC: file too large for sync access, '${e}' — use async readFile() instead`),{code:`ENOSYNC`})}function oa(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 sa=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=$(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=ra($(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=ra(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=ra(e);t!==`/`&&(this.tree.has(t)||this.mkdir(t,!0))}readFile(e){this.touched=!0;let t=$(e),n=this.tree.get(t);if(!n||n.isDirectory)throw ia(t);if(n.truncated)throw aa(t);return n.content}writeFile(e,t){this.touched=!0;let n=$(e);this.ensureParentDirs(n),this.tree.set(n,{content:t,isDirectory:!1})}exists(e){this.touched=!0;let t=$(e);return this.tree.has(t)}stat(e){this.touched=!0;let t=$(e),n=this.tree.get(t);if(!n)throw ia(t);return{isFile:!n.isDirectory,isDirectory:n.isDirectory,size:n.isDirectory?0:n.content.byteLength}}readdir(e){this.touched=!0;let t=$(e);if(!this.tree.get(t)?.isDirectory)throw ia(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);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=ra(n);if(r!==`/`&&!this.tree.has(r)){if(!t)throw ia(n);this.mkdir(r,!0)}this.tree.set(n,{content:new Uint8Array,isDirectory:!0})}rm(e,t){this.touched=!0;let n=$(e),r=this.tree.get(n);if(!r)throw ia(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),r=this.tree.get(n);if(!r||r.isDirectory)throw ia(n);let i=$(t);this.ensureParentDirs(i),this.tree.set(i,{content:r.content.slice(),isDirectory:!1})}rename(e,t){this.touched=!0;let n=$(e),r=this.tree.get(n);if(!r)throw ia(n);let i=$(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),n=this.tree.get(t);if(!n)throw ia(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+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&&!oa(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 ca(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}var la=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function ua(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function da(e,t){let n;try{n=await e.call(`vfs`,`snapshot`,[t])}catch{n={entries:[]}}return new sa(n)}function fa(e){return{usbBridge:no(e),serialBridge:io(e),hidBridge:oo(e)}}async function pa(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=ga(i,a),{processShim:s,getDidCallProcessExit:c}=_a(e,i,a),l=!!e.env?.NO_COLOR,u=lr({isTTY:!l,noColor:l}),d=sr({writeStdout:i,writeStderr:a,exit:e=>{throw new la(e)},color:u}),f=new Yi(t),p=Ta(f,w),h=await da(f,e.cwd);Object.assign(p,Ea(h,e.cwd));let g=ya(f,h,e.cwd),_=Sa(g,{cwd:e.cwd}),v=na({argv:e.argv,fs:p,exec:g}),y=Ba(f),{usbBridge:b,serialBridge:x,hidBridge:S}=fa(f),C=m({fetch:w});async function w(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await f.call(`fetch`,`request`,[n,za(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 T=Ca({exec:g,agent:_,skill:v,http:C,browser:y,usb:b,serial:x,hid:S,cli:d,color:u}),E=e.filename,D=ca(E),O=await ka(f,e.code,e.cwd,E),k=Ma({graph:O,fsBridge:p,processShim:s,childProcess:Vi(g),nodeConsole:o,sliccyModules:T,shimmedPackages:ja(f)}).require,A={exports:{},filename:e.filename},j=O.entrySource!==void 0,ee=O.entrySource??e.code,M=globalThis;M.__slicc_compileWasm=e=>f.call(`wasm`,`compile`,[e]);let te=await Ra(ee,{process:s,console:o,require:k,module:A,exports:A.exports,fetch:w,__dirname:D,__filename:E},a,j);await ma(f,h,a),c()||await ha(f),delete M.__slicc_compileWasm,f.dispose(),t.postMessage({type:`realm-done`,stdout:n.join(``),stderr:r.join(``),exitCode:te})}async function ma(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 ha(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 ga(e,t){return{log:(...t)=>e(`${t.map(ua).join(` `)}
44
+ `),info:(...t)=>e(`${t.map(ua).join(` `)}
45
+ `),warn:(...e)=>t(`${e.map(ua).join(` `)}
46
+ `),error:(...e)=>t(`${e.map(ua).join(` `)}
47
+ `)}}function _a(e,t,n){let r=!!e.env?.NO_COLOR,i=wa(e.stdin??``),a=or(e.argv),o=!1;return{processShim:{argv:a,env:e.env,cwd:()=>e.cwd,exit:e=>{throw o=!0,new la(Number.isFinite(e)?Number(e):0)},stdin:i,stdout:{write:t,isTTY:!r},stderr:{write:n,isTTY:!r}},getDidCallProcessExit:()=>o}}function va(e){return e===`SIGKILL`?137:e===`SIGINT`?130:143}function ya(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:va(t)}),Promise.resolve(!0)),stdin:{write:e=>{!c&&!u&&o.push(e)},end:()=>m()},done:p}}});return c.exec=c,c}function ba(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 xa(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`,ba(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 Sa(e,t){let n=t.cwd,r=async(t,r)=>{let i=r??{},a=await e.spawn(xa(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 Ca(e){return{...e,time:pr,fmt:Sr,pool:Cr}}function wa(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 Ta(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 Ea(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 Da(e,t){return e?.startsWith(`/`)?ca(e):t}function Oa(e){return e.includes(`require`)||e.includes(`import`)}async function ka(e,t,n,r){return Oa(t)?e.call(`module`,`buildGraph`,[t,Da(r,n),r]):{files:[],entryMap:{},edges:{},errors:{}}}function Aa(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 ja(e){return{playwright:Ji(e)}}function Ma(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:Fa(e,o)};let t=e.startsWith(`node:`)?e.slice(5):e,a=Na(t,n,r,i);if(a.hit)return a;if(Xi.has(t))throw Qi(e,t);if(Ui.has(t))throw La(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]):Pa(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=ca(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`&&Aa(o.exports),o.exports}return{require:e=>f(t.entryMap,e)}}function Na(e,t,n,r){return e===`fs`||e===`fs/promises`?{hit:!0,value:t}:e===`path`?{hit:!0,value:Pr}:e===`crypto`?{hit:!0,value:Gr}: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:ti}:e===`assert/strict`?{hit:!0,value:ei}:e===`util`?{hit:!0,value:_i}:e===`events`?{hit:!0,value:Oi}:e===`os`?{hit:!0,value:Ci}:e===`stream`?{hit:!0,value:Ni}:e===`url`?{hit:!0,value:Ei}:e===`zlib`?{hit:!0,value:Si}:{hit:!1}}function Pa(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 Fa(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 Ia={http:` Use fetch() instead.`,https:` Use fetch() instead.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`};function La(e,t){return Error(`require('${e}'): Node built-in '${t}' is not available in the browser environment.${Ia[t]||``}`)}async function Ra(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";
48
+ `:``}${e}`);try{return await s(...a),0}catch(e){return e instanceof la?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function za(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 Ba(e){return{findTab:t=>e.call(`browser`,`findTab`,[Ya(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,Xa(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[Va(t),Ha(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[Va(t),Ha(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[Va(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[Va(t),n]),fetch:(t,n,r={})=>Ja(n,r).then(n=>e.call(`browser`,`evalAsync`,[Va(t),n])),websocket:Za(e)}}function Va(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 Ha(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 Ua(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 Wa(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:Ua(e),filename:typeof r.name==`string`?r.name:`blob`,type:r.type||``}})}return{kind:`formdata`,entries:t}}async function Ga(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:Ua(new Uint8Array(await e.arrayBuffer())),type:e.type||``}}:e instanceof ArrayBuffer?{descriptor:{kind:`bytes`,data:Ua(new Uint8Array(e))}}:ArrayBuffer.isView(e)?{descriptor:{kind:`bytes`,data:Ua(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}}:e instanceof FormData?{descriptor:await Wa(e)}:(n()||(t[`Content-Type`]=`application/json`),{body:JSON.stringify(e)})}function Ka(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 qa(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 Ja(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 Ga(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=Ka(c),d=qa(t.responseType);return`(async () => {const __init = `+JSON.stringify(l)+`;`+u+`const r = await fetch(`+JSON.stringify(e)+`, __init);`+d+`})()`}function Ya(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 Xa(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function Za(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=Va(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 Qa(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 $a(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function eo(e){return e==null?[]:Array.isArray(e)?e:[e]}function to(e,t){let n=t.handle,r=e=>({status:e.status,data:$a(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,Qa(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,Qa(r)])}}function no(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>to(e,t)),request:async t=>to(e,await e.call(`usb`,`request`,[eo(t)]))}}function ro(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?Qa(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,Qa(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function io(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>ro(e,t)),request:async t=>ro(e,await e.call(`serial`,`request`,[eo(t)]))}}function ao(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:$a(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,Qa(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,Qa(r)]),receiveFeatureReport:async t=>$a((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 oo(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>ao(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[eo(t)]))[0];if(!n)throw Error(`No device selected.`);return ao(e,n)}}}const so={postMessage:(e,t)=>t?self.postMessage(e,t):self.postMessage(e),addEventListener:(e,t)=>self.addEventListener(e,t),removeEventListener:(e,t)=>self.removeEventListener(e,t)};self.addEventListener(`message`,e=>{if(e.data?.type!==`realm-init`)return;let t=e.data;t.kind===`js`&&pa(t,so).catch(e=>{let t={type:`realm-error`,message:e instanceof Error?e.message:String(e)};self.postMessage(t)})});