(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="b849b593-4d79-5267-8e92-e0f3629f4773",globalThis._sentryDebugIdIdentifier="sentry-dbid-b849b593-4d79-5267-8e92-e0f3629f4773");})();

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------------------------------------------*/
import __module from "module";
import __path from "path";
import __fs from "fs";
const __rootRequire = __module.createRequire(import.meta.url);
const __appPath = __fs.realpathSync(import.meta.dirname);
const __sharpEntrypoint = __path.join(__appPath, "sharp", "index.js");
const __clipboardEntrypoint = __path.join(__appPath, "clipboard", "index.js");
const __foundryEntrypoint = __path.join(__appPath, "foundry-local-sdk", "index.js");
const __pvRecorderEntrypoint = __path.join(__appPath, "pvrecorder", "index.js");
const __sharpRequire = __fs.existsSync(__sharpEntrypoint)
    ? __module.createRequire(__sharpEntrypoint)
    : __rootRequire;
const __clipboardRequire = __fs.existsSync(__clipboardEntrypoint)
    ? __module.createRequire(__clipboardEntrypoint)
    : __rootRequire;
const __foundryRequire = __fs.existsSync(__foundryEntrypoint)
    ? __module.createRequire(__foundryEntrypoint)
    : __rootRequire;
const __pvRecorderRequire = __fs.existsSync(__pvRecorderEntrypoint)
    ? __module.createRequire(__pvRecorderEntrypoint)
    : __rootRequire;
const __isVendoredNativeModule = (module) =>
    typeof module === "string" &&
    (module.startsWith("@img/") || module.startsWith("@teddyzhu/") || module === "foundry-local-sdk" || module === "@picovoice/pvrecorder-node");
