(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="159e025b-4db2-5f0f-80d3-87d0795b1163",globalThis._sentryDebugIdIdentifier="sentry-dbid-159e025b-4db2-5f0f-80d3-87d0795b1163");})();

/*---------------------------------------------------------------------------------------------
 *  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 __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 __napiOopEntrypoint = __path.join(__appPath, "napi-oop-runtime", "index.js");
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 __napiOopRequire = __fs.existsSync(__napiOopEntrypoint)
    ? __module.createRequire(__napiOopEntrypoint)
    : __rootRequire;
const __isVendoredNativeModule = (module) =>
    typeof module === "string" &&
    (module.startsWith("@teddyzhu/") || module === "foundry-local-sdk" || module === "@picovoice/pvrecorder-node" || module === "napi-oop-runtime");
const require = (module) => {
    let req = __rootRequire;
    if (typeof module === "string" && module.startsWith("@teddyzhu/")) {
        req = __clipboardRequire;
    }
    if (module === "foundry-local-sdk") {
        req = __foundryRequire;
    }
    if (module === "@picovoice/pvrecorder-node") {
        req = __pvRecorderRequire;
    }
    if (module === "napi-oop-runtime") {
        req = __napiOopRequire;
    }

    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 __esmShimFilename = __url.fileURLToPath(import.meta.url);
const __esmShimDirname = __path.dirname(__esmShimFilename);
var hs=Object.create;var Vr=Object.defineProperty;var ms=Object.getOwnPropertyDescriptor;var vs=Object.getOwnPropertyNames;var ys=Object.getPrototypeOf,Es=Object.prototype.hasOwnProperty;var de=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var j=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var Ss=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vs(e))!Es.call(t,i)&&i!==n&&Vr(t,i,{get:()=>e[i],enumerable:!(r=ms(e,i))||r.enumerable});return t};var it=(t,e,n)=>(n=t!=null?hs(ys(t)):{},Ss(e||!t||!t.__esModule?Vr(n,"default",{value:t,enumerable:!0}):n,t));var Hr=j((bd,qr)=>{"use strict";var jr=()=>process.platform==="linux",st=null,ws=()=>{if(!st)if(jr()&&process.report){let t=process.report.excludeNetwork;process.report.excludeNetwork=!0,st=process.report.getReport(),process.report.excludeNetwork=t}else st={};return st};qr.exports={isLinux:jr,getReport:ws}});var Ur=j((Rd,Wr)=>{"use strict";var Me=de("fs"),bs="/usr/bin/ldd",Rs="/proc/self/exe",at=2048,ks=t=>{let e=Me.openSync(t,"r"),n=Buffer.alloc(at),r=Me.readSync(e,n,0,at,0);return Me.close(e,()=>{}),n.subarray(0,r)},Is=t=>new Promise((e,n)=>{Me.open(t,"r",(r,i)=>{if(r)n(r);else{let o=Buffer.alloc(at);Me.read(i,o,0,at,0,(a,d)=>{e(o.subarray(0,d)),Me.close(i,()=>{})})}})});Wr.exports={LDD_PATH:bs,SELF_PATH:Rs,readFileSync:ks,readFile:Is}});var zr=j((kd,Br)=>{"use strict";var _s=t=>{if(t.length<64||t.readUInt32BE(0)!==2135247942||t.readUInt8(4)!==2||t.readUInt8(5)!==1)return null;let e=t.readUInt32LE(32),n=t.readUInt16LE(54),r=t.readUInt16LE(56);for(let i=0;i<r;i++){let o=e+i*n;if(t.readUInt32LE(o)===3){let d=t.readUInt32LE(o+8),u=t.readUInt32LE(o+32);return t.subarray(d,d+u).toString().replace(/\0.*$/g,"")}}return null};Br.exports={interpreterPath:_s}});var ui=j((Id,li)=>{"use strict";var Jr=de("child_process"),{isLinux:xe,getReport:Kr}=Hr(),{LDD_PATH:ct,SELF_PATH:Qr,readFile:nn,readFileSync:rn}=Ur(),{interpreterPath:Yr}=zr(),se,ae,ce,Xr="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",he="",Zr=()=>he||new Promise(t=>{Jr.exec(Xr,(e,n)=>{he=e?" ":n,t(he)})}),ei=()=>{if(!he)try{he=Jr.execSync(Xr,{encoding:"utf8"})}catch{he=" "}return he},le="glibc",ti=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,be="musl",Ps=t=>t.includes("libc.musl-")||t.includes("ld-musl-"),ni=()=>{let t=Kr();return t.header&&t.header.glibcVersionRuntime?le:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(Ps)?be:null},ri=t=>{let[e,n]=t.split(/[\r\n]+/);return e&&e.includes(le)?le:n&&n.includes(be)?be:null},ii=t=>{if(t){if(t.includes("/ld-musl-"))return be;if(t.includes("/ld-linux-"))return le}return null},oi=t=>(t=t.toString(),t.includes("musl")?be:t.includes("GNU C Library")?le:null),Cs=async()=>{if(ae!==void 0)return ae;ae=null;try{let t=await nn(ct);ae=oi(t)}catch{}return ae},Ms=()=>{if(ae!==void 0)return ae;ae=null;try{let t=rn(ct);ae=oi(t)}catch{}return ae},xs=async()=>{if(se!==void 0)return se;se=null;try{let t=await nn(Qr),e=Yr(t);se=ii(e)}catch{}return se},Ts=()=>{if(se!==void 0)return se;se=null;try{let t=rn(Qr),e=Yr(t);se=ii(e)}catch{}return se},si=async()=>{let t=null;if(xe()&&(t=await xs(),!t&&(t=await Cs(),t||(t=ni()),!t))){let e=await Zr();t=ri(e)}return t},ai=()=>{let t=null;if(xe()&&(t=Ts(),!t&&(t=Ms(),t||(t=ni()),!t))){let e=ei();t=ri(e)}return t},Os=async()=>xe()&&await si()!==le,Ns=()=>xe()&&ai()!==le,Ls=async()=>{if(ce!==void 0)return ce;ce=null;try{let e=(await nn(ct)).match(ti);e&&(ce=e[1])}catch{}return ce},Fs=()=>{if(ce!==void 0)return ce;ce=null;try{let e=rn(ct).match(ti);e&&(ce=e[1])}catch{}return ce},ci=()=>{let t=Kr();return t.header&&t.header.glibcVersionRuntime?t.header.glibcVersionRuntime:null},Gr=t=>t.trim().split(/\s+/)[1],di=t=>{let[e,n,r]=t.split(/[\r\n]+/);return e&&e.includes(le)?Gr(e):n&&r&&n.includes(be)?Gr(r):null},As=async()=>{let t=null;if(xe()&&(t=await Ls(),t||(t=ci()),!t)){let e=await Zr();t=di(e)}return t},Ds=()=>{let t=null;if(xe()&&(t=Fs(),t||(t=ci()),!t)){let e=ei();t=di(e)}return t};li.exports={GLIBC:le,MUSL:be,family:si,familySync:ai,isNonGlibcLinux:Os,isNonGlibcLinuxSync:Ns,version:As,versionSync:Ds}});var Oe=j(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.stringArray=z.array=z.func=z.error=z.number=z.string=z.boolean=void 0;function oa(t){return t===!0||t===!1}z.boolean=oa;function Pi(t){return typeof t=="string"||t instanceof String}z.string=Pi;function sa(t){return typeof t=="number"||t instanceof Number}z.number=sa;function aa(t){return t instanceof Error}z.error=aa;function ca(t){return typeof t=="function"}z.func=ca;function Ci(t){return Array.isArray(t)}z.array=Ci;function da(t){return Ci(t)&&t.every(e=>Pi(e))}z.stringArray=da});var xn=j(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.Message=v.NotificationType9=v.NotificationType8=v.NotificationType7=v.NotificationType6=v.NotificationType5=v.NotificationType4=v.NotificationType3=v.NotificationType2=v.NotificationType1=v.NotificationType0=v.NotificationType=v.RequestType9=v.RequestType8=v.RequestType7=v.RequestType6=v.RequestType5=v.RequestType4=v.RequestType3=v.RequestType2=v.RequestType1=v.RequestType=v.RequestType0=v.AbstractMessageSignature=v.ParameterStructures=v.ResponseError=v.ErrorCodes=void 0;var Re=Oe(),sn;(function(t){t.ParseError=-32700,t.InvalidRequest=-32600,t.MethodNotFound=-32601,t.InvalidParams=-32602,t.InternalError=-32603,t.jsonrpcReservedErrorRangeStart=-32099,t.serverErrorStart=-32099,t.MessageWriteError=-32099,t.MessageReadError=-32098,t.PendingResponseRejected=-32097,t.ConnectionInactive=-32096,t.ServerNotInitialized=-32002,t.UnknownErrorCode=-32001,t.jsonrpcReservedErrorRangeEnd=-32e3,t.serverErrorEnd=-32e3})(sn||(v.ErrorCodes=sn={}));var an=class t extends Error{constructor(e,n,r){super(n),this.code=Re.number(e)?e:sn.UnknownErrorCode,this.data=r,Object.setPrototypeOf(this,t.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};v.ResponseError=an;var Y=class t{constructor(e){this.kind=e}static is(e){return e===t.auto||e===t.byName||e===t.byPosition}toString(){return this.kind}};v.ParameterStructures=Y;Y.auto=new Y("auto");Y.byPosition=new Y("byPosition");Y.byName=new Y("byName");var F=class{constructor(e,n){this.method=e,this.numberOfParams=n}get parameterStructures(){return Y.auto}};v.AbstractMessageSignature=F;var cn=class extends F{constructor(e){super(e,0)}};v.RequestType0=cn;var dn=class extends F{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.RequestType=dn;var ln=class extends F{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.RequestType1=ln;var un=class extends F{constructor(e){super(e,2)}};v.RequestType2=un;var pn=class extends F{constructor(e){super(e,3)}};v.RequestType3=pn;var fn=class extends F{constructor(e){super(e,4)}};v.RequestType4=fn;var gn=class extends F{constructor(e){super(e,5)}};v.RequestType5=gn;var hn=class extends F{constructor(e){super(e,6)}};v.RequestType6=hn;var mn=class extends F{constructor(e){super(e,7)}};v.RequestType7=mn;var vn=class extends F{constructor(e){super(e,8)}};v.RequestType8=vn;var yn=class extends F{constructor(e){super(e,9)}};v.RequestType9=yn;var En=class extends F{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.NotificationType=En;var Sn=class extends F{constructor(e){super(e,0)}};v.NotificationType0=Sn;var wn=class extends F{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.NotificationType1=wn;var bn=class extends F{constructor(e){super(e,2)}};v.NotificationType2=bn;var Rn=class extends F{constructor(e){super(e,3)}};v.NotificationType3=Rn;var kn=class extends F{constructor(e){super(e,4)}};v.NotificationType4=kn;var In=class extends F{constructor(e){super(e,5)}};v.NotificationType5=In;var _n=class extends F{constructor(e){super(e,6)}};v.NotificationType6=_n;var Pn=class extends F{constructor(e){super(e,7)}};v.NotificationType7=Pn;var Cn=class extends F{constructor(e){super(e,8)}};v.NotificationType8=Cn;var Mn=class extends F{constructor(e){super(e,9)}};v.NotificationType9=Mn;var Mi;(function(t){function e(i){let o=i;return o&&Re.string(o.method)&&(Re.string(o.id)||Re.number(o.id))}t.isRequest=e;function n(i){let o=i;return o&&Re.string(o.method)&&i.id===void 0}t.isNotification=n;function r(i){let o=i;return o&&(o.result!==void 0||!!o.error)&&(Re.string(o.id)||Re.number(o.id)||o.id===null)}t.isResponse=r})(Mi||(v.Message=Mi={}))});var On=j(me=>{"use strict";var xi;Object.defineProperty(me,"__esModule",{value:!0});me.LRUCache=me.LinkedMap=me.Touch=void 0;var G;(function(t){t.None=0,t.First=1,t.AsOld=t.First,t.Last=2,t.AsNew=t.Last})(G||(me.Touch=G={}));var vt=class{constructor(){this[xi]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,n=G.None){let r=this._map.get(e);if(r)return n!==G.None&&this.touch(r,n),r.value}set(e,n,r=G.None){let i=this._map.get(e);if(i)i.value=n,r!==G.None&&this.touch(i,r);else{switch(i={key:e,value:n,next:void 0,previous:void 0},r){case G.None:this.addItemLast(i);break;case G.First:this.addItemFirst(i);break;case G.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let n=this._map.get(e);if(n)return this._map.delete(e),this.removeItem(n),this._size--,n.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,n){let r=this._state,i=this._head;for(;i;){if(n?e.bind(n)(i.value,i.key,this):e(i.value,i.key,this),this._state!==r)throw new Error("LinkedMap got modified during iteration.");i=i.next}}keys(){let e=this._state,n=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let i={value:n.key,done:!1};return n=n.next,i}else return{value:void 0,done:!0}}};return r}values(){let e=this._state,n=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let i={value:n.value,done:!1};return n=n.next,i}else return{value:void 0,done:!0}}};return r}entries(){let e=this._state,n=this._head,r={[Symbol.iterator]:()=>r,next:()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(n){let i={value:[n.key,n.value],done:!1};return n=n.next,i}else return{value:void 0,done:!0}}};return r}[(xi=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let n=this._head,r=this.size;for(;n&&r>e;)this._map.delete(n.key),n=n.next,r--;this._head=n,this._size=r,n&&(n.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw new Error("Invalid list");this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw new Error("Invalid list");this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{let n=e.next,r=e.previous;if(!n||!r)throw new Error("Invalid list");n.previous=r,r.next=n}e.next=void 0,e.previous=void 0,this._state++}touch(e,n){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(n!==G.First&&n!==G.Last)){if(n===G.First){if(e===this._head)return;let r=e.next,i=e.previous;e===this._tail?(i.next=void 0,this._tail=i):(r.previous=i,i.next=r),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(n===G.Last){if(e===this._tail)return;let r=e.next,i=e.previous;e===this._head?(r.previous=void 0,this._head=r):(r.previous=i,i.next=r),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((n,r)=>{e.push([r,n])}),e}fromJSON(e){this.clear();for(let[n,r]of e)this.set(n,r)}};me.LinkedMap=vt;var Tn=class extends vt{constructor(e,n=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,n),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,n=G.AsNew){return super.get(e,n)}peek(e){return super.get(e,G.None)}set(e,n){return super.set(e,n,G.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};me.LRUCache=Tn});var Oi=j(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.Disposable=void 0;var Ti;(function(t){function e(n){return{dispose:n}}t.create=e})(Ti||(yt.Disposable=Ti={}))});var ve=j(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});var Nn;function Ln(){if(Nn===void 0)throw new Error("No runtime abstraction layer installed");return Nn}(function(t){function e(n){if(n===void 0)throw new Error("No runtime abstraction layer provided");Nn=n}t.install=e})(Ln||(Ln={}));Fn.default=Ln});var Le=j(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Emitter=Ne.Event=void 0;var la=ve(),Ni;(function(t){let e={dispose(){}};t.None=function(){return e}})(Ni||(Ne.Event=Ni={}));var An=class{add(e,n=null,r){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(n),Array.isArray(r)&&r.push({dispose:()=>this.remove(e,n)})}remove(e,n=null){if(!this._callbacks)return;let r=!1;for(let i=0,o=this._callbacks.length;i<o;i++)if(this._callbacks[i]===e)if(this._contexts[i]===n){this._callbacks.splice(i,1),this._contexts.splice(i,1);return}else r=!0;if(r)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...e){if(!this._callbacks)return[];let n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let o=0,a=r.length;o<a;o++)try{n.push(r[o].apply(i[o],e))}catch(d){(0,la.default)().console.error(d)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},Et=class t{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,n,r)=>{this._callbacks||(this._callbacks=new An),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,n);let i={dispose:()=>{this._callbacks&&(this._callbacks.remove(e,n),i.dispose=t._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(r)&&r.push(i),i}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};Ne.Emitter=Et;Et._noop=function(){}});var bt=j(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CancellationTokenSource=Fe.CancellationToken=void 0;var ua=ve(),pa=Oe(),Dn=Le(),St;(function(t){t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Dn.Event.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Dn.Event.None});function e(n){let r=n;return r&&(r===t.None||r===t.Cancelled||pa.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}t.is=e})(St||(Fe.CancellationToken=St={}));var fa=Object.freeze(function(t,e){let n=(0,ua.default)().timer.setTimeout(t.bind(e),0);return{dispose(){n.dispose()}}}),wt=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?fa:(this._emitter||(this._emitter=new Dn.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},$n=class{get token(){return this._token||(this._token=new wt),this._token}cancel(){this._token?this._token.cancel():this._token=St.Cancelled}dispose(){this._token?this._token instanceof wt&&this._token.dispose():this._token=St.None}};Fe.CancellationTokenSource=$n});var Li=j(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.SharedArrayReceiverStrategy=Ae.SharedArraySenderStrategy=void 0;var ga=bt(),ze;(function(t){t.Continue=0,t.Cancelled=1})(ze||(ze={}));var Vn=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let n=new SharedArrayBuffer(4),r=new Int32Array(n,0,1);r[0]=ze.Continue,this.buffers.set(e.id,n),e.$cancellationData=n}async sendCancellation(e,n){let r=this.buffers.get(n);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,ze.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};Ae.SharedArraySenderStrategy=Vn;var jn=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===ze.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},qn=class{constructor(e){this.token=new jn(e)}cancel(){}dispose(){}},Hn=class{constructor(){this.kind="request"}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new ga.CancellationTokenSource:new qn(n)}};Ae.SharedArrayReceiverStrategy=Hn});var Un=j(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.Semaphore=void 0;var ha=ve(),Wn=class{constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((n,r)=>{this._waiting.push({thunk:e,resolve:n,reject:r}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,ha.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let n=e.thunk();n instanceof Promise?n.then(r=>{this._active--,e.resolve(r),this.runNext()},r=>{this._active--,e.reject(r),this.runNext()}):(this._active--,e.resolve(n),this.runNext())}catch(n){this._active--,e.reject(n),this.runNext()}}};Rt.Semaphore=Wn});var Ai=j(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.ReadableStreamMessageReader=ye.AbstractMessageReader=ye.MessageReader=void 0;var zn=ve(),De=Oe(),Bn=Le(),ma=Un(),Fi;(function(t){function e(n){let r=n;return r&&De.func(r.listen)&&De.func(r.dispose)&&De.func(r.onError)&&De.func(r.onClose)&&De.func(r.onPartialMessage)}t.is=e})(Fi||(ye.MessageReader=Fi={}));var kt=class{constructor(){this.errorEmitter=new Bn.Emitter,this.closeEmitter=new Bn.Emitter,this.partialMessageEmitter=new Bn.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${De.string(e.message)?e.message:"unknown"}`)}};ye.AbstractMessageReader=kt;var Gn;(function(t){function e(n){let r,i,o,a=new Map,d,u=new Map;if(n===void 0||typeof n=="string")r=n??"utf-8";else{if(r=n.charset??"utf-8",n.contentDecoder!==void 0&&(o=n.contentDecoder,a.set(o.name,o)),n.contentDecoders!==void 0)for(let p of n.contentDecoders)a.set(p.name,p);if(n.contentTypeDecoder!==void 0&&(d=n.contentTypeDecoder,u.set(d.name,d)),n.contentTypeDecoders!==void 0)for(let p of n.contentTypeDecoders)u.set(p.name,p)}return d===void 0&&(d=(0,zn.default)().applicationJson.decoder,u.set(d.name,d)),{charset:r,contentDecoder:o,contentDecoders:a,contentTypeDecoder:d,contentTypeDecoders:u}}t.fromOptions=e})(Gn||(Gn={}));var Jn=class extends kt{constructor(e,n){super(),this.readable=e,this.options=Gn.fromOptions(n),this.buffer=(0,zn.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new ma.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let n=this.readable.onData(r=>{this.onData(r)});return this.readable.onError(r=>this.fireError(r)),this.readable.onClose(()=>this.fireClose()),n}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let r=this.buffer.tryReadHeaders(!0);if(!r)return;let i=r.get("content-length");if(!i){this.fireError(new Error(`Header must provide a Content-Length property.
${JSON.stringify(Object.fromEntries(r))}`));return}let o=parseInt(i);if(isNaN(o)){this.fireError(new Error(`Content-Length value must be a number. Got ${i}`));return}this.nextMessageLength=o}let n=this.buffer.tryReadBody(this.nextMessageLength);if(n===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let r=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(n):n,i=await this.options.contentTypeDecoder.decode(r,this.options);this.callback(i)}).catch(r=>{this.fireError(r)})}}catch(n){this.fireError(n)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,zn.default)().timer.setTimeout((e,n)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:n}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};ye.ReadableStreamMessageReader=Jn});var qi=j(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.WriteableStreamMessageWriter=Ee.AbstractMessageWriter=Ee.MessageWriter=void 0;var Di=ve(),Ge=Oe(),va=Un(),$i=Le(),ya="Content-Length: ",Vi=`\r
`,ji;(function(t){function e(n){let r=n;return r&&Ge.func(r.dispose)&&Ge.func(r.onClose)&&Ge.func(r.onError)&&Ge.func(r.write)}t.is=e})(ji||(Ee.MessageWriter=ji={}));var It=class{constructor(){this.errorEmitter=new $i.Emitter,this.closeEmitter=new $i.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,n,r){this.errorEmitter.fire([this.asError(e),n,r])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${Ge.string(e.message)?e.message:"unknown"}`)}};Ee.AbstractMessageWriter=It;var Kn;(function(t){function e(n){return n===void 0||typeof n=="string"?{charset:n??"utf-8",contentTypeEncoder:(0,Di.default)().applicationJson.encoder}:{charset:n.charset??"utf-8",contentEncoder:n.contentEncoder,contentTypeEncoder:n.contentTypeEncoder??(0,Di.default)().applicationJson.encoder}}t.fromOptions=e})(Kn||(Kn={}));var Qn=class extends It{constructor(e,n){super(),this.writable=e,this.options=Kn.fromOptions(n),this.errorCount=0,this.writeSemaphore=new va.Semaphore(1),this.writable.onError(r=>this.fireError(r)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(r=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(r):r).then(r=>{let i=[];return i.push(ya,r.byteLength.toString(),Vi),i.push(Vi),this.doWrite(e,i,r)},r=>{throw this.fireError(r),r}))}async doWrite(e,n,r){try{return await this.writable.write(n.join(""),"ascii"),this.writable.write(r)}catch(i){return this.handleError(i,e),Promise.reject(i)}}handleError(e,n){this.errorCount++,this.fireError(e,n,this.errorCount)}end(){this.writable.end()}};Ee.WriteableStreamMessageWriter=Qn});var Hi=j(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.AbstractMessageBuffer=void 0;var Ea=13,Sa=10,wa=`\r
`,Yn=class{constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let n=typeof e=="string"?this.fromString(e,this._encoding):e;this._chunks.push(n),this._totalLength+=n.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let n=0,r=0,i=0,o=0;e:for(;r<this._chunks.length;){let p=this._chunks[r];for(i=0;i<p.length;){switch(p[i]){case Ea:switch(n){case 0:n=1;break;case 2:n=3;break;default:n=0}break;case Sa:switch(n){case 1:n=2;break;case 3:n=4,i++;break e;default:n=0}break;default:n=0}i++}o+=p.byteLength,r++}if(n!==4)return;let a=this._read(o+i),d=new Map,u=this.toString(a,"ascii").split(wa);if(u.length<2)return d;for(let p=0;p<u.length-2;p++){let y=u[p],I=y.indexOf(":");if(I===-1)throw new Error(`Message header must separate key and value using ':'
${y}`);let x=y.substr(0,I),q=y.substr(I+1).trim();d.set(e?x.toLowerCase():x,q)}return d}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(e===0)return this.emptyBuffer();if(e>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){let o=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(o)}if(this._chunks[0].byteLength>e){let o=this._chunks[0],a=this.asNative(o,e);return this._chunks[0]=o.slice(e),this._totalLength-=e,a}let n=this.allocNative(e),r=0,i=0;for(;e>0;){let o=this._chunks[i];if(o.byteLength>e){let a=o.slice(0,e);n.set(a,r),r+=e,this._chunks[i]=o.slice(e),this._totalLength-=e,e-=e}else n.set(o,r),r+=o.byteLength,this._chunks.shift(),this._totalLength-=o.byteLength,e-=o.byteLength}return n}};_t.AbstractMessageBuffer=Yn});var Gi=j(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.createMessageConnection=S.ConnectionOptions=S.MessageStrategy=S.CancellationStrategy=S.CancellationSenderStrategy=S.CancellationReceiverStrategy=S.RequestCancellationReceiverStrategy=S.IdCancellationReceiverStrategy=S.ConnectionStrategy=S.ConnectionError=S.ConnectionErrors=S.LogTraceNotification=S.SetTraceNotification=S.TraceFormat=S.TraceValues=S.Trace=S.NullLogger=S.ProgressType=S.ProgressToken=void 0;var Wi=ve(),D=Oe(),E=xn(),Ui=On(),Je=Le(),Xn=bt(),Ye;(function(t){t.type=new E.NotificationType("$/cancelRequest")})(Ye||(Ye={}));var Zn;(function(t){function e(n){return typeof n=="string"||typeof n=="number"}t.is=e})(Zn||(S.ProgressToken=Zn={}));var Ke;(function(t){t.type=new E.NotificationType("$/progress")})(Ke||(Ke={}));var er=class{constructor(){}};S.ProgressType=er;var tr;(function(t){function e(n){return D.func(n)}t.is=e})(tr||(tr={}));S.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var C;(function(t){t[t.Off=0]="Off",t[t.Messages=1]="Messages",t[t.Compact=2]="Compact",t[t.Verbose=3]="Verbose"})(C||(S.Trace=C={}));var Bi;(function(t){t.Off="off",t.Messages="messages",t.Compact="compact",t.Verbose="verbose"})(Bi||(S.TraceValues=Bi={}));(function(t){function e(r){if(!D.string(r))return t.Off;switch(r=r.toLowerCase(),r){case"off":return t.Off;case"messages":return t.Messages;case"compact":return t.Compact;case"verbose":return t.Verbose;default:return t.Off}}t.fromString=e;function n(r){switch(r){case t.Off:return"off";case t.Messages:return"messages";case t.Compact:return"compact";case t.Verbose:return"verbose";default:return"off"}}t.toString=n})(C||(S.Trace=C={}));var X;(function(t){t.Text="text",t.JSON="json"})(X||(S.TraceFormat=X={}));(function(t){function e(n){return D.string(n)?(n=n.toLowerCase(),n==="json"?t.JSON:t.Text):t.Text}t.fromString=e})(X||(S.TraceFormat=X={}));var nr;(function(t){t.type=new E.NotificationType("$/setTrace")})(nr||(S.SetTraceNotification=nr={}));var Pt;(function(t){t.type=new E.NotificationType("$/logTrace")})(Pt||(S.LogTraceNotification=Pt={}));var Qe;(function(t){t[t.Closed=1]="Closed",t[t.Disposed=2]="Disposed",t[t.AlreadyListening=3]="AlreadyListening"})(Qe||(S.ConnectionErrors=Qe={}));var $e=class t extends Error{constructor(e,n){super(n),this.code=e,Object.setPrototypeOf(this,t.prototype)}};S.ConnectionError=$e;var rr;(function(t){function e(n){let r=n;return r&&D.func(r.cancelUndispatched)}t.is=e})(rr||(S.ConnectionStrategy=rr={}));var Ct;(function(t){function e(n){let r=n;return r&&(r.kind===void 0||r.kind==="id")&&D.func(r.createCancellationTokenSource)&&(r.dispose===void 0||D.func(r.dispose))}t.is=e})(Ct||(S.IdCancellationReceiverStrategy=Ct={}));var ir;(function(t){function e(n){let r=n;return r&&r.kind==="request"&&D.func(r.createCancellationTokenSource)&&(r.dispose===void 0||D.func(r.dispose))}t.is=e})(ir||(S.RequestCancellationReceiverStrategy=ir={}));var Mt;(function(t){t.Message=Object.freeze({createCancellationTokenSource(n){return new Xn.CancellationTokenSource}});function e(n){return Ct.is(n)||ir.is(n)}t.is=e})(Mt||(S.CancellationReceiverStrategy=Mt={}));var xt;(function(t){t.Message=Object.freeze({sendCancellation(n,r){return n.sendNotification(Ye.type,{id:r})},cleanup(n){}});function e(n){let r=n;return r&&D.func(r.sendCancellation)&&D.func(r.cleanup)}t.is=e})(xt||(S.CancellationSenderStrategy=xt={}));var Tt;(function(t){t.Message=Object.freeze({receiver:Mt.Message,sender:xt.Message});function e(n){let r=n;return r&&Mt.is(r.receiver)&&xt.is(r.sender)}t.is=e})(Tt||(S.CancellationStrategy=Tt={}));var Ot;(function(t){function e(n){let r=n;return r&&D.func(r.handleMessage)}t.is=e})(Ot||(S.MessageStrategy=Ot={}));var zi;(function(t){function e(n){let r=n;return r&&(Tt.is(r.cancellationStrategy)||rr.is(r.connectionStrategy)||Ot.is(r.messageStrategy))}t.is=e})(zi||(S.ConnectionOptions=zi={}));var re;(function(t){t[t.New=1]="New",t[t.Listening=2]="Listening",t[t.Closed=3]="Closed",t[t.Disposed=4]="Disposed"})(re||(re={}));function ba(t,e,n,r){let i=n!==void 0?n:S.NullLogger,o=0,a=0,d=0,u="2.0",p,y=new Map,I,x=new Map,q=new Map,_,H=new Ui.LinkedMap,b=new Map,Q=new Set,J=new Map,T=C.Off,we=X.Text,W,pe=re.New,Zt=new Je.Emitter,_r=new Je.Emitter,Pr=new Je.Emitter,Cr=new Je.Emitter,Mr=new Je.Emitter,fe=r&&r.cancellationStrategy?r.cancellationStrategy:Tt.Message;function xr(s){if(s===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+s.toString()}function Qo(s){return s===null?"res-unknown-"+(++d).toString():"res-"+s.toString()}function Yo(){return"not-"+(++a).toString()}function Xo(s,l){E.Message.isRequest(l)?s.set(xr(l.id),l):E.Message.isResponse(l)?s.set(Qo(l.id),l):s.set(Yo(),l)}function Zo(s){}function Tr(){return pe===re.Listening}function Or(){return pe===re.Closed}function _e(){return pe===re.Disposed}function Nr(){(pe===re.New||pe===re.Listening)&&(pe=re.Closed,_r.fire(void 0))}function es(s){Zt.fire([s,void 0,void 0])}function ts(s){Zt.fire(s)}t.onClose(Nr),t.onError(es),e.onClose(Nr),e.onError(ts);function Lr(){_||H.size===0||(_=(0,Wi.default)().timer.setImmediate(()=>{_=void 0,ns()}))}function Fr(s){E.Message.isRequest(s)?is(s):E.Message.isNotification(s)?ss(s):E.Message.isResponse(s)?os(s):as(s)}function ns(){if(H.size===0)return;let s=H.shift();try{let l=r?.messageStrategy;Ot.is(l)?l.handleMessage(s,Fr):Fr(s)}finally{Lr()}}let rs=s=>{try{if(E.Message.isNotification(s)&&s.method===Ye.type.method){let l=s.params.id,f=xr(l),m=H.get(f);if(E.Message.isRequest(m)){let O=r?.connectionStrategy,$=O&&O.cancelUndispatched?O.cancelUndispatched(m,Zo):void 0;if($&&($.error!==void 0||$.result!==void 0)){H.delete(f),J.delete(l),$.id=m.id,rt($,s.method,Date.now()),e.write($).catch(()=>i.error("Sending response for canceled message failed."));return}}let L=J.get(l);if(L!==void 0){L.cancel(),en(s);return}else Q.add(l)}Xo(H,s)}finally{Lr()}};function is(s){if(_e())return;function l(P,A,M){let U={jsonrpc:u,id:s.id};P instanceof E.ResponseError?U.error=P.toJson():U.result=P===void 0?null:P,rt(U,A,M),e.write(U).catch(()=>i.error("Sending response failed."))}function f(P,A,M){let U={jsonrpc:u,id:s.id,error:P.toJson()};rt(U,A,M),e.write(U).catch(()=>i.error("Sending response failed."))}function m(P,A,M){P===void 0&&(P=null);let U={jsonrpc:u,id:s.id,result:P};rt(U,A,M),e.write(U).catch(()=>i.error("Sending response failed."))}ls(s);let L=y.get(s.method),O,$;L&&(O=L.type,$=L.handler);let V=Date.now();if($||p){let P=s.id??String(Date.now()),A=Ct.is(fe.receiver)?fe.receiver.createCancellationTokenSource(P):fe.receiver.createCancellationTokenSource(s);s.id!==null&&Q.has(s.id)&&A.cancel(),s.id!==null&&J.set(P,A);try{let M;if($)if(s.params===void 0){if(O!==void 0&&O.numberOfParams!==0){f(new E.ResponseError(E.ErrorCodes.InvalidParams,`Request ${s.method} defines ${O.numberOfParams} params but received none.`),s.method,V);return}M=$(A.token)}else if(Array.isArray(s.params)){if(O!==void 0&&O.parameterStructures===E.ParameterStructures.byName){f(new E.ResponseError(E.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by name but received parameters by position`),s.method,V);return}M=$(...s.params,A.token)}else{if(O!==void 0&&O.parameterStructures===E.ParameterStructures.byPosition){f(new E.ResponseError(E.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by position but received parameters by name`),s.method,V);return}M=$(s.params,A.token)}else p&&(M=p(s.method,s.params,A.token));let U=M;M?U.then?U.then(K=>{J.delete(P),l(K,s.method,V)},K=>{J.delete(P),K instanceof E.ResponseError?f(K,s.method,V):K&&D.string(K.message)?f(new E.ResponseError(E.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${K.message}`),s.method,V):f(new E.ResponseError(E.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,V)}):(J.delete(P),l(M,s.method,V)):(J.delete(P),m(M,s.method,V))}catch(M){J.delete(P),M instanceof E.ResponseError?l(M,s.method,V):M&&D.string(M.message)?f(new E.ResponseError(E.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${M.message}`),s.method,V):f(new E.ResponseError(E.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,V)}}else f(new E.ResponseError(E.ErrorCodes.MethodNotFound,`Unhandled method ${s.method}`),s.method,V)}function os(s){if(!_e())if(s.id===null)s.error?i.error(`Received response message without id: Error is: 
${JSON.stringify(s.error,void 0,4)}`):i.error("Received response message without id. No further error information provided.");else{let l=s.id,f=b.get(l);if(us(s,f),f!==void 0){b.delete(l);try{if(s.error){let m=s.error;f.reject(new E.ResponseError(m.code,m.message,m.data))}else if(s.result!==void 0)f.resolve(s.result);else throw new Error("Should never happen.")}catch(m){m.message?i.error(`Response handler '${f.method}' failed with message: ${m.message}`):i.error(`Response handler '${f.method}' failed unexpectedly.`)}}}}function ss(s){if(_e())return;let l,f;if(s.method===Ye.type.method){let m=s.params.id;Q.delete(m),en(s);return}else{let m=x.get(s.method);m&&(f=m.handler,l=m.type)}if(f||I)try{if(en(s),f)if(s.params===void 0)l!==void 0&&l.numberOfParams!==0&&l.parameterStructures!==E.ParameterStructures.byName&&i.error(`Notification ${s.method} defines ${l.numberOfParams} params but received none.`),f();else if(Array.isArray(s.params)){let m=s.params;s.method===Ke.type.method&&m.length===2&&Zn.is(m[0])?f({token:m[0],value:m[1]}):(l!==void 0&&(l.parameterStructures===E.ParameterStructures.byName&&i.error(`Notification ${s.method} defines parameters by name but received parameters by position`),l.numberOfParams!==s.params.length&&i.error(`Notification ${s.method} defines ${l.numberOfParams} params but received ${m.length} arguments`)),f(...m))}else l!==void 0&&l.parameterStructures===E.ParameterStructures.byPosition&&i.error(`Notification ${s.method} defines parameters by position but received parameters by name`),f(s.params);else I&&I(s.method,s.params)}catch(m){m.message?i.error(`Notification handler '${s.method}' failed with message: ${m.message}`):i.error(`Notification handler '${s.method}' failed unexpectedly.`)}else Pr.fire(s)}function as(s){if(!s){i.error("Received empty message.");return}i.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(s,null,4)}`);let l=s;if(D.string(l.id)||D.number(l.id)){let f=l.id,m=b.get(f);m&&m.reject(new Error("The received response has neither a result nor an error property."))}}function ge(s){if(s!=null)switch(T){case C.Verbose:return JSON.stringify(s,null,4);case C.Compact:return JSON.stringify(s);default:return}}function cs(s){if(!(T===C.Off||!W))if(we===X.Text){let l;(T===C.Verbose||T===C.Compact)&&s.params&&(l=`Params: ${ge(s.params)}

`),W.log(`Sending request '${s.method} - (${s.id})'.`,l)}else Pe("send-request",s)}function ds(s){if(!(T===C.Off||!W))if(we===X.Text){let l;(T===C.Verbose||T===C.Compact)&&(s.params?l=`Params: ${ge(s.params)}

`:l=`No parameters provided.

`),W.log(`Sending notification '${s.method}'.`,l)}else Pe("send-notification",s)}function rt(s,l,f){if(!(T===C.Off||!W))if(we===X.Text){let m;(T===C.Verbose||T===C.Compact)&&(s.error&&s.error.data?m=`Error data: ${ge(s.error.data)}

`:s.result?m=`Result: ${ge(s.result)}

`:s.error===void 0&&(m=`No result returned.

`)),W.log(`Sending response '${l} - (${s.id})'. Processing request took ${Date.now()-f}ms`,m)}else Pe("send-response",s)}function ls(s){if(!(T===C.Off||!W))if(we===X.Text){let l;(T===C.Verbose||T===C.Compact)&&s.params&&(l=`Params: ${ge(s.params)}

`),W.log(`Received request '${s.method} - (${s.id})'.`,l)}else Pe("receive-request",s)}function en(s){if(!(T===C.Off||!W||s.method===Pt.type.method))if(we===X.Text){let l;(T===C.Verbose||T===C.Compact)&&(s.params?l=`Params: ${ge(s.params)}

`:l=`No parameters provided.

`),W.log(`Received notification '${s.method}'.`,l)}else Pe("receive-notification",s)}function us(s,l){if(!(T===C.Off||!W))if(we===X.Text){let f;if((T===C.Verbose||T===C.Compact)&&(s.error&&s.error.data?f=`Error data: ${ge(s.error.data)}

`:s.result?f=`Result: ${ge(s.result)}

`:s.error===void 0&&(f=`No result returned.

`)),l){let m=s.error?` Request failed: ${s.error.message} (${s.error.code}).`:"";W.log(`Received response '${l.method} - (${s.id})' in ${Date.now()-l.timerStart}ms.${m}`,f)}else W.log(`Received response ${s.id} without active response promise.`,f)}else Pe("receive-response",s)}function Pe(s,l){if(!W||T===C.Off)return;let f={isLSPMessage:!0,type:s,message:l,timestamp:Date.now()};W.log(f)}function We(){if(Or())throw new $e(Qe.Closed,"Connection is closed.");if(_e())throw new $e(Qe.Disposed,"Connection is disposed.")}function ps(){if(Tr())throw new $e(Qe.AlreadyListening,"Connection is already listening")}function fs(){if(!Tr())throw new Error("Call listen() first.")}function Ue(s){return s===void 0?null:s}function Ar(s){if(s!==null)return s}function Dr(s){return s!=null&&!Array.isArray(s)&&typeof s=="object"}function tn(s,l){switch(s){case E.ParameterStructures.auto:return Dr(l)?Ar(l):[Ue(l)];case E.ParameterStructures.byName:if(!Dr(l))throw new Error("Received parameters by name but param is not an object literal.");return Ar(l);case E.ParameterStructures.byPosition:return[Ue(l)];default:throw new Error(`Unknown parameter structure ${s.toString()}`)}}function $r(s,l){let f,m=s.numberOfParams;switch(m){case 0:f=void 0;break;case 1:f=tn(s.parameterStructures,l[0]);break;default:f=[];for(let L=0;L<l.length&&L<m;L++)f.push(Ue(l[L]));if(l.length<m)for(let L=l.length;L<m;L++)f.push(null);break}return f}let Ce={sendNotification:(s,...l)=>{We();let f,m;if(D.string(s)){f=s;let O=l[0],$=0,V=E.ParameterStructures.auto;E.ParameterStructures.is(O)&&($=1,V=O);let P=l.length,A=P-$;switch(A){case 0:m=void 0;break;case 1:m=tn(V,l[$]);break;default:if(V===E.ParameterStructures.byName)throw new Error(`Received ${A} parameters for 'by Name' notification parameter structure.`);m=l.slice($,P).map(M=>Ue(M));break}}else{let O=l;f=s.method,m=$r(s,O)}let L={jsonrpc:u,method:f,params:m};return ds(L),e.write(L).catch(O=>{throw i.error("Sending notification failed."),O})},onNotification:(s,l)=>{We();let f;return D.func(s)?I=s:l&&(D.string(s)?(f=s,x.set(s,{type:void 0,handler:l})):(f=s.method,x.set(s.method,{type:s,handler:l}))),{dispose:()=>{f!==void 0?x.delete(f):I=void 0}}},onProgress:(s,l,f)=>{if(q.has(l))throw new Error(`Progress handler for token ${l} already registered`);return q.set(l,f),{dispose:()=>{q.delete(l)}}},sendProgress:(s,l,f)=>Ce.sendNotification(Ke.type,{token:l,value:f}),onUnhandledProgress:Cr.event,sendRequest:(s,...l)=>{We(),fs();let f,m,L;if(D.string(s)){f=s;let P=l[0],A=l[l.length-1],M=0,U=E.ParameterStructures.auto;E.ParameterStructures.is(P)&&(M=1,U=P);let K=l.length;Xn.CancellationToken.is(A)&&(K=K-1,L=A);let oe=K-M;switch(oe){case 0:m=void 0;break;case 1:m=tn(U,l[M]);break;default:if(U===E.ParameterStructures.byName)throw new Error(`Received ${oe} parameters for 'by Name' request parameter structure.`);m=l.slice(M,K).map(gs=>Ue(gs));break}}else{let P=l;f=s.method,m=$r(s,P);let A=s.numberOfParams;L=Xn.CancellationToken.is(P[A])?P[A]:void 0}let O=o++,$;L&&($=L.onCancellationRequested(()=>{let P=fe.sender.sendCancellation(Ce,O);return P===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${O}`),Promise.resolve()):P.catch(()=>{i.log(`Sending cancellation messages for id ${O} failed`)})}));let V={jsonrpc:u,id:O,method:f,params:m};return cs(V),typeof fe.sender.enableCancellation=="function"&&fe.sender.enableCancellation(V),new Promise(async(P,A)=>{let M=oe=>{P(oe),fe.sender.cleanup(O),$?.dispose()},U=oe=>{A(oe),fe.sender.cleanup(O),$?.dispose()},K={method:f,timerStart:Date.now(),resolve:M,reject:U};try{b.set(O,K),await e.write(V)}catch(oe){throw b.delete(O),K.reject(new E.ResponseError(E.ErrorCodes.MessageWriteError,oe.message?oe.message:"Unknown reason")),i.error("Sending request failed."),oe}})},onRequest:(s,l)=>{We();let f=null;return tr.is(s)?(f=void 0,p=s):D.string(s)?(f=null,l!==void 0&&(f=s,y.set(s,{handler:l,type:void 0}))):l!==void 0&&(f=s.method,y.set(s.method,{type:s,handler:l})),{dispose:()=>{f!==null&&(f!==void 0?y.delete(f):p=void 0)}}},hasPendingResponse:()=>b.size>0,trace:async(s,l,f)=>{let m=!1,L=X.Text;f!==void 0&&(D.boolean(f)?m=f:(m=f.sendNotification||!1,L=f.traceFormat||X.Text)),T=s,we=L,T===C.Off?W=void 0:W=l,m&&!Or()&&!_e()&&await Ce.sendNotification(nr.type,{value:C.toString(s)})},onError:Zt.event,onClose:_r.event,onUnhandledNotification:Pr.event,onDispose:Mr.event,end:()=>{e.end()},dispose:()=>{if(_e())return;pe=re.Disposed,Mr.fire(void 0);let s=new E.ResponseError(E.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let l of b.values())l.reject(s);b=new Map,J=new Map,Q=new Set,H=new Ui.LinkedMap,D.func(e.dispose)&&e.dispose(),D.func(t.dispose)&&t.dispose()},listen:()=>{We(),ps(),pe=re.Listening,t.listen(rs)},inspect:()=>{(0,Wi.default)().console.log("inspect")}};return Ce.onNotification(Pt.type,s=>{if(T===C.Off||!W)return;let l=T===C.Verbose||T===C.Compact;W.log(s.message,l?s.verbose:void 0)}),Ce.onNotification(Ke.type,s=>{let l=q.get(s.token);l?l(s.value):Cr.fire(s)}),Ce}S.createMessageConnection=ba});var Nt=j(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.ProgressType=c.ProgressToken=c.createMessageConnection=c.NullLogger=c.ConnectionOptions=c.ConnectionStrategy=c.AbstractMessageBuffer=c.WriteableStreamMessageWriter=c.AbstractMessageWriter=c.MessageWriter=c.ReadableStreamMessageReader=c.AbstractMessageReader=c.MessageReader=c.SharedArrayReceiverStrategy=c.SharedArraySenderStrategy=c.CancellationToken=c.CancellationTokenSource=c.Emitter=c.Event=c.Disposable=c.LRUCache=c.Touch=c.LinkedMap=c.ParameterStructures=c.NotificationType9=c.NotificationType8=c.NotificationType7=c.NotificationType6=c.NotificationType5=c.NotificationType4=c.NotificationType3=c.NotificationType2=c.NotificationType1=c.NotificationType0=c.NotificationType=c.ErrorCodes=c.ResponseError=c.RequestType9=c.RequestType8=c.RequestType7=c.RequestType6=c.RequestType5=c.RequestType4=c.RequestType3=c.RequestType2=c.RequestType1=c.RequestType0=c.RequestType=c.Message=c.RAL=void 0;c.MessageStrategy=c.CancellationStrategy=c.CancellationSenderStrategy=c.CancellationReceiverStrategy=c.ConnectionError=c.ConnectionErrors=c.LogTraceNotification=c.SetTraceNotification=c.TraceFormat=c.TraceValues=c.Trace=void 0;var N=xn();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return N.Message}});Object.defineProperty(c,"RequestType",{enumerable:!0,get:function(){return N.RequestType}});Object.defineProperty(c,"RequestType0",{enumerable:!0,get:function(){return N.RequestType0}});Object.defineProperty(c,"RequestType1",{enumerable:!0,get:function(){return N.RequestType1}});Object.defineProperty(c,"RequestType2",{enumerable:!0,get:function(){return N.RequestType2}});Object.defineProperty(c,"RequestType3",{enumerable:!0,get:function(){return N.RequestType3}});Object.defineProperty(c,"RequestType4",{enumerable:!0,get:function(){return N.RequestType4}});Object.defineProperty(c,"RequestType5",{enumerable:!0,get:function(){return N.RequestType5}});Object.defineProperty(c,"RequestType6",{enumerable:!0,get:function(){return N.RequestType6}});Object.defineProperty(c,"RequestType7",{enumerable:!0,get:function(){return N.RequestType7}});Object.defineProperty(c,"RequestType8",{enumerable:!0,get:function(){return N.RequestType8}});Object.defineProperty(c,"RequestType9",{enumerable:!0,get:function(){return N.RequestType9}});Object.defineProperty(c,"ResponseError",{enumerable:!0,get:function(){return N.ResponseError}});Object.defineProperty(c,"ErrorCodes",{enumerable:!0,get:function(){return N.ErrorCodes}});Object.defineProperty(c,"NotificationType",{enumerable:!0,get:function(){return N.NotificationType}});Object.defineProperty(c,"NotificationType0",{enumerable:!0,get:function(){return N.NotificationType0}});Object.defineProperty(c,"NotificationType1",{enumerable:!0,get:function(){return N.NotificationType1}});Object.defineProperty(c,"NotificationType2",{enumerable:!0,get:function(){return N.NotificationType2}});Object.defineProperty(c,"NotificationType3",{enumerable:!0,get:function(){return N.NotificationType3}});Object.defineProperty(c,"NotificationType4",{enumerable:!0,get:function(){return N.NotificationType4}});Object.defineProperty(c,"NotificationType5",{enumerable:!0,get:function(){return N.NotificationType5}});Object.defineProperty(c,"NotificationType6",{enumerable:!0,get:function(){return N.NotificationType6}});Object.defineProperty(c,"NotificationType7",{enumerable:!0,get:function(){return N.NotificationType7}});Object.defineProperty(c,"NotificationType8",{enumerable:!0,get:function(){return N.NotificationType8}});Object.defineProperty(c,"NotificationType9",{enumerable:!0,get:function(){return N.NotificationType9}});Object.defineProperty(c,"ParameterStructures",{enumerable:!0,get:function(){return N.ParameterStructures}});var or=On();Object.defineProperty(c,"LinkedMap",{enumerable:!0,get:function(){return or.LinkedMap}});Object.defineProperty(c,"LRUCache",{enumerable:!0,get:function(){return or.LRUCache}});Object.defineProperty(c,"Touch",{enumerable:!0,get:function(){return or.Touch}});var Ra=Oi();Object.defineProperty(c,"Disposable",{enumerable:!0,get:function(){return Ra.Disposable}});var Ji=Le();Object.defineProperty(c,"Event",{enumerable:!0,get:function(){return Ji.Event}});Object.defineProperty(c,"Emitter",{enumerable:!0,get:function(){return Ji.Emitter}});var Ki=bt();Object.defineProperty(c,"CancellationTokenSource",{enumerable:!0,get:function(){return Ki.CancellationTokenSource}});Object.defineProperty(c,"CancellationToken",{enumerable:!0,get:function(){return Ki.CancellationToken}});var Qi=Li();Object.defineProperty(c,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return Qi.SharedArraySenderStrategy}});Object.defineProperty(c,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return Qi.SharedArrayReceiverStrategy}});var sr=Ai();Object.defineProperty(c,"MessageReader",{enumerable:!0,get:function(){return sr.MessageReader}});Object.defineProperty(c,"AbstractMessageReader",{enumerable:!0,get:function(){return sr.AbstractMessageReader}});Object.defineProperty(c,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return sr.ReadableStreamMessageReader}});var ar=qi();Object.defineProperty(c,"MessageWriter",{enumerable:!0,get:function(){return ar.MessageWriter}});Object.defineProperty(c,"AbstractMessageWriter",{enumerable:!0,get:function(){return ar.AbstractMessageWriter}});Object.defineProperty(c,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return ar.WriteableStreamMessageWriter}});var ka=Hi();Object.defineProperty(c,"AbstractMessageBuffer",{enumerable:!0,get:function(){return ka.AbstractMessageBuffer}});var B=Gi();Object.defineProperty(c,"ConnectionStrategy",{enumerable:!0,get:function(){return B.ConnectionStrategy}});Object.defineProperty(c,"ConnectionOptions",{enumerable:!0,get:function(){return B.ConnectionOptions}});Object.defineProperty(c,"NullLogger",{enumerable:!0,get:function(){return B.NullLogger}});Object.defineProperty(c,"createMessageConnection",{enumerable:!0,get:function(){return B.createMessageConnection}});Object.defineProperty(c,"ProgressToken",{enumerable:!0,get:function(){return B.ProgressToken}});Object.defineProperty(c,"ProgressType",{enumerable:!0,get:function(){return B.ProgressType}});Object.defineProperty(c,"Trace",{enumerable:!0,get:function(){return B.Trace}});Object.defineProperty(c,"TraceValues",{enumerable:!0,get:function(){return B.TraceValues}});Object.defineProperty(c,"TraceFormat",{enumerable:!0,get:function(){return B.TraceFormat}});Object.defineProperty(c,"SetTraceNotification",{enumerable:!0,get:function(){return B.SetTraceNotification}});Object.defineProperty(c,"LogTraceNotification",{enumerable:!0,get:function(){return B.LogTraceNotification}});Object.defineProperty(c,"ConnectionErrors",{enumerable:!0,get:function(){return B.ConnectionErrors}});Object.defineProperty(c,"ConnectionError",{enumerable:!0,get:function(){return B.ConnectionError}});Object.defineProperty(c,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return B.CancellationReceiverStrategy}});Object.defineProperty(c,"CancellationSenderStrategy",{enumerable:!0,get:function(){return B.CancellationSenderStrategy}});Object.defineProperty(c,"CancellationStrategy",{enumerable:!0,get:function(){return B.CancellationStrategy}});Object.defineProperty(c,"MessageStrategy",{enumerable:!0,get:function(){return B.MessageStrategy}});var Ia=ve();c.RAL=Ia.default});var Zi=j(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});var Yi=de("util"),ue=Nt(),Lt=class t extends ue.AbstractMessageBuffer{constructor(e="utf-8"){super(e)}emptyBuffer(){return t.emptyBuffer}fromString(e,n){return Buffer.from(e,n)}toString(e,n){return e instanceof Buffer?e.toString(n):new Yi.TextDecoder(n).decode(e)}asNative(e,n){return n===void 0?e instanceof Buffer?e:Buffer.from(e):e instanceof Buffer?e.slice(0,n):Buffer.from(e,0,n)}allocNative(e){return Buffer.allocUnsafe(e)}};Lt.emptyBuffer=Buffer.allocUnsafe(0);var cr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ue.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ue.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ue.Disposable.create(()=>this.stream.off("end",e))}onData(e){return this.stream.on("data",e),ue.Disposable.create(()=>this.stream.off("data",e))}},dr=class{constructor(e){this.stream=e}onClose(e){return this.stream.on("close",e),ue.Disposable.create(()=>this.stream.off("close",e))}onError(e){return this.stream.on("error",e),ue.Disposable.create(()=>this.stream.off("error",e))}onEnd(e){return this.stream.on("end",e),ue.Disposable.create(()=>this.stream.off("end",e))}write(e,n){return new Promise((r,i)=>{let o=a=>{a==null?r():i(a)};typeof e=="string"?this.stream.write(e,n,o):this.stream.write(e,o)})}end(){this.stream.end()}},Xi=Object.freeze({messageBuffer:Object.freeze({create:t=>new Lt(t)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(t,e)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(t,void 0,0),e.charset))}catch(n){return Promise.reject(n)}}}),decoder:Object.freeze({name:"application/json",decode:(t,e)=>{try{return t instanceof Buffer?Promise.resolve(JSON.parse(t.toString(e.charset))):Promise.resolve(JSON.parse(new Yi.TextDecoder(e.charset).decode(t)))}catch(n){return Promise.reject(n)}}})}),stream:Object.freeze({asReadableStream:t=>new cr(t),asWritableStream:t=>new dr(t)}),console,timer:Object.freeze({setTimeout(t,e,...n){let r=setTimeout(t,e,...n);return{dispose:()=>clearTimeout(r)}},setImmediate(t,...e){let n=setImmediate(t,...e);return{dispose:()=>clearImmediate(n)}},setInterval(t,e,...n){let r=setInterval(t,e,...n);return{dispose:()=>clearInterval(r)}}})});function lr(){return Xi}(function(t){function e(){ue.RAL.install(Xi)}t.install=e})(lr||(lr={}));ur.default=lr});var no=j(k=>{"use strict";var _a=k&&k.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Pa=k&&k.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_a(e,t,n)};Object.defineProperty(k,"__esModule",{value:!0});k.createMessageConnection=k.createServerSocketTransport=k.createClientSocketTransport=k.createServerPipeTransport=k.createClientPipeTransport=k.generateRandomPipeName=k.StreamMessageWriter=k.StreamMessageReader=k.SocketMessageWriter=k.SocketMessageReader=k.PortMessageWriter=k.PortMessageReader=k.IPCMessageWriter=k.IPCMessageReader=void 0;var Ve=Zi();Ve.default.install();var eo=de("path"),Ca=de("os"),Ma=de("crypto"),Dt=de("net"),Z=Nt();Pa(Nt(),k);var pr=class extends Z.AbstractMessageReader{constructor(e){super(),this.process=e;let n=this.process;n.on("error",r=>this.fireError(r)),n.on("close",()=>this.fireClose())}listen(e){return this.process.on("message",e),Z.Disposable.create(()=>this.process.off("message",e))}};k.IPCMessageReader=pr;var fr=class extends Z.AbstractMessageWriter{constructor(e){super(),this.process=e,this.errorCount=0;let n=this.process;n.on("error",r=>this.fireError(r)),n.on("close",()=>this.fireClose)}write(e){try{return typeof this.process.send=="function"&&this.process.send(e,void 0,void 0,n=>{n?(this.errorCount++,this.handleError(n,e)):this.errorCount=0}),Promise.resolve()}catch(n){return this.handleError(n,e),Promise.reject(n)}}handleError(e,n){this.errorCount++,this.fireError(e,n,this.errorCount)}end(){}};k.IPCMessageWriter=fr;var gr=class extends Z.AbstractMessageReader{constructor(e){super(),this.onData=new Z.Emitter,e.on("close",()=>this.fireClose),e.on("error",n=>this.fireError(n)),e.on("message",n=>{this.onData.fire(n)})}listen(e){return this.onData.event(e)}};k.PortMessageReader=gr;var hr=class extends Z.AbstractMessageWriter{constructor(e){super(),this.port=e,this.errorCount=0,e.on("close",()=>this.fireClose()),e.on("error",n=>this.fireError(n))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(n){return this.handleError(n,e),Promise.reject(n)}}handleError(e,n){this.errorCount++,this.fireError(e,n,this.errorCount)}end(){}};k.PortMessageWriter=hr;var ke=class extends Z.ReadableStreamMessageReader{constructor(e,n="utf-8"){super((0,Ve.default)().stream.asReadableStream(e),n)}};k.SocketMessageReader=ke;var Ie=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};k.SocketMessageWriter=Ie;var Ft=class extends Z.ReadableStreamMessageReader{constructor(e,n){super((0,Ve.default)().stream.asReadableStream(e),n)}};k.StreamMessageReader=Ft;var At=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n)}};k.StreamMessageWriter=At;var to=process.env.XDG_RUNTIME_DIR,xa=new Map([["linux",107],["darwin",103]]);function Ta(){let t=(0,Ma.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${t}-sock`;let e;to?e=eo.join(to,`vscode-ipc-${t}.sock`):e=eo.join(Ca.tmpdir(),`vscode-${t}.sock`);let n=xa.get(process.platform);return n!==void 0&&e.length>n&&(0,Ve.default)().console.warn(`WARNING: IPC handle "${e}" is longer than ${n} characters.`),e}k.generateRandomPipeName=Ta;function Oa(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,Dt.createServer)(d=>{a.close(),n([new ke(d,e),new Ie(d,e)])});a.on("error",o),a.listen(t,()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}k.createClientPipeTransport=Oa;function Na(t,e="utf-8"){let n=(0,Dt.createConnection)(t);return[new ke(n,e),new Ie(n,e)]}k.createServerPipeTransport=Na;function La(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,Dt.createServer)(d=>{a.close(),n([new ke(d,e),new Ie(d,e)])});a.on("error",o),a.listen(t,"127.0.0.1",()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}k.createClientSocketTransport=La;function Fa(t,e="utf-8"){let n=(0,Dt.createConnection)(t,"127.0.0.1");return[new ke(n,e),new Ie(n,e)]}k.createServerSocketTransport=Fa;function Aa(t){let e=t;return e.read!==void 0&&e.addListener!==void 0}function Da(t){let e=t;return e.write!==void 0&&e.addListener!==void 0}function $a(t,e,n,r){n||(n=Z.NullLogger);let i=Aa(t)?new Ft(t):t,o=Da(e)?new At(e):e;return Z.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,Z.createMessageConnection)(i,o,n,r)}k.createMessageConnection=$a});var $t=j((Nl,ro)=>{"use strict";ro.exports=no()});import{join as vd}from"node:path";import*as pt from"os";import on from"node:path";import{fileURLToPath as Qs}from"node:url";var ot=class{initialQueue=[];initialQueueResolvers=Promise.withResolvers();logWriter=null;writePromise=this.initialQueueResolvers.promise;setLogWriter(e){this.logWriter=e;for(let n of this.initialQueue)this.writePromise=this.logWriter.writeLog(n.method,n.message);this.initialQueue=[],this.initialQueueResolvers.resolve()}async flush(){this.logWriter&&await this.writePromise}async dispose(){await this.flush()}outputPath(){return this.logWriter?.outputPath()}logToLevel(e,n){this.logWriter?this.writePromise=this.logWriter.writeLog(e,n):this.initialQueue.push({method:e,message:n})}info(e){this.logToLevel("info",e)}debug(e){this.logToLevel("debug",e)}warning(e){this.logToLevel("warning",e)}error(e){this.logToLevel("error",e instanceof Error?e.message:e)}log(e){this.error(e)}isDebug(){return!1}shouldLog(e){return!0}notice(e){this.info(e instanceof Error?e.message:e)}startGroup(e,n){this.info(`--- Start of group: ${e} ---`)}endGroup(e){this.info("--- End of group ---")}},h=new ot;import{createRequire as $s}from"node:module";import{platform as Vs,type as js}from"node:os";import{join as fi,resolve as qs}from"node:path";import{fileURLToPath as Hs}from"node:url";var dt=it(ui(),1);function lt(t={}){return(t.platform??process.platform)!=="linux"?"gnu":t.detectLibcFamily?t.detectLibcFamily()==="musl"?"musl":"gnu":(0,dt.familySync)()===dt.MUSL?"musl":"gnu"}function pi(t=process.platform,e){let n=e??(t==="linux"?lt():"gnu");return t==="linux"&&n==="musl"?"linuxmusl":t}function Ws(){let t=hi(),e=t==="linux"?lt({platform:t}):"gnu";return`${pi(t,e)}-${process.arch}`}function Us(){let t=hi(),{arch:e}=process;switch(t){case"win32":return`win32-${e}-msvc`;case"darwin":return`darwin-${e}`;case"linux":return`linux-${e}-${lt({platform:t})}`;default:throw new Error(`Unsupported platform: ${t}/${e}`)}}var ee;function hi(){if(ee!==void 0)return ee;switch(js()){case"Windows_NT":ee="win32";break;case"Darwin":ee="darwin";break;case"Linux":ee="linux";break;case"AIX":ee="aix";break;case"FreeBSD":case"DragonFly":ee="freebsd";break;case"OpenBSD":ee="openbsd";break;case"NetBSD":ee="netbsd";break;case"SunOS":ee="sunos";break;default:ee=Vs();break}return ee}function mi(t,e){let n=Ws(),r=`${t}.node`,i=`${t}.${Us()}.node`,o=[];for(let d of e){let u=qs(d),p=fi(u,"prebuilds",n,r),y=gi(p);if(y.ok)return y.value;o.push({path:p,err:y.err});let I=fi(u,i),x=gi(I);if(x.ok)return x.value;o.push({path:I,err:x.err})}let a=o.map(d=>`  ${d.path}: ${Bs(d.err)}`).join(`
`);throw new Error(`Native addon "${t}" not found for ${n}. Tried:
${a}`)}function Bs(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return Object.prototype.toString.call(t)}}function gi(t){try{return{ok:!0,value:zs(t)}}catch(e){return{ok:!1,err:e}}}function zs(t){return $s(Hs(import.meta.url))(t)}import{createRequire as Gs}from"node:module";function Js(){return typeof __napiOopRequire<"u"&&__napiOopRequire||Gs(import.meta.url)}var ut="COPILOT_RUNTIME_OOP";function vi(){return process.env[ut]==="1"||process.env[ut]==="true"}function Ks(t,e){let n=new Set((t.classes??[]).map(i=>i.name)),r={};for(let i of t.classes??[]){let o=i.methods.find(u=>u.js_name==="constructor"),a=o?o.rust_name:`${i.name}.constructor`,d=class{__provider;__handle;constructor(...u){let p=u[u.length-1],y=u.slice(0,u.length-1);this.__provider=p,this.__handle=p.call(a,y),p.trackExternal(this.__handle)}};Object.defineProperty(d,"name",{value:i.name}),d.__fromHandle=function(u,p){let y=Object.create(d.prototype);return y.__provider=u,y.__handle=p,u.trackExternal(p),y};for(let u of i.methods){if(u.js_name==="constructor")continue;let p=n.has(u.ret),y=u.rust_name,I=(x,q)=>p?e[u.ret].__fromHandle(x.__provider,q):q;if(u.is_getter){Object.defineProperty(d.prototype,u.js_name,{configurable:!0,get(){return u.is_async?(async()=>I(this,await this.__provider.callAsync(y,[this.__handle])))():I(this,this.__provider.call(y,[this.__handle]))}});continue}d.prototype[u.js_name]=u.is_async?async function(...x){return I(this,await this.__provider.callAsync(y,[this.__handle,...x]))}:function(...x){return I(this,this.__provider.call(y,[this.__handle,...x]))}}r[i.name]=d,e[i.name]=d}return r}function yi(){let{bindClasses:t,connectFromEnvSync:e,createSyncBinding:n,SOCKET_ENV:r}=Js()("napi-oop-runtime");if(!process.env[r])throw new Error(`${ut} is set but ${r} is not; the out-of-process runtime must be launched by the Rust provider parent, which exports the connect-back socket.`);let i=e();if(delete process.env[ut],!i.manifest)throw new Error("out-of-process provider did not advertise a surface manifest in its handshake");let o=JSON.parse(i.manifest),a=new Set((o.classes??[]).map(b=>b.name)),d=o.functions.filter(b=>b.is_async).map(b=>b.js_name),u=o.functions.filter(b=>b.ret==="ExternalObject").map(b=>b.js_name),p={};for(let b of o.functions)p[b.js_name]=b.rust_name;let y=n(i,d,u,p),I={},x=Ks(o,I),q={};for(let b of o.functions)a.has(b.ret)&&(q[b.js_name]={cls:I[b.ret],isAsync:b.is_async,rustName:b.rust_name});let _=t(y,i,x,q),H=new Map((o.constants??[]).map(b=>[b.js_name,b.value]));return H.size===0?_:new Proxy(_,{get(b,Q,J){return typeof Q=="string"&&H.has(Q)?H.get(Q):Reflect.get(b,Q,J)},has(b,Q){return typeof Q=="string"&&H.has(Q)?!0:Reflect.has(b,Q)}})}var Ei="__copilotRuntimeAddon__";function Ys(){let t=globalThis,e=t[Ei];return e||(e={addon:null},t[Ei]=e),e}function Si(){let t=Ys();if(t.addon)return t.addon;if(vi()){h.debug("[runtimeBridge] out-of-process mode: skipping the in-process runtime .node; all native calls are remoted to the Rust provider");let r=yi();return t.addon=r,r}h.debug("[runtimeBridge] in-process mode: loading the native runtime .node addon into this process");let e=on.dirname(Qs(import.meta.url)),n=mi("runtime",[e,on.resolve(e,".."),on.resolve(e,"..","..","native","runtime")]);return t.addon=n,n}var Xs;function Te(){return Xs??=Si()}var wi="\0__copilot_git_structured_error__\0";function Zs(t){if(!(t instanceof Error)||!t.message.startsWith(wi))return t;let e;try{e=JSON.parse(t.message.slice(wi.length))}catch{return t}let n=new Error(typeof e.message=="string"?e.message:"");typeof e.name=="string"&&(n.name=e.name);for(let[r,i]of Object.entries(e))r==="message"||r==="name"||(n[r]=i);return n}function ea(t,e){let n=Reflect.get(t,e);if(typeof n=="function"&&typeof e=="string"&&/^git[A-Z]/.test(e)){let r=n;return(...i)=>{let o=r.apply(t,i);return o instanceof Promise?o.catch(a=>{throw Zs(a)}):o}}return n}var R=new Proxy({},{get:(t,e)=>ea(Te(),e),has:(t,e)=>Reflect.has(Te(),e),set:(t,e,n)=>Reflect.set(Te(),e,n),ownKeys:()=>Reflect.ownKeys(Te()),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(Te(),e),defineProperty:(t,e,n)=>Reflect.defineProperty(Te(),e,n)});function bi(t,e){return R.resolveCopilotHome(t?.configDir??null,process.env.COPILOT_HOME??null,pt.homedir())}var Bd=pt.tmpdir();function ft(t){let e=[],n=!1,r=()=>{n||(e.push(...t()),n=!0)};return new Proxy(e,{get(i,o,a){r();let d=Reflect.get(i,o,a);return typeof d!="function"?d:(...u)=>Reflect.apply(d,i,u)},set(i,o,a,d){return r(),Reflect.set(i,o,a,d)},has(i,o){return r(),Reflect.has(i,o)},deleteProperty(i,o){return r(),Reflect.deleteProperty(i,o)},defineProperty(i,o,a){return r(),Reflect.defineProperty(i,o,a)},getOwnPropertyDescriptor(i,o){return r(),Reflect.getOwnPropertyDescriptor(i,o)},ownKeys(i){return r(),Reflect.ownKeys(i)}})}var Ri=ft(()=>R.settingsSecretEnvVarNames()),Qd=ft(()=>R.settingsEnvVarNamesToFilterFromShellsAndMcp()),Yd=ft(()=>R.settingsEnvVarNamesToFilterFromShellsOnly()),Xd=ft(()=>R.settingsOtelEnvVarPrefixesToFilterFromShells());function ta(t){return JSON.stringify(t,(e,n)=>{switch(typeof n){case"bigint":return n.toString();case"function":case"symbol":return;default:return n}})??"null"}function ki(t,e=[]){let n=R.settingsGetSecretValues(ta(t));if(!n.ok)throw new Error(n.errorMessage??"Failed to get settings secret values");return e.push(...JSON.parse(n.json)),e}function Be(t){return R.environmentNonEmptyValue(process.env[t])??void 0}var na=["GITHUB_COPILOT_OIDC_","GITHUB_AGENTIC_APP_OIDC_"];var Ii=new FinalizationRegistry(t=>{try{R.secretFilterDispose(t)}catch{}}),gt=class t{static singleton;static getInstance(){return t.singleton||(t.singleton=new t),t.singleton}static __resetForTests(){t.singleton?.dispose(),t.singleton=void 0}handle;finalizerToken={};disposed=!1;runner;logger;settings;additionalSecretEnvVarNames=new Set;sourceSecretsDirty=!0;constructor(){this.handle=R.secretFilterCreate(),Ii.register(this,this.handle,this.finalizerToken)}get nativeHandle(){return this.ensureSourceSecretsSynced(),this.handle}setRunner(e){this.runner=e,this.logger=e.logger,this.sourceSecretsDirty=!0}applySettings(e){this.settings=e,this.sourceSecretsDirty=!0}addSecretEnvVarNames(e){for(let n of e)this.additionalSecretEnvVarNames.add(n);this.sourceSecretsDirty=!0}isAdditionalSecretValue(e){return this.disposed?!1:R.secretFilterIsAdditionalSecretValue(this.handle,e)}getAdditionalSecretValues(){return new Set(this.disposed?[]:R.secretFilterGetAdditionalSecretValues(this.handle))}getRawAdditionalSecretValues(){return new Set(this.disposed?[]:R.secretFilterGetRawAdditionalSecretValues(this.handle))}addSecretValues(e){let n=this.disposed?0:R.secretFilterAddSecretValues(this.handle,e);this.logger?.debug(`[filter]: registered ${n} new filterable value(s) (${e.length} provided, total tracked: ${this.getRawAdditionalSecretValues().size})`)}filterSecrets(e){let n=typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"message"),r=n?e.message??e.toString():e;this.ensureSourceSecretsSynced();let i=this.disposed?{value:r,changed:!1}:R.secretFilterFilter(this.handle,r,[]);return this.logger&&i.changed&&this.logger.debug(`[filter]: filtered content (original length=${r.length}, filtered length=${i.value.length})`),n?(e.message=i.value,e):i.value}filterSecretsFromJsonString(e){return this.ensureSourceSecretsSynced(),this.disposed?e:R.secretFilterFilterJsonString(this.handle,e,[])}filterSecretsFromJsonSerializable(e){if(e==null)return e;let n=JSON.stringify(e);return n===void 0?e:JSON.parse(this.filterSecretsFromJsonString(n))}syncSourceSecretsToNative(){this.ensureSourceSecretsSynced()}getSourceSecretValuesSnapshot(){return[...new Set([...this.getSourceSecretValues(),...this.getRawAdditionalSecretValues()])]}filterSecretsFromObj(e){if(e==null)return e;if(typeof e=="string")return this.filterSecrets(e);if(typeof e=="number"){let n=this.filterSecrets(e.toString()),r=Number(n);return isNaN(r)?n:r}if(Array.isArray(e))return e.map(n=>this.filterSecretsFromObj(n));if(typeof e=="object"){if(e instanceof Date||e instanceof RegExp)return e;let n={};for(let[r,i]of Object.entries(e))n[r]=this.filterSecretsFromObj(i);return n}return e}dispose(){this.disposed||(this.disposed=!0,Ii.unregister(this.finalizerToken),R.secretFilterDispose(this.handle),t.singleton===this&&(t.singleton=void 0))}invalidateSourceSecrets(){this.sourceSecretsDirty=!0}ensureSourceSecretsSynced(){this.disposed||!this.sourceSecretsDirty||(R.secretFilterSetSourceSecretValues(this.handle,this.getSourceSecretValues()),this.sourceSecretsDirty=!1)}getSourceSecretValues(){let e=new Set;for(let n of Ri){let r=Be(n);r&&e.add(r)}for(let n of this.additionalSecretEnvVarNames){let r=Be(n);r&&e.add(r)}for(let n of ra()){let r=Be(n);r&&e.add(r)}if(this.runner)for(let n of this.runner.sensitiveKeys){let r=Be(n);r&&e.add(r)}if(this.settings){let n=ki(this.settings);for(let r of n)e.add(r)}return[...e]}};function ra(){let t=[];for(let e of Object.keys(process.env))na.some(n=>e.startsWith(n))&&t.push(e);return t}function ia(...t){return R.runnerIsDebugEnvironment(t)}var ht=class{logLevel;debugEnvironmentVariables;secretFilter=gt.getInstance();constructor(e,n){this.logLevel=R.runnerResolveLogLevel(e,n??[]),this.debugEnvironmentVariables=n}filterSecrets(e){return typeof e=="string"?this.secretFilter.filterSecrets(e):this.secretFilter.filterSecrets(e)}shouldLog(e){return R.runnerShouldLog(this.logLevel??3,e)}isDebug(){return ia(...this.debugEnvironmentVariables??[])}};var _i=new FinalizationRegistry(t=>{R.runnerFileLoggerDispose(t).catch(()=>{})}),mt=class extends ht{handle;constructor(e,n,r){super(n,r),this.handle=R.runnerFileLoggerCreate(e,n,r??[]),_i.register(this,this.handle,this)}async dispose(){_i.unregister(this),await R.runnerFileLoggerDispose(this.handle)}get writeQueue(){return R.runnerFileLoggerFlush(this.handle)}outputPath(){return R.runnerFileLoggerOutputPath(this.handle)}shouldLog(e){return R.runnerFileLoggerShouldLog(this.handle,e)}isDebug(){return R.runnerFileLoggerIsDebug(this.handle)}log(e){this.logNative("log",e)}debug(e){this.logNative("debug",e)}info(e){this.logNative("info",e)}notice(e){this.logNative("notice",e)}warning(e){this.logNative("warning",e)}error(e){this.logNative("error",e)}startGroup(e,n){this.logNative("startGroup",e,n)}endGroup(e){this.logNative("endGroup","",e)}get stats(){return R.runnerFileLoggerStats(this.handle)}write(e,n){R.runnerFileLoggerWrite(this.handle,e,n)}writeLog(e,n){return this.logNative(e,n),this.writeQueue}logNative(e,n,r){R.runnerFileLoggerLog(this.handle,e,String(this.filterSecrets(n)),r)}};var oo=it($t(),1);var io=["setEnabled","selectModel","selectAudioDevice","listAudioDevices","downloadModel","cancelDownload","deleteModel","installRuntime","refreshCatalog","openSession","finishSession","acknowledgeOperationError"];function ja(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{},type:`rpc:${t}`,connectionId:n,requestId:r}}var Vt=class{connectionId;connection;submit;pending=new Map;closeHandlers=new Set;closeDisposable;disposeDisposable;nextRequestId=1;attached=!1;disposed=!1;constructor(e){this.connection=e.connection,this.connectionId=e.connectionId,this.submit=e.submit;for(let n of io)this.connection.onRequest(n,r=>this.dispatchRpc(n,r));this.closeDisposable=this.connection.onClose(()=>this.handleClose()),this.disposeDisposable=this.connection.onDispose(()=>this.handleClose())}getConnection(){return this.connection}attach(){this.attached||this.disposed||(this.attached=!0,this.connection.listen())}dispose(){if(this.disposed)return;this.disposed=!0,this.closeDisposable.dispose(),this.disposeDisposable.dispose();try{this.connection.dispose()}catch{}this.rejectAllPending(new Error("Engine connection disposed."));let e=[...this.closeHandlers];this.closeHandlers.clear();for(let n of e)n()}send(e){if(this.disposed)return;let{type:n,...r}=e;this.connection.sendNotification(n,r).catch(()=>{})}resolveRpc(e,n){if(this.disposed)return;let r=this.pending.get(e);r&&(this.pending.delete(e),r.resolve(n))}rejectRpc(e,n){if(this.disposed)return;let r=this.pending.get(e);r&&(this.pending.delete(e),r.reject(new oo.ResponseError(1,`Engine RPC rejected: ${n.code}`,{reason:n})))}onClose(e){return this.closeHandlers.add(e),()=>{this.closeHandlers.delete(e)}}dispatchRpc(e,n){if(this.disposed)return Promise.reject(new Error("Engine connection disposed."));let r=this.nextRequestId++;return new Promise((i,o)=>{this.pending.set(r,{resolve:i,reject:o});try{this.submit(ja(e,n,this.connectionId,r))}catch(a){this.pending.delete(r),o(a)}})}handleClose(){this.disposed||this.dispose()}rejectAllPending(e){if(this.pending.size===0)return;let n=[...this.pending.values()];this.pending.clear();for(let r of n)r.reject(e)}};var jt=class{peers=new Map;connectedHandlers=new Set;disconnectedHandlers=new Set;submit=null;nextAutoConnectionId=1;disposed=!1;setSubmit(e){this.submit=e}registerConnection(e){if(this.disposed)throw new Error("EngineRpcHost is disposed.");if(!this.submit)throw new Error("EngineRpcHost.registerConnection called before setSubmit.");let n=e.connectionId??this.generateConnectionId();if(this.peers.has(n))throw new Error(`EngineRpcHost: connection id "${n}" already registered.`);let r=new Vt({connection:e.connection,connectionId:n,submit:this.submit});this.peers.set(n,r),r.onClose(()=>{if(this.peers.get(n)===r){this.peers.delete(n);for(let i of this.disconnectedHandlers)i(n)}});try{r.attach();for(let i of this.connectedHandlers)i(n)}catch(i){this.peers.delete(n);try{r.dispose()}catch{}throw i}return r}get connectionCount(){return this.peers.size}dispose(){if(this.disposed)return;this.disposed=!0;let e=[...this.peers.values()];for(let n of e)try{n.dispose()}catch{}}broadcast(e){if(!this.disposed)for(let n of this.peers.values())n.send(e)}sendTo(e,n){this.disposed||this.peers.get(e)?.send(n)}resolveRpc(e,n,r){this.disposed||this.peers.get(e)?.resolveRpc(n,r)}rejectRpc(e,n,r){this.disposed||this.peers.get(e)?.rejectRpc(n,r)}onClientConnected(e){return this.connectedHandlers.add(e),()=>{this.connectedHandlers.delete(e)}}onClientDisconnected(e){return this.disconnectedHandlers.add(e),()=>{this.disconnectedHandlers.delete(e)}}generateConnectionId(){return`c${this.nextAutoConnectionId++}`}};function qa(t){if(t.includes("<!DOCTYPE")||t.includes("<html")){let e=Math.min(t.indexOf("<!DOCTYPE")!==-1?t.indexOf("<!DOCTYPE"):1/0,t.indexOf("<html")!==-1?t.indexOf("<html"):1/0),n=t.substring(0,e).trim();return n?`${n} [HTML error page omitted]`:"[HTML error page omitted]"}return t}function w(t){let e;if(t instanceof Error)e=String(t);else if(typeof t=="object"&&t!==null)try{e=JSON.stringify(t)??"[object]"}catch{return"[object with circular reference]"}else e=String(t);return qa(e)}var je=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="VoiceBackendError"}code};function mr(t){return t.code!==void 0?new je(t.message,t.code):new Error(t.message)}function qt(t){return t instanceof Error?t:new Error(String(t))}async function so(t,e){try{return await t()}catch(n){if((e?.platform??process.platform)!=="win32")throw n;let i=w(n);if(!/Failed to load (?:dependency|core) library/i.test(i))throw n;let a=(e?.arch??process.arch)==="arm64"?"https://aka.ms/vs/17/release/vc_redist.arm64.exe":"https://aka.ms/vs/17/release/vc_redist.x64.exe";throw new je(`Voice mode requires the Microsoft Visual C++ Redistributable (2015-2022). Download and install it, then try again: ${a}`,"windows-runtime-missing",{cause:n})}}var vr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};function Xe(t,e,n){let r,i=new Promise((o,a)=>{r=setTimeout(()=>a(new vr(n)),e)});return Promise.race([t,i]).finally(()=>{r&&clearTimeout(r)})}var ao="nemotron-3.5-asr-streaming-0.6b",co=new Set([ao,"nemotron-speech-streaming-en-0.6b","nemotron-speech-streaming-es-0.6b"]);function lo(t){return t.find(e=>e.inCatalog&&e.alias===ao)}var Ha="github-copilot-cli",Wa="automatic-speech-recognition",Ua={AzureCatalogFilter:"'',test"},uo=1e4,po=2e3,Ht=class{events;installer;managerFactory;liveSessionFactory;nativeLocation;managerPromise;downloads=new Map;loaded=null;sessions=new Map;outstandingTeardowns=new Set;disposed=!1;constructor(e){this.events=e.events,this.installer=e.installer,this.managerFactory=e.managerFactory,this.liveSessionFactory=e.liveSessionFactory}checkRuntime(e){this.runCheckRuntime(e)}async runCheckRuntime(e){try{if(this.managerFactory){this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"});return}let n=await this.installer.inspect();n.kind==="downloaded"?(this.nativeLocation=n.location,this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"installed"})):n.kind==="update-available"?this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"update-available"}):this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}catch(n){h.error(`[voice-engine] checkRuntime failed: ${w(n)}`),this.events.submit({type:"internal:runtimeChecked",generation:e,cacheState:"not-downloaded"})}}fetchCatalog(e){this.runFetchCatalog(e)}async runFetchCatalog(e){try{let r=await(await this.getManager()).catalog.getModels(),i=[];for(let o of r)for(let a of o.variants)Ba(a)&&co.has(a.alias)&&i.push(Ga(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(n){let r=w(n);h.error(`[voice-engine] fetchCatalog failed: ${r}`),this.events.submit({type:"internal:catalogFetchFailed",generation:e,reason:r})}}installRuntime(e){this.runInstallRuntime(e)}async runInstallRuntime(e){try{let n=await this.installer.install();this.nativeLocation=n,this.events.submit({type:"internal:runtimeInstalled",generation:e})}catch(n){let r=w(n);h.error(`[voice-engine] installRuntime failed: ${r}`),this.events.submit({type:"internal:runtimeInstallFailed",generation:e,reason:r})}}downloadModel(e,n){let r=this.downloads.get(e);if(r&&!r.abortController.signal.aborted){r.generations.add(n);return}let i=new Set([n]),o=new AbortController,a={promise:Promise.resolve(),generations:i,abortController:o};a.promise=this.runDownload(e,i,o.signal),this.downloads.set(e,a)}cancelDownload(e){let n=this.downloads.get(e);n&&n.abortController.abort()}async runDownload(e,n,r){try{await(await this.getVariant(e)).download(o=>{for(let a of n)try{this.events.submit({type:"internal:modelDownloadProgress",generation:a,variantId:e,percent:o})}catch(d){h.warning(`[voice-engine] download progress callback threw: ${w(d)}`)}},r);for(let o of n)this.events.submit({type:"internal:modelDownloaded",generation:o,variantId:e})}catch(i){if(r.aborted)for(let o of n)this.events.submit({type:"internal:modelDownloadCancelled",generation:o,variantId:e});else{let o=w(i);h.error(`[voice-engine] downloadModel '${e}' failed: ${o}`);for(let a of n)this.events.submit({type:"internal:modelDownloadFailed",generation:a,variantId:e,reason:o})}}finally{this.downloads.get(e)?.abortController.signal===r&&this.downloads.delete(e)}}loadModel(e,n){this.runLoad(e,n)}async runLoad(e,n){try{let r=await this.getVariant(e);if(!r.isCached)throw new Error(`Voice model '${e}' is not downloaded.`);await r.load(),this.loaded&&this.loaded.variantId!==e&&h.warning(`[voice-engine] loadModel: replacing loaded model '${this.loaded.variantId}' with '${e}' (reducer should have unloaded first)`),this.loaded={variantId:e,variant:r},this.events.submit({type:"internal:modelLoaded",generation:n,variantId:e})}catch(r){let i=w(r);h.error(`[voice-engine] loadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelLoadFailed",generation:n,variantId:e,reason:i})}}unloadModel(e){this.runUnload(e)}async runUnload(e){let n=this.loaded&&this.loaded.variantId===e?this.loaded:null;if(n&&(this.loaded=null),!n){this.events.submit({type:"internal:modelUnloaded",variantId:e});return}try{await n.variant.unload(),this.events.submit({type:"internal:modelUnloaded",variantId:e})}catch(r){let i=w(r);h.error(`[voice-engine] unloadModel '${e}' failed: ${i}`),this.events.submit({type:"internal:modelUnloadFailed",variantId:e,reason:i}),this.events.submit({type:"internal:modelUnloaded",variantId:e})}}deleteModel(e){this.runDelete(e)}async openSttSession(e,n){if(this.disposed)return{ok:!1,subreason:"session-open-failed"};if(this.sessions.has(e))return h.warning(`[voice-engine] openSttSession(${e}): sessionId already in use`),{ok:!1,subreason:"session-open-failed"};let r=this.loaded&&this.loaded.variantId===n?this.loaded:void 0;if(!r)return{ok:!1,subreason:"model-unavailable"};let i={phase:"opening",cancelled:!1};this.sessions.set(e,i);let o=this.runOpenSession(e,r,i);return this.trackTeardown(o.then(()=>{}).catch(()=>{})),o}async runOpenSession(e,n,r){let i;try{i=await this.openStreamingSession(e,n.variant)}catch(a){return h.error(`[voice-engine] openSttSession(${e}) failed: ${w(a)}`),this.sessions.get(e)===r&&this.sessions.delete(e),{ok:!1,subreason:r.cancelled?"cancelled":"session-open-failed"}}let o=this.sessions.get(e);return o!==r||r.cancelled?(o===r&&this.sessions.delete(e),this.trackTeardown(this.teardownSession(i).catch(a=>h.warning(`[voice-engine] orphan teardown(${e}) failed: ${w(a)}`))),{ok:!1,subreason:"cancelled"}):(this.sessions.set(e,{phase:"active",session:i}),i.drainTask=this.runStreamingDrain(i),{ok:!0})}appendSttPcm(e,n){if(this.disposed)return;let r=this.sessions.get(e);if(!r||r.phase!=="active")return;let i=r.session;if(!i.error)try{let o=i.sdk.append(n);o instanceof Promise&&o.catch(a=>this.failSession(i,"drain-failed",a))}catch(o){this.failSession(i,"drain-failed",o)}}endSttSession(e){if(this.disposed)return;let n=this.sessions.get(e);if(!n)return;if(n.phase==="opening"){n.cancelled=!0,this.sessions.delete(e);return}let r=n.session;this.sessions.delete(e),this.trackTeardown(this.runEnd(r))}async runEnd(e){let n=e.sessionId;try{if(e.error){this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}let r;try{r=await this.stopStreaming(e)}catch(i){h.error(`[voice-engine] runEnd(${n}) failed: ${w(i)}`),this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}if(e.error){this.events.submit({type:"internal:sttError",sessionId:n,subreason:"drain-failed"});return}this.events.submit({type:"internal:sttFinal",sessionId:n,text:r})}finally{await this.teardownSession(e).catch(r=>h.warning(`[voice-engine] teardown(${n}) failed: ${w(r)}`))}}cancelSttSession(e){if(this.disposed)return;let n=this.sessions.get(e);if(!n)return;if(n.phase==="opening"){n.cancelled=!0,this.sessions.delete(e);return}let r=n.session;r.cancelled=!0,this.sessions.delete(e),this.trackTeardown(this.runCancel(r))}async runCancel(e){try{await this.disposeSdk(e.sdk)}catch(n){h.warning(`[voice-engine] runCancel(${e.sessionId}) teardown: ${w(n)}`)}}trackTeardown(e){this.outstandingTeardowns.add(e),e.finally(()=>this.outstandingTeardowns.delete(e)).catch(()=>{})}failSession(e,n,r){if(e.error)return;let i=r instanceof Error?r:new Error(String(r));e.error=i,h.error(`[voice-engine] session(${e.sessionId}) failed: ${w(i)}`);let o=this.sessions.get(e.sessionId);!o||o.phase!=="active"||o.session!==e||(this.sessions.delete(e.sessionId),this.events.submit({type:"internal:sttError",sessionId:e.sessionId,subreason:n}),this.trackTeardown(this.teardownSession(e).catch(a=>h.warning(`[voice-engine] failSession teardown: ${w(a)}`))))}async openStreamingSession(e,n){let r=this.liveSessionFactory?await this.liveSessionFactory(n):n.createAudioClient().createLiveTranscriptionSession();r.settings.language="auto";try{await r.start()}catch(i){throw await this.disposeSdk(r),i}return{sessionId:e,committed:"",tail:"",sdk:r,drainTask:Promise.resolve(),cancelled:!1}}async runStreamingDrain(e){try{for await(let n of e.sdk.getStream()){if(e.cancelled||e.error)break;let r=za(n);r&&(n.is_final?(e.committed+=r,e.tail=""):e.tail+=r,this.events.onSttPartial(e.sessionId,e.committed+e.tail))}}catch(n){this.failSession(e,"drain-failed",n)}}async stopStreaming(e){return await Xe(e.sdk.stop(),uo,"Streaming session stop timed out."),await Xe(e.drainTask,uo,"Streaming session drain timed out."),e.committed+e.tail}async teardownSession(e){await this.disposeSdk(e.sdk)}async disposeSdk(e){await Xe(e.dispose(),po,"SDK dispose timed out.").catch(()=>{})}async dispose(){if(!this.disposed){this.disposed=!0;for(let[e,n]of this.sessions)if(n.phase==="opening")n.cancelled=!0,this.sessions.delete(e);else{let r=n.session;r.cancelled=!0,this.sessions.delete(e),this.trackTeardown(this.runCancel(r))}for(;this.outstandingTeardowns.size>0;)await Promise.allSettled([...this.outstandingTeardowns]);if(this.loaded){let e=this.loaded;this.loaded=null,await Xe(e.variant.unload(),po,"variant.unload timed out").catch(n=>{h.error(`[voice-engine] dispose: variant.unload failed: ${w(n)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(n){h.error(`[voice-engine] deleteModel '${e}' failed: ${w(n)}`)}}async getVariant(e){return(await this.getManager()).catalog.getModelVariant(e)}getManager(){return this.managerPromise||(this.managerPromise=this.initManager().catch(e=>{throw this.managerPromise=void 0,e})),this.managerPromise}async initManager(){if(this.managerFactory)return this.managerFactory();if(!this.nativeLocation)throw new Error("LocalFoundryEngineAdapter: manager-backed operation before checkRuntime/installRuntime");let e=this.nativeLocation;return so(async()=>de("foundry-local-sdk").FoundryLocalManager.createAsync({appName:Ha,libraryPath:e.corePath,additionalSettings:{...Ua}}))}};function Ba(t){return t.info.task===Wa}function za(t){return t.content?.[0]?.text??""}function Ga(t){let e=t.info,n=t.info.runtime?.deviceType??e.device,r=n?n.toLowerCase():void 0,i=e.sizeInBytes??(typeof t.info.fileSizeMb=="number"?Math.round(t.info.fileSizeMb*1024*1024):void 0);return{variantId:t.id,displayName:t.info.name??t.id,alias:t.alias,sizeBytes:i,device:r,cached:t.isCached,inCatalog:!0}}var mo=1600,vo=15,Ze=-1,fo=150,Wt=class{events;pvRecorderLoader;state={tag:"idle"};disposed=!1;constructor(e){this.events=e.events,this.pvRecorderLoader=e.pvRecorderLoader??(async()=>de("@picovoice/pvrecorder-node"))}openForSession(e,n){if(this.disposed)return Promise.resolve({ok:!1,subreason:"cancelled"});let r=this.state;switch(r.tag){case"idle":return this.beginStart(e,n,void 0);case"stopping":return this.beginStart(e,n,r.teardown);case"starting":case"active":return h.error(`[voice-mic] openForSession(${e}) while ${r.tag} for session ${r.sessionId} \u2014 engine contract violation`),Promise.resolve({ok:!1,subreason:"in-use"});default:return r}}beginStart(e,n,r){let i,o=new Promise(u=>{i=u}),a={stopped:!1,commitDrain:!1,resolveOpen:i},d=(async()=>{r&&await r.catch(()=>{}),await this.runStart(e,n,a)})();return this.state={tag:"starting",sessionId:e,device:n,cancel:a,startTask:d},o}closeSession(e){let n=this.state;switch(n.tag){case"idle":case"stopping":return n.tag==="stopping"?n.teardown:Promise.resolve();case"starting":{n.cancel.stopped=!0,n.cancel.resolveOpen({ok:!1,subreason:"cancelled"});let r=n.startTask.then(()=>{},()=>{});return this.state={tag:"stopping",teardown:r},r.then(()=>{this.state.tag==="stopping"&&this.state.teardown===r&&(this.state={tag:"idle"})},()=>{}),r}case"active":{let r=n.cancel,i=n.recorder,o=n.loop;e==="discard"?(r.stopped=!0,te(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([o,ho(fo)]).catch(()=>{}),r.stopped=!0,te(()=>i.stop())),await Promise.race([o,ho(fo)]).catch(()=>{}),te(()=>i.release())})();return this.state={tag:"stopping",teardown:a},a.then(()=>{this.state.tag==="stopping"&&this.state.teardown===a&&(this.state={tag:"idle"})},()=>{}),a}default:return n}}async dispose(){if(this.disposed)return;this.disposed=!0;let e=this.state;switch(e.tag){case"idle":return;case"starting":{e.cancel.stopped=!0,e.cancel.resolveOpen({ok:!1,subreason:"cancelled"}),await e.startTask.catch(()=>{}),this.state={tag:"idle"};return}case"active":{e.cancel.stopped=!0,te(()=>e.recorder.stop()),await e.loop.catch(()=>{}),te(()=>e.recorder.release()),this.state={tag:"idle"};return}case"stopping":{await e.teardown.catch(()=>{}),this.state={tag:"idle"};return}default:return e}}async listDevices(){if(this.disposed)return{ok:!1,reason:"unavailable"};if(this.state.tag==="stopping"&&await this.state.teardown.catch(()=>{}),this.disposed||this.state.tag!=="idle")return{ok:!1,reason:"unavailable"};let e;try{e=await this.pvRecorderLoader()}catch(r){return h.warning(`[voice-mic] listDevices: pvrecorder-node load failed: ${w(r)}`),{ok:!1,reason:"unavailable"}}if(this.disposed||this.state.tag!=="idle")return{ok:!1,reason:"unavailable"};let n;try{n=e.PvRecorder.getAvailableDevices()}catch(r){return h.warning(`[voice-mic] getAvailableDevices failed: ${w(r)}`),{ok:!1,reason:"unavailable"}}return n.length===0?{ok:!0,devices:n,defaultDevice:null}:{ok:!0,devices:n,defaultDevice:Ka(e)}}async runStart(e,n,r){if(r.stopped||this.disposed){this.exitCancelled(r);return}let i;try{i=await this.pvRecorderLoader()}catch(p){h.error(`[voice-mic] pvrecorder-node load failed: ${w(p)}`),this.failOpen(r,"hardware-error");return}if(r.stopped||this.disposed){this.exitCancelled(r);return}let o=Ja(i,n);n!==null&&o.deviceId===Ze&&h.warning(`[voice-mic] requested device "${n?.name}" (#${n?.occurrence}) unavailable; using system default`);let d;try{d=new i.PvRecorder(mo,o.deviceId,vo),d.start()}catch(p){if(d!==void 0){let y=d;te(()=>y.stop()),te(()=>y.release())}this.failOpen(r,go(p));return}if(r.stopped||this.disposed){te(()=>d.stop()),te(()=>d.release()),this.exitCancelled(r);return}let u=this.runReadLoop(d,e,r);this.state={tag:"active",sessionId:e,device:n,cancel:r,recorder:d,loop:u},r.resolveOpen({ok:!0})}failOpen(e,n){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:n})}exitCancelled(e){this.state.tag==="starting"&&this.state.cancel===e&&(this.state={tag:"idle"}),e.resolveOpen({ok:!1,subreason:"cancelled"})}async runReadLoop(e,n,r){for(;!r.stopped;){let i;try{i=await e.read()}catch(a){if(r.stopped||r.commitDrain)return;r.stopped=!0,this.state.tag==="active"&&this.state.cancel===r&&(this.state={tag:"idle"}),te(()=>e.stop()),te(()=>e.release());let d=go(a);h.error(`[voice-mic] read loop failed (${d}): ${w(a)}`),this.disposed||this.events.submit({type:"internal:micError",sessionId:n,subreason:d});return}if(r.stopped)return;let o=new Uint8Array(i.byteLength);if(o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),this.events.onPcmFrame(n,o),r.commitDrain)return}}};function Ja(t,e){if(e===null)return{deviceId:Ze};let n;try{n=t.PvRecorder.getAvailableDevices()}catch{return{deviceId:Ze}}let r=0;for(let i=0;i<n.length;i++)if(n[i]===e.name){if(r===e.occurrence)return{deviceId:i};r++}return{deviceId:Ze}}function Ka(t){let e;try{return e=new t.PvRecorder(mo,Ze,vo),e.getSelectedDevice()}catch(n){return h.warning(`[voice-mic] default-device probe failed: ${w(n)}`),null}finally{if(e!==void 0){let n=e;te(()=>n.release())}}}function go(t){switch(t?.constructor?.name??""){case"PvRecorderStatusDeviceAlreadyInitializedError":case"PvRecorderStatusBackendError":return"in-use";case"PvRecorderStatusInvalidArgumentError":return"no-device";case"PvRecorderStatusIOError":case"PvRecorderStatusRuntimeError":return"hardware-error";default:return"hardware-error"}}function ho(t){return new Promise(e=>setTimeout(e,t))}function te(t){try{t()}catch{}}function Qa(t){return{state:t.state,enabled:t.enabled,selectedTarget:t.selectedTarget,models:t.models.map(e=>({...e})),catalogStatus:t.catalogStatus,inFlightDownloads:t.inFlightDownloads.map(e=>({...e})),session:t.session?{...t.session}:null,lastOperationError:t.lastOperationError?{...t.lastOperationError}:null,selectedDevice:t.selectedDevice?{...t.selectedDevice}:null}}function Ya(t){return{generations:{runtimeInstall:t.generations.runtimeInstall,runtimeCheck:t.generations.runtimeCheck,downloadByVariant:new Map(t.generations.downloadByVariant),catalogFetch:t.generations.catalogFetch},nextLoadGeneration:t.nextLoadGeneration,modelLoad:{...t.modelLoad},currentSession:t.currentSession?{...t.currentSession}:null,clientEnabled:t.clientEnabled,pendingDelete:t.pendingDelete?{...t.pendingDelete}:null}}function Ut(t,e){t.enabled=e.clientEnabled}function qe(t,e){return t.models.find(n=>n.variantId===e)}function yo(t,e){let n=qe(t,e);return!!n&&(n.inCatalog||n.cached)}function Eo(t,e){let n=qe(t,e);return!!n&&n.cached}function et(t){return t.currentSession!==null}function Xa(t,e){t.session=e.currentSession?{id:e.currentSession.id,status:e.currentSession.status}:null}function yr(t,e){let r=(t.generations.downloadByVariant.get(e)??0)+1;return t.generations.downloadByVariant.set(e,r),r}function Bt(t,e){return t.generations.downloadByVariant.get(e)??0}function Za(t,e,n){t.pendingFinishReply&&(n.push({type:"replyResolve",connectionId:t.pendingFinishReply.connectionId,requestId:t.pendingFinishReply.requestId,result:e}),t.pendingFinishReply=void 0)}function ie(t,e,n,r){let i=e.currentSession;i&&(r.push({type:"cancelSession",sessionId:i.id}),Za(i,n,r),e.currentSession=null,t.session=null)}function ec(t,e,n){let r=t.state.kind;if(r!=="no-model"&&r!=="downloading"&&r!=="loading"&&r!=="ready")return;if(r==="no-model"&&t.selectedTarget===null&&t.catalogStatus==="ok"){let u=lo(t.models);u?.cached&&(t.selectedTarget=u.variantId)}let i=t.selectedTarget,o=t.enabled&&i!==null&&yo(t,i)?i:null,a=e.modelLoad;if(a.kind==="loading"||a.kind==="unloading")return;if(o===null){a.kind==="loaded"&&(n.push({type:"unloadModel",variantId:a.variantId}),e.modelLoad={kind:"unloading",variantId:a.variantId});return}if(a.kind==="loaded"){if(a.variantId===o){(t.state.kind!=="ready"||t.state.variantId!==o)&&(t.state={kind:"ready",variantId:o});return}n.push({type:"unloadModel",variantId:a.variantId}),e.modelLoad={kind:"unloading",variantId:a.variantId};return}if(Eo(t,o)){let u=++e.nextLoadGeneration;e.modelLoad={kind:"loading",variantId:o,generation:u},t.state={kind:"loading",variantId:o},n.push({type:"loadModel",variantId:o,generation:u});return}if((t.state.kind!=="downloading"||t.state.variantId!==o)&&(t.state={kind:"downloading",variantId:o}),!t.inFlightDownloads.some(u=>u.variantId===o)){let u=yr(e,o);t.inFlightDownloads.push({variantId:o}),n.push({type:"downloadModel",variantId:o,generation:u})}}function So(t){return t.kind==="starting"||t.kind==="runtime-missing"||t.kind==="installing-runtime"||t.kind==="fetching-catalog"||t.kind==="failed"}function wo(t,e,n){let r=Qa(t),i=Ya(e),a=tc(r,i,n,[]);return ec(a.snapshot,a.internal,a.effects),Xa(a.snapshot,a.internal),a}function tc(t,e,n,r){switch(n.type){case"boot":return nc(t,e,n,r);case"shutdown":return rc(t,e,r);case"rpc:setEnabled":return ic(t,e,n,r);case"rpc:selectModel":return oc(t,e,n,r);case"rpc:selectAudioDevice":return sc(t,e,n,r);case"rpc:listAudioDevices":return ac(t,e,n,r);case"rpc:downloadModel":return cc(t,e,n,r);case"rpc:cancelDownload":return dc(t,e,n,r);case"rpc:deleteModel":return lc(t,e,n,r);case"rpc:installRuntime":return uc(t,e,n,r);case"rpc:refreshCatalog":return pc(t,e,n,r);case"rpc:openSession":return fc(t,e,n,r);case"rpc:finishSession":return gc(t,e,n,r);case"rpc:acknowledgeOperationError":return hc(t,e,n,r);case"internal:catalogFetched":return mc(t,e,n,r);case"internal:catalogFetchFailed":return vc(t,e,n,r);case"internal:runtimeChecked":return yc(t,e,n,r);case"internal:runtimeInstalled":return Ec(t,e,n,r);case"internal:runtimeInstallFailed":return Sc(t,e,n,r);case"internal:modelDownloadProgress":return wc(t,e,n,r);case"internal:modelDownloaded":return bc(t,e,n,r);case"internal:modelDownloadCancelled":return Rc(t,e,n,r);case"internal:modelDownloadFailed":return kc(t,e,n,r);case"internal:modelLoaded":return Ic(t,e,n,r);case"internal:modelLoadFailed":return _c(t,e,n,r);case"internal:modelUnloaded":return Pc(t,e,n,r);case"internal:modelUnloadFailed":return Cc(t,e,n,r);case"internal:micError":return Oc(t,e,n,r);case"internal:sessionWarmed":return Mc(t,e,n,r);case"internal:sessionWarmupFailed":return xc(t,e,n,r);case"internal:sttFinal":return Nc(t,e,n,r);case"internal:sttError":return Lc(t,e,n,r);case"client:disconnected":return Fc(t,e,n,r)}}function g(t,e,n){return{snapshot:t,internal:e,effects:n}}function nc(t,e,n,r){e.clientEnabled=n.bootEnabled,Ut(t,e),t.selectedTarget=n.bootSelectedModel,t.selectedDevice=n.bootSelectedDevice,t.state={kind:"starting"};let i=++e.generations.runtimeCheck;return r.push({type:"checkRuntime",generation:i}),g(t,e,r)}function rc(t,e,n){ie(t,e,{kind:"lost",reason:"engine-disabled"},n);for(let r of t.inFlightDownloads)yr(e,r.variantId);return t.inFlightDownloads=[],e.generations.runtimeInstall++,e.generations.runtimeCheck++,e.generations.catalogFetch++,t.state={kind:"failed",reason:"shutdown"},g(t,e,n)}function ic(t,e,n,r){let i=e.clientEnabled;e.clientEnabled=n.enabled,Ut(t,e);let o=t.enabled;return i&&!o&&(ie(t,e,{kind:"lost",reason:"engine-disabled"},r),(t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready")&&(t.state={kind:"no-model"})),!i&&o&&t.state.kind==="model-failed"&&(t.state={kind:"no-model"},t.lastOperationError=null),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function oc(t,e,n,r){return So(t.state)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r)):et(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):yo(t,n.variantId)?(e.clientEnabled=!0,Ut(t,e),t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),n.variantId===t.selectedTarget&&t.enabled?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)):(t.selectedTarget=n.variantId,t.lastOperationError=null,t.state.kind==="downloading"&&t.state.variantId!==n.variantId&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r))):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),g(t,e,r))}function sc(t,e,n,r){return et(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):(t.selectedDevice=n.device?{name:n.device.name,occurrence:n.device.occurrence}:null,r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r))}function ac(t,e,n,r){return et(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):(r.push({type:"listAudioDevices",connectionId:n.connectionId,requestId:n.requestId}),g(t,e,r))}function cc(t,e,n,r){if(So(t.state))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r);if(!qe(t,n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),g(t,e,r);if(Eo(t,n.variantId))return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r);if(!t.inFlightDownloads.some(o=>o.variantId===n.variantId)){let o=yr(e,n.variantId);t.inFlightDownloads.push({variantId:n.variantId}),r.push({type:"downloadModel",variantId:n.variantId,generation:o})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function dc(t,e,n,r){return t.inFlightDownloads.some(o=>o.variantId===n.variantId)&&(r.push({type:"cancelDownload",variantId:n.variantId}),e.generations.downloadByVariant.set(n.variantId,(e.generations.downloadByVariant.get(n.variantId)??0)+1),t.inFlightDownloads=t.inFlightDownloads.filter(o=>o.variantId!==n.variantId),t.selectedTarget===n.variantId&&(t.selectedTarget=null,t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function lc(t,e,n,r){if(t.inFlightDownloads.some(y=>y.variantId===n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),g(t,e,r);if(n.variantId===t.selectedTarget&&et(e))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r);let o=e.modelLoad;if((o.kind==="loading"||o.kind==="unloading")&&o.variantId===n.variantId)return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),g(t,e,r);let a=qe(t,n.variantId),d=o.kind==="loaded"&&o.variantId===n.variantId,u=n.variantId===t.selectedTarget,p=t.state.kind==="model-failed"&&t.state.variantId===n.variantId;return d?e.pendingDelete={variantId:n.variantId}:(r.push({type:"deleteModel",variantId:n.variantId}),a&&(a.cached=!1)),(u||p)&&(t.selectedTarget=null,e.clientEnabled=!1,Ut(t,e),(t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready"||t.state.kind==="model-failed")&&(t.state={kind:"no-model"})),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function uc(t,e,n,r){if(t.state.kind!=="runtime-missing")return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),g(t,e,r);let i=++e.generations.runtimeInstall;return t.state={kind:"installing-runtime",cacheState:t.state.cacheState},r.push({type:"installRuntime",generation:i}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function pc(t,e,n,r){if((t.state.kind==="no-model"||t.state.kind==="downloading"||t.state.kind==="loading"||t.state.kind==="ready"||t.state.kind==="model-failed")&&t.catalogStatus!=="fetching"){let o=++e.generations.catalogFetch;t.catalogStatus="fetching",r.push({type:"fetchCatalog",generation:o})}return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function fc(t,e,n,r){return t.enabled?et(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),g(t,e,r)):t.selectedTarget?t.state.kind!=="ready"?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),g(t,e,r)):(e.currentSession={id:n.sessionId,ownerConnectionId:n.connectionId,status:"opening"},r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),r.push({type:"warmupSession",sessionId:n.sessionId,variantId:t.selectedTarget,device:t.selectedDevice}),g(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),g(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"engine-disabled"}}),g(t,e,r))}function gc(t,e,n,r){let i=e.currentSession;if(!(i!==null&&i.id===n.sessionId&&i.ownerConnectionId===n.connectionId)){let a=n.commit?{kind:"lost",reason:"unknown-session"}:{kind:"discarded"};return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:a}),g(t,e,r)}return n.commit?i!==null&&i.status==="opening"?(ie(t,e,{kind:"lost",reason:"not-ready"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),g(t,e,r)):i!==null&&i.pendingFinishReply?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),g(t,e,r)):(i!==null&&(i.pendingFinishReply={connectionId:n.connectionId,requestId:n.requestId}),r.push({type:"commitSession",sessionId:n.sessionId}),g(t,e,r)):(ie(t,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"discarded"}}),g(t,e,r))}function hc(t,e,n,r){return t.lastOperationError=null,t.state.kind==="model-failed"&&(t.state={kind:"no-model"}),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),g(t,e,r)}function mc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.models=n.models.map(i=>({...i})),t.catalogStatus="ok",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),g(t,e,r)}function vc(t,e,n,r){return n.generation!==e.generations.catalogFetch||(t.catalogStatus="failed",(t.state.kind==="starting"||t.state.kind==="fetching-catalog")&&(t.state={kind:"no-model"})),g(t,e,r)}function yc(t,e,n,r){if(n.generation!==e.generations.runtimeCheck||t.state.kind!=="starting")return g(t,e,r);if(n.cacheState!=="installed")return t.state={kind:"runtime-missing",cacheState:n.cacheState},g(t,e,r);t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;return r.push({type:"fetchCatalog",generation:i}),g(t,e,r)}function Ec(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return g(t,e,r);if(t.state.kind==="installing-runtime"){t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;r.push({type:"fetchCatalog",generation:i})}return g(t,e,r)}function Sc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return g(t,e,r);t.state.kind==="installing-runtime"&&(t.state={kind:"runtime-missing",cacheState:t.state.cacheState});let i={operation:"installRuntime",reason:n.reason};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function wc(t,e,n,r){if(n.generation!==Bt(e,n.variantId))return g(t,e,r);let i={type:"modelDownloadProgress",variantId:n.variantId,percent:n.percent};return r.push({type:"broadcast",event:i}),g(t,e,r)}function bc(t,e,n,r){if(n.generation!==Bt(e,n.variantId))return g(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(o=>o.variantId!==n.variantId);let i=qe(t,n.variantId);return i?i.cached=!0:t.models.push({variantId:n.variantId,displayName:n.variantId,cached:!0,inCatalog:!1}),g(t,e,r)}function Rc(t,e,n,r){return n.generation!==Bt(e,n.variantId)||(t.inFlightDownloads=t.inFlightDownloads.filter(i=>i.variantId!==n.variantId),t.state.kind==="downloading"&&t.state.variantId===n.variantId&&(t.selectedTarget=null,t.state={kind:"no-model"})),g(t,e,r)}function kc(t,e,n,r){if(n.generation!==Bt(e,n.variantId))return g(t,e,r);t.inFlightDownloads=t.inFlightDownloads.filter(a=>a.variantId!==n.variantId),t.state.kind==="downloading"&&t.state.variantId===n.variantId&&(t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelDownloadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),ie(t,e,{kind:"lost",reason:"engine-disabled"},r)));let i={operation:"downloadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function Ic(t,e,n,r){let i=e.modelLoad;return i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId?(r.push({type:"unloadModel",variantId:n.variantId}),g(t,e,r)):(e.modelLoad={kind:"loaded",variantId:n.variantId},t.enabled&&t.selectedTarget===n.variantId&&(t.state={kind:"ready",variantId:n.variantId},t.lastOperationError=null),g(t,e,r))}function _c(t,e,n,r){let i=e.modelLoad;if(i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId)return g(t,e,r);e.modelLoad={kind:"unloaded"},t.selectedTarget=null,t.state={kind:"model-failed",variantId:n.variantId,reason:n.reason},e.currentSession&&(r.push({type:"logWarning",message:`invariant: currentSession present in handleModelLoadFailed (sessionId=${e.currentSession.id}, variantId=${n.variantId})`}),ie(t,e,{kind:"lost",reason:"engine-disabled"},r));let o={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=o;let a={type:"operationError",error:o};return r.push({type:"broadcast",event:a}),g(t,e,r)}function Pc(t,e,n,r){let i=e.modelLoad;if(i.kind!=="unloading"||i.variantId!==n.variantId)return g(t,e,r);if(e.modelLoad={kind:"unloaded"},e.pendingDelete&&e.pendingDelete.variantId===n.variantId){r.push({type:"deleteModel",variantId:n.variantId});let o=qe(t,n.variantId);o&&(o.cached=!1),(t.state.kind==="ready"||t.state.kind==="loading"||t.state.kind==="downloading")&&t.state.variantId===n.variantId&&(t.state={kind:"no-model"}),e.pendingDelete=null}return g(t,e,r)}function Cc(t,e,n,r){let i={operation:"loadModel",reason:n.reason,variantId:n.variantId};t.lastOperationError=i;let o={type:"operationError",error:i};return r.push({type:"broadcast",event:o}),g(t,e,r)}function Mc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||i.status==="opening"&&(i.status="active"),g(t,e,r)}function xc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||(Tc(i.ownerConnectionId,n.sessionId,n.failure,r),ie(t,e,{kind:"lost",reason:n.failure.side==="mic"?"mic-error":"stt-error"},r)),g(t,e,r)}function Tc(t,e,n,r){let i=n.side==="mic"?{type:"micError",sessionId:e,subreason:n.subreason}:{type:"sttError",sessionId:e,subreason:n.subreason};r.push({type:"sendTo",connectionId:t,event:i})}function Oc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o={type:"micError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:o}),ie(t,e,{kind:"lost",reason:"mic-error"},r),g(t,e,r)}function Nc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o=i.pendingFinishReply?{kind:"committed",text:n.text}:{kind:"discarded"};return ie(t,e,o,r),g(t,e,r)}function Lc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return g(t,e,r);let o={type:"sttError",sessionId:n.sessionId,subreason:n.subreason};return r.push({type:"sendTo",connectionId:i.ownerConnectionId,event:o}),ie(t,e,{kind:"lost",reason:"stt-error"},r),g(t,e,r)}function Fc(t,e,n,r){let i=e.currentSession;return i&&i.ownerConnectionId===n.connectionId&&ie(t,e,{kind:"lost",reason:"engine-disabled"},r),g(t,e,r)}function bo(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null,selectedDevice:null}}function Ro(){return{generations:{runtimeInstall:0,runtimeCheck:0,downloadByVariant:new Map,catalogFetch:0},nextLoadGeneration:0,modelLoad:{kind:"unloaded"},currentSession:null,clientEnabled:!1,pendingDelete:null}}function ko(t={}){let e=t.attackMs??12,n=t.releaseMs??100,r=Math.max(1,Math.round(8/1e3*16e3)),i=0;return{feed(o){let a=o.byteLength/2|0;if(a!==0)for(let d=0;d<a;d+=r){let u=Math.min(a,d+r),p=0;for(let H=d;H<u;H++){let b=o[H*2],J=(o[H*2+1]<<8|b)<<16>>16,T=J<0?-J:J;T>p&&(p=T)}let y=p/32768,I=Math.min(1,Math.sqrt(y)),x=(u-d)/16e3*1e3,q=I>i?e:n,_=1-Math.exp(-x/Math.max(.001,q));i=i+(I-i)*_}},current(){return i},reset(){i=0}}}function Ac(t){throw new Error(`Unhandled EngineEffect type: ${t.type}`)}var Io=64,zt=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=bo(),this.internal=Ro(),this.host=e.host,this.levelMeter=ko(),this.foundry=e.foundryFactory(this.buildFoundryEvents()),this.mic=e.micFactory(this.buildMicEvents()),this.submit({type:"boot",bootEnabled:e.bootSettings.voice?.enabled===!0,bootSelectedModel:e.bootSettings.voice?.selectedModel??null,bootSelectedDevice:e.bootSettings.voice?.selectedDevice??null}),this.unsubscribeConnected=e.host.onClientConnected(n=>{e.host.sendTo(n,{type:"initialize",snapshot:this.snapshot})}),this.unsubscribeDisconnected=e.host.onClientDisconnected(n=>{this.submit({type:"client:disconnected",connectionId:n})})}buildFoundryEvents(){return{submit:e=>{this.submit(e)},onSttPartial:(e,n)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active"||r.pendingFinishReply)return;this.host.sendTo(r.ownerConnectionId,{type:"sessionPreview",sessionId:e,partialTranscript:n})}catch(r){h.error(`[VoiceEngine] onSttPartial threw: ${w(r)}`)}}}}buildMicEvents(){return{submit:e=>{this.submit(e)},onPcmFrame:(e,n)=>{if(!this.disposed)try{let r=this.internal.currentSession;if(!r||r.id!==e||r.status!=="active")return;this.levelMeter.feed(n),this.foundry.appendSttPcm(e,n),r.pendingFinishReply||this.emitEnvelope(r.id,r.ownerConnectionId)}catch(r){h.error(`[VoiceEngine] onPcmFrame threw: ${w(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=Io){h.error(`[VoiceEngine] dispatch depth exceeded ${Io} for command '${e.type}'; dropping to avoid runaway recursion.`);return}this.dispatchDepth++;try{let n=this.snapshot,r=n.session?.status==="active"?n.session.id:null,{snapshot:i,internal:o,effects:a}=wo(this.snapshot,this.internal,e);this.snapshot=i,this.internal=o;for(let u of a)try{this.dispatch(u)}catch(p){h.error(`[VoiceEngine] dispatching effect '${u.type}' threw: ${w(p)}`)}let d=this.snapshot.session?.status==="active"?this.snapshot.session.id:null;r===null&&d!==null&&this.levelMeter.reset(),n!==this.snapshot&&this.host.broadcast({type:"state",snapshot:this.snapshot})}finally{this.dispatchDepth--}}}getSnapshot(){return this.snapshot}async dispose(){if(this.disposed)return;this.disposed=!0,this.unsubscribeConnected(),this.unsubscribeDisconnected();let e=await Promise.allSettled([this.foundry.dispose(),this.mic.dispose()]);for(let n of e)n.status==="rejected"&&h.error(`[VoiceEngine] adapter dispose rejected: ${w(n.reason)}`)}emitEnvelope(e,n){try{this.host.sendTo(n,{type:"sessionAudio",sessionId:e,envelope:this.levelMeter.current()})}catch(r){h.error(`[VoiceEngine] emitEnvelope threw: ${w(r)}`)}}dispatch(e){switch(e.type){case"checkRuntime":this.foundry.checkRuntime(e.generation);break;case"fetchCatalog":this.foundry.fetchCatalog(e.generation);break;case"installRuntime":this.foundry.installRuntime(e.generation);break;case"downloadModel":this.foundry.downloadModel(e.variantId,e.generation);break;case"cancelDownload":this.foundry.cancelDownload(e.variantId);break;case"loadModel":this.foundry.loadModel(e.variantId,e.generation);break;case"unloadModel":this.foundry.unloadModel(e.variantId);break;case"deleteModel":this.foundry.deleteModel(e.variantId);break;case"warmupSession":{let{sessionId:n,variantId:r,device:i}=e,o;try{o=this.mic.openForSession(n,i)}catch(p){o=Promise.reject(p instanceof Error?p:new Error(String(p)))}let a=o.then(p=>(p.ok||this.foundry.cancelSttSession(n),p)),d;try{d=this.foundry.openSttSession(n,r)}catch(p){d=Promise.reject(p instanceof Error?p:new Error(String(p)))}let u=d.then(p=>(p.ok||this.mic.closeSession("discard").catch(()=>{}),p));Promise.all([a,u]).then(([p,y])=>{this.disposed||(p.ok&&y.ok?this.submit({type:"internal:sessionWarmed",sessionId:n}):p.ok?y.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:y.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"mic",subreason:p.subreason}}))},p=>{h.error(`[VoiceEngine] warmupSession(${n}) rejected: ${w(p)}`),!this.disposed&&this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:"session-open-failed"}})});break}case"cancelSession":this.mic.closeSession("discard").catch(()=>{}),this.foundry.cancelSttSession(e.sessionId);break;case"commitSession":{let n=e.sessionId;this.mic.closeSession("commit").then(()=>{this.disposed||this.foundry.endSttSession(n)},r=>{h.error(`[VoiceEngine] commitSession(${n}) drain rejected: ${w(r)}`),!this.disposed&&this.foundry.endSttSession(n)});break}case"replyResolve":this.host.resolveRpc(e.connectionId,e.requestId,e.result);break;case"replyReject":this.host.rejectRpc(e.connectionId,e.requestId,e.reason);break;case"listAudioDevices":{let{connectionId:n,requestId:r}=e,i;try{i=this.mic.listDevices()}catch(o){i=Promise.reject(o instanceof Error?o:new Error(String(o)))}i.then(o=>{this.disposed||this.host.resolveRpc(n,r,o)},o=>{h.error(`[VoiceEngine] listAudioDevices rejected: ${w(o)}`),!this.disposed&&this.host.resolveRpc(n,r,{ok:!1,reason:"unavailable"})});break}case"broadcast":this.host.broadcast(e.event);break;case"sendTo":this.host.sendTo(e.connectionId,e.event);break;case"logWarning":h.warning(`[VoiceEngine] ${e.message}`);break;default:Ac(e)}}};import{existsSync as Er}from"node:fs";import{dirname as _o,join as Sr}from"node:path";import{fileURLToPath as Dc}from"node:url";function Po(t){let{importMetaUrl:e,filename:n,label:r}=t,i;try{i=_o(Dc(e))}catch(p){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${w(p)}).`)}let o=Sr(i,n);if(Er(o))return o;let a=$c(i),d=a?Sr(a,"dist-cli",n):void 0;if(d&&Er(d))return d;let u=d?`${o}, ${d}`:o;throw new Error(`Voice ${r} worker bundle not found. Searched: ${u}`)}function $c(t){let e=t;for(;;){if(Er(Sr(e,"package.json")))return e;let n=_o(e);if(n===e)return;e=n}}function Co(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}var wr=16*1024;function br(t,e,n=h){let r=Vc(t.level)?t.level:"info",i=typeof t.message=="string"?t.message:Co(t.message);n[r](`[${e} worker] ${jc(i)}`)}function Vc(t){return t==="debug"||t==="info"||t==="warning"||t==="error"}function jc(t){return t.length<=wr?t:`${t.slice(0,wr)}\u2026 [truncated, ${t.length-wr} more chars]`}import{Worker as qc}from"node:worker_threads";var Mo=(t,e)=>new qc(t,e);import{createRequire as Wc}from"node:module";import*as Se from"node:fs/promises";import*as ne from"node:path";import{createHash as Uc}from"node:crypto";import{join as tt,basename as Mu}from"node:path";import{homedir as Rr}from"node:os";function Hc(){return process.env.XDG_CACHE_HOME||tt(Rr(),".cache")}function xo(){if(process.platform==="darwin")return tt(Rr(),"Library","Caches","copilot");if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||tt(Rr(),".cache");return tt(t,"copilot")}return tt(Hc(),"copilot")}var Bc=1,zc=".complete";var No={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function Gc(){return typeof __foundryRequire<"u"&&__foundryRequire||Wc(import.meta.url)}var Gt;function Jc(){if(Gt)return Gt;try{let t=Gc()("foundry-local-sdk/deps_versions.json");if(typeof t["foundry-local-core"]?.nuget!="string"||typeof t.onnxruntime?.version!="string"||typeof t["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 Gt=t,Gt}catch(t){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${w(t)}. 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 Kc(t=process.platform){let e=Jc();return[{name:"Microsoft.AI.Foundry.Local.Core",version:e["foundry-local-core"].nuget},{name:t==="linux"?"Microsoft.ML.OnnxRuntime.Gpu.Linux":"Microsoft.ML.OnnxRuntime.Foundry",version:e.onnxruntime.version},{name:"Microsoft.ML.OnnxRuntimeGenAI.Foundry",version:e["onnxruntime-genai"].version}]}function Lo(t){return t==="win32"?".dll":t==="darwin"?".dylib":".so"}function Qc(t,e){return ne.join(t,`Microsoft.AI.Foundry.Local.Core${Lo(e)}`)}function Yc(t){let e=Lo(t),n=t==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${e}`,`${n}onnxruntime${e}`,`${n}onnxruntime-genai${e}`]}function Xc(t,e=process.platform,n=process.arch){let r=No[`${e}-${n}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${n}`);let i=t??process.env.COPILOT_CACHE_HOME??xo(),o=Kc(e),a=Uc("sha256").update(JSON.stringify({schema:Bc,artifacts:o})).digest("hex").slice(0,12);return ne.join(i,"foundry",a,r)}async function Fo(t={}){let e=t.platform??process.platform,n=t.arch??process.arch,r=`${e}-${n}`,i=No[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let o=Xc(t.cacheRoot,e,n),a=Yc(e);if(await To(o,a))return{kind:"downloaded",location:{corePath:Qc(o,e)}};let d=ne.dirname(ne.dirname(o)),u;try{u=await Se.readdir(d)}catch{return{kind:"not-downloaded"}}let p=ne.basename(ne.dirname(o));for(let y of u){if(y===p)continue;let I=ne.join(d,y,i);if(await To(I,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function To(t,e){return await Oo(ne.join(t,zc))?(await Promise.all(e.map(r=>Oo(ne.join(t,r))))).every(Boolean):!1}async function Oo(t){try{return await Se.access(t),!0}catch{return!1}}var Ao=5e3;function Do(t={}){let{cacheRoot:e,workerFactory:n=Mo,workerScriptPath:r,inspectImpl:i=Fo}=t,o,a;return{async inspect(){if(a&&Date.now()<a.expiry)return a.result;let d=await i({cacheRoot:e});return a={result:d,expiry:Date.now()+Ao},d},install(d){if(o)return o;a=void 0;let u=Zc({cacheRoot:e,workerFactory:n,workerScriptPath:r??Po({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:d}).then(p=>(a={result:{kind:"downloaded",location:p},expiry:Date.now()+Ao},p)).catch(p=>{throw o=void 0,a=void 0,p});return o=u,u}}}function Zc(t){return new Promise((e,n)=>{let r;try{r=t.workerFactory(t.workerScriptPath,{workerData:{cacheRoot:t.cacheRoot}})}catch(a){n(qt(a));return}let i=!1,o=a=>{i||(i=!0,r.terminate().catch(d=>{h.warning(`[voice-runtime] installer worker terminate failed: ${w(d)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){h.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let d=a;if(d.kind==="log"){br(d,"Installer");return}if(d.kind==="download-started"){if(!t.onProgress)return;try{t.onProgress({kind:"indeterminate"})}catch(u){h.warning(`[voice-runtime] installer onProgress threw: ${w(u)}`)}return}if(d.kind==="ok"){o(()=>e(d.location));return}if(d.kind==="error"){o(()=>n(mr(d.error)));return}}),r.on("error",a=>{o(()=>n(qt(a)))}),r.on("exit",a=>{o(()=>n(new Error(`Voice installer worker exited unexpectedly with code ${a}.`)))})})}import{readFileSync as ed,unlinkSync as td,writeFileSync as nd}from"node:fs";function $o(t,e){nd(t,`${e}
`,{encoding:"utf8"})}function Vo(t){let e;try{e=ed(t,"utf8")}catch{return null}let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?null:n}function jo(t){try{td(t)}catch{}}var Qt=it($t(),1);import{unlinkSync as rd}from"node:fs";import{createConnection as id,createServer as od}from"node:net";var qo=it($t(),1),Jt=class extends qo.AbstractMessageWriter{socket;errorCount=0;ended=!1;constructor(e){super(),this.socket=e,e.on("close",()=>this.fireClose()),e.on("error",n=>this.fireError(n,void 0,0))}write(e){if(this.ended)return Promise.resolve();try{let n=JSON.stringify(e);if(n===void 0)throw new Error("FastSocketMessageWriter: message serialized to undefined");let r=Buffer.from(n,"utf-8"),i=Buffer.from(`Content-Length: ${r.byteLength}\r
\r
`,"ascii"),o=Buffer.concat([i,r],i.byteLength+r.byteLength);return this.socket.write(o),Promise.resolve()}catch(n){return this.errorCount++,this.fireError(n,e,this.errorCount),Promise.reject(n instanceof Error?n:new Error(String(n)))}}end(){if(!this.ended){this.ended=!0;try{this.socket.end()}catch{}}}dispose(){if(super.dispose(),!this.ended){this.ended=!0;try{this.socket.end()}catch{}}}};var Kt=class{host;address;server=null;stopped=!1;constructor(e){this.host=e.host,this.address=e.address}async start(){if(this.stopped)throw new Error("VoiceServer.start called after stop().");if(this.server)throw new Error("VoiceServer.start called more than once.");let e=await sd(this.address,n=>this.handleSocket(n));return e===null?"lost":(this.server=e,"bound")}async stop(){if(this.stopped)return;this.stopped=!0,h.info(`voice server: server stopping (clients=${this.host.connectionCount})`);let e=this.server;this.server=null,e&&await new Promise(n=>{e.close(()=>n())})}handleSocket(e){if(this.stopped){e.destroy();return}let n=(0,Qt.createMessageConnection)(new Qt.SocketMessageReader(e),new Jt(e));try{let r=this.host.registerConnection({connection:n});h.info(`voice server: client connected id=${r.connectionId} (clients=${this.host.connectionCount})`)}catch(r){h.error(`voice server: registerConnection failed: ${r.message}`);try{n.dispose()}catch{}e.destroy()}}};function sd(t,e){return new Promise((n,r)=>{let i=o=>{let a=od(e),d=u=>{if(a.removeAllListeners(),u.code==="EADDRINUSE"&&o&&process.platform!=="win32"){let p=id(t);p.once("connect",()=>{p.destroy(),n(null)}),p.once("error",y=>{let I=y.code;if(I==="ECONNREFUSED"||I==="ENOENT"){try{rd(t)}catch{}i(!1)}else n(null)});return}if(u.code==="EADDRINUSE"||u.code==="EEXIST"){n(null);return}r(u)};a.once("error",d),a.listen(t,()=>{a.removeListener("error",d),n(a)})};i(!0)})}import{createHash as ud}from"node:crypto";import{mkdirSync as Wo}from"node:fs";import{homedir as Uo,tmpdir as pd}from"node:os";import{join as He}from"node:path";import{readFileSync as ad}from"fs";import{dirname as cd,join as kr}from"path";import{fileURLToPath as dd}from"url";var nt=null;function Ho(){return ld().version}function ld(){if(nt!==null)return nt;try{let t=dd(import.meta.url),e=cd(t),n=[kr(e,"package.json"),kr(e,"../package.json"),kr(e,"../../package.json")];for(let i of n)try{let o=JSON.parse(ad(i,"utf8")),a={name:o.name||"unknown",version:o.version||"unknown",buildMetadata:o.buildMetadata};return nt=a,a}catch{continue}let r={name:"unknown",version:"unknown"};return nt=r,r}catch{let e={name:"unknown",version:"unknown"};return nt=e,e}}var fd=8,Yt="copilot-voice",gd="COPILOT_VOICE_SERVER_INSTANCE",hd=100;function Bo(t={}){let e=t.platform??process.platform,n=t.env??process.env,r=t.tmpDir??pd(),i=t.cliVersion??Ho(),o=n[gd]||void 0;if(e==="win32"){let I=Xt(n.USERPROFILE??n.HOMEPATH??n.USERNAME??t.homeDir??Uo()??"anon"),x=Xt(`${i}|${I}${o?`|${o}`:""}`),q=`\\\\.\\pipe\\${Yt}-${x}`,_=He(r,Yt);return Wo(_,{recursive:!0}),{address:q,pidFile:He(_,`${x}.pid`),endpointHash:x}}let a=Xt(o?`${i}|${o}`:i),d=n.XDG_RUNTIME_DIR,u=Xt(n.HOME??t.homeDir??Uo()??n.USER??"anon"),p=d?He(d,Yt):He(r,`${Yt}-${u}`);Wo(p,{recursive:!0,mode:448});let y=He(p,`${a}.sock`);return y.length>hd&&h.warning(`voice server: Unix socket path is ${y.length} bytes (macOS limit is 104): ${y}`),{address:y,pidFile:He(p,`${a}.pid`),endpointHash:a}}function Xt(t){return ud("sha256").update(t).digest("hex").slice(0,fd)}var zo="COPILOT_VOICE_SERVER_BOOT";function Go(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!Ir(e))return{};let n=e.voice;if(!Ir(n))return{};let r={};typeof n.enabled=="boolean"&&(r.enabled=n.enabled),typeof n.selectedModel=="string"&&n.selectedModel.length>0&&(r.selectedModel=n.selectedModel);let i=md(n.selectedDevice);return i&&(r.selectedDevice=i),Object.keys(r).length>0?{voice:r}:{}}function md(t){if(!Ir(t))return;let e=t.name;if(typeof e!="string"||e.length===0)return;let n=t.occurrence,r=typeof n=="number"&&Number.isInteger(n)&&n>=0?n:0;return{name:e,occurrence:r}}function Ir(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var yd=10,Jo=1,Ko=6e4;async function kp(){let t=Bo(),e=Ed(t.endpointHash),n=new mt(e);h.setLogWriter(n),h.info(`voice server: boot pid=${process.pid} endpoint=${t.address}`);let r=Do(),i=new jt,o=new zt({host:i,foundryFactory:_=>new Ht({events:_,installer:r}),micFactory:_=>new Wt({events:_}),bootSettings:Go(process.env[zo])});i.setSubmit(_=>o.submit(_));let a=!1,d=null,u=()=>{d===null&&(d=setTimeout(()=>{d=null,h.info("voice server: idle timeout, shutting down"),q("idle timeout").catch(()=>{})},Ko))},p=()=>{d!==null&&(clearTimeout(d),d=null)};i.onClientConnected(()=>p()),i.onClientDisconnected(()=>{a||i.connectionCount===0&&u()}),u();let y=new Kt({host:i,address:t.address}),I;try{I=await y.start()}catch(_){h.error(`voice server: bind threw: ${_.stack??String(_)}`),await n.writeQueue,process.exit(Jo)}I==="lost"&&(h.info(`voice server: bind-loser, another voice server owns ${t.address}`),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(yd));try{$o(t.pidFile,process.pid)}catch(_){h.error(`voice server: writeServerPidFile failed: ${_.message}`),await y.stop(),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(Jo)}let x=()=>{Vo(t.pidFile)===process.pid&&jo(t.pidFile)},q=async _=>{if(a)return;a=!0,p(),h.info(`voice server: shutdown (${_})`);let H=y.stop().catch(b=>{h.error(`voice server: server.stop failed: ${b.message}`)});i.dispose(),await H,await o.dispose().catch(b=>{h.error(`voice server: engine.dispose failed: ${b.message}`)}),x(),await n.writeQueue.catch(()=>{}),process.exit(0)};for(let _ of["SIGINT","SIGTERM","SIGHUP"])process.on(_,()=>{q(`signal ${_}`).catch(()=>{})});process.on("uncaughtException",_=>{h.error(`voice server: uncaughtException: ${_.stack??String(_)}`),q("uncaughtException").catch(()=>{})}),process.on("unhandledRejection",_=>{h.error(`voice server: unhandledRejection: ${String(_)}`)}),process.on("exit",()=>{x()}),h.info(`voice server: ready (idle timer armed ${Ko}ms)`)}function Ed(t){return vd(bi(void 0,"state"),"logs",`voice-server-${t}.log`)}export{kp as runVoiceServer};
//# sourceMappingURL=voice-server.js.map