const require = (module) => {
    let req = __rootRequire;
    if (typeof module === "string" && module.startsWith("@img/")) {
        req = __sharpRequire;
    }
    if (typeof module === "string" && module.startsWith("@teddyzhu/")) {
        req = __clipboardRequire;
    }
    if (module === "foundry-local-sdk") {
        req = __foundryRequire;
    }
    if (module === "@picovoice/pvrecorder-node") {
        req = __pvRecorderRequire;
    }

    if (typeof module === "string" && (__module.isBuiltin(module) || __isVendoredNativeModule(module))) {
        return req(module);
    }

    const modulePath = __fs.realpathSync(req.resolve(module));
    const relativePath = __path.relative(__appPath, modulePath);

    if (relativePath.startsWith("..")) {
        throw new Error("Requiring module outside of application is a security concern; module: " + modulePath + ", app: " + __appPath);
    }

    return req(module);
};import __url from "url";
const __filename = __url.fileURLToPath(import.meta.url);
const __dirname = __path.dirname(__filename);
import{parentPort as A,workerData as re}from"node:worker_threads";var m=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;writePromise=this.initialQueueResolvers.promise;setLogWriter(r){this.logWriter=r;for(let t of this.initialQueue)this.writePromise=this.logWriter.writeLog(t.method,t.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(r,t){this.logWriter?this.writePromise=this.logWriter.writeLog(r,t):this.initialQueue.push({method:r,message:t})}info(r){this.logToLevel("info",r)}debug(r){this.logToLevel("debug",r)}warning(r){this.logToLevel("warning",r)}error(r){this.logToLevel("error",r instanceof Error?r.message:r)}log(r){this.error(r)}isDebug(){return!1}shouldLog(r){return!0}notice(r){this.info(r instanceof Error?r.message:r)}startGroup(r,t){this.info(`--- Start of group: ${r} ---`)}endGroup(r){this.info("--- End of group ---")}},u=new m;import{createRequire as W}from"node:module";import{existsSync as H}from"node:fs";import*as s from"node:fs/promises";import*as a from"node:path";import{createHash as J}from"node:crypto";import{join as l,basename as ie}from"node:path";import{homedir as h}from"node:os";function D(){return process.env.XDG_CACHE_HOME||l(h(),".cache")}function b(){if(process.platform==="darwin")return l(h(),"Library","Caches","copilot");if(process.platform==="win32"){let e=process.env.LOCALAPPDATA||l(h(),".cache");return l(e,"copilot")}return l(D(),"copilot")}function j(e){if(e.includes("<!DOCTYPE")||e.includes("<html")){let r=Math.min(e.indexOf("<!DOCTYPE")!==-1?e.indexOf("<!DOCTYPE"):1/0,e.indexOf("<html")!==-1?e.indexOf("<html"):1/0),t=e.substring(0,r).trim();return t?`${t} [HTML error page omitted]`:"[HTML error page omitted]"}return e}function y(e){let r;if(e instanceof Error)r=String(e);else if(typeof e=="object"&&e!==null)try{r=JSON.stringify(e)??"[object]"}catch{return"[object with circular reference]"}else r=String(e);return j(r)}var U=1,I=".complete";var w={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function O(){return typeof __foundryRequire<"u"&&__foundryRequire||W(import.meta.url)}var f;function V(){if(f)return f;try{let e=O()("foundry-local-sdk/script/install-utils.cjs");if(typeof e.runInstall!="function")throw new Error(`Expected exports {runInstall: function}, got: ${JSON.stringify(Object.fromEntries(Object.entries(e).map(([r,t])=>[r,typeof t])))}`);return f=e,f}catch(e){throw new Error(`Failed to load foundry-local-sdk/script/install-utils.cjs: ${y(e)}. The upstream foundry-local-sdk installer may have changed shape \u2014 re-run the audit checklist in src/cli/voice/foundry/installer/nativeLoader.ts and update accordingly.`)}}var p;function q(){if(p)return p;try{let e=O()("foundry-local-sdk/deps_versions.json");if(typeof e["foundry-local-core"]?.nuget!="string"||typeof e.onnxruntime?.version!="string"||typeof e["onnxruntime-genai"]?.version!="string")throw new Error('deps_versions.json is missing one of the expected version keys: ["foundry-local-core"].nuget, .onnxruntime.version, ["onnxruntime-genai"].version');return p=e,p}catch(e){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${y(e)}. The upstream foundry-local-sdk installer may have changed shape \u2014 re-run the audit checklist in src/cli/voice/foundry/installer/nativeLoader.ts and update accordingly.`)}}function C(e=process.platform){let r=q();return[{name:"Microsoft.AI.Foundry.Local.Core",version:r["foundry-local-core"].nuget},{name:e==="linux"?"Microsoft.ML.OnnxRuntime.Gpu.Linux":"Microsoft.ML.OnnxRuntime.Foundry",version:r.onnxruntime.version},{name:"Microsoft.ML.OnnxRuntimeGenAI.Foundry",version:r["onnxruntime-genai"].version}]}function M(e){return e==="win32"?".dll":e==="darwin"?".dylib":".so"}function G(e,r){return a.join(e,`Microsoft.AI.Foundry.Local.Core${M(r)}`)}function K(e){let r=M(e),t=e==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${r}`,`${t}onnxruntime${r}`,`${t}onnxruntime-genai${r}`]}function Y(e,r=process.platform,t=process.arch){let n=w[`${r}-${t}`];if(!n)throw new Error(`Voice mode not supported on ${r}-${t}`);let o=e??process.env.COPILOT_CACHE_HOME??b(),i=C(r),c=J("sha256").update(JSON.stringify({schema:U,artifacts:i})).digest("hex").slice(0,12);return a.join(o,"foundry",c,n)}async function N(e={}){let r=e.platform??process.platform,t=e.arch??process.arch,n=`${r}-${t}`;if(!w[n])throw new Error(`Voice mode is not supported on ${n}. Supported platforms: ${Object.keys(w).join(", ")}.`);let i=Y(e.cacheRoot,r,t),c=G(i,r),d=K(r);return await _(i,d)||(e.onDownloadStart?.(),await B(i,r,d,e.runInstall)),S(c,i,r,e.existsSyncImpl)}async function _(e,r){return await v(a.join(e,I))?(await Promise.all(r.map(n=>v(a.join(e,n))))).every(Boolean):!1}function S(e,r,t,n=z){if(t!=="win32")return{corePath:e,needsBootstrap:!1};let o=a.join(r,"Microsoft.WindowsAppRuntime.Bootstrap.dll");return{corePath:e,needsBootstrap:n(o)}}function z(e){try{return H(e)}catch{return!1}}async function v(e){try{return await s.access(e),!0}catch{return!1}}async function B(e,r,t,n){let o=a.dirname(e);await s.mkdir(o,{recursive:!0});let i=a.join(o,`.tmp-${a.basename(e)}-${process.pid}-${Date.now()}`);await s.mkdir(i,{recursive:!0});try{let c=n??V().runInstall,d=C(r);await X(()=>c(d,{binDir:i}));for(let P of t)if(!await v(a.join(i,P)))throw new Error(`Foundry runtime download finished but required file is missing: ${P}. RID for ${r} may not be supported by the published packages.`);await s.writeFile(a.join(i,I),""),await Q(i,e,t)}catch(c){throw await s.rm(i,{recursive:!0,force:!0}).catch(()=>{}),c}}async function Q(e,r,t){try{await s.rename(e,r)}catch(n){let o=n.code;if(o==="ENOTEMPTY"||o==="EEXIST"||o==="EPERM"){if(await _(r,t)){await s.rm(e,{recursive:!0,force:!0}).catch(()=>{});return}await s.rm(r,{recursive:!0,force:!0}),await s.rename(e,r);return}throw n}}async function X(e){let r=process.stdout.write.bind(process.stdout),t=process.stderr.write.bind(process.stderr);process.stdout.write=(()=>!0),process.stderr.write=(()=>!0);try{return await e()}finally{process.stdout.write=r,process.stderr.write=t}}var E=class extends Error{constructor(t,n,o){super(t,o);this.code=n;this.name="VoiceBackendError"}};function $(e){return e instanceof E?{message:e.message,code:e.code}:e instanceof Error?{message:e.message}:{message:String(e)}}function R(e){return e instanceof Error?e:new Error(String(e))}var Z=16;function x(e){return F(e,new WeakSet,0)}function F(e,r,t){if(t>=Z)return"<cause chain truncated>";if(typeof e=="object"&&e!==null){if(r.has(e))return"<cyclic cause>";r.add(e)}if(!(e instanceof Error))return String(e);let n=e.stack??`${e.name}: ${e.message}`;if(e.cause===void 0)return n;let o=F(e.cause,r,t+1);return`${n}
Caused by: ${o}`}var k=16*1024,L=class{constructor(r){this.port=r}writeLog(r,t){let n={kind:"log",level:r,message:ee(t)};try{this.port.postMessage(n)}catch{}return Promise.resolve()}outputPath(){return"<voice-worker>"}};function T(e,r=u){r.setLogWriter(new L(e))}function ee(e){return e.length<=k?e:`${e.slice(0,k)}\u2026 [truncated, ${e.length-k} more chars]`}if(!A)throw new Error("voice-installer.worker.js must be loaded as a worker thread.");var g=A;T(g);var te=re??{};async function ne(){try{let r={kind:"ok",location:await N({cacheRoot:te.cacheRoot,onDownloadStart:()=>{let t={kind:"download-started"};g.postMessage(t)}})};g.postMessage(r)}catch(e){let r=R(e);u.error(`[voice-installer worker] install failed: ${x(r)}`);let t={kind:"error",error:$(r)};g.postMessage(t)}finally{setImmediate(()=>process.exit(0))}}ne().catch(e=>{u.error(`[voice-installer worker] fatal: ${x(e)}`),process.exit(1)});
