(()=>{const stack=new Error().stack;stack&&(globalThis._sentryDebugIds=globalThis._sentryDebugIds||{},globalThis._sentryDebugIds[stack]="a5e671bd-9b15-545f-9b44-f3750998f754",globalThis._sentryDebugIdIdentifier="sentry-dbid-a5e671bd-9b15-545f-9b44-f3750998f754");})();

/*---------------------------------------------------------------------------------------------
 *  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 gs=Object.create;var $r=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 ws=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vs(e))!Es.call(t,i)&&i!==n&&$r(t,i,{get:()=>e[i],enumerable:!(r=ms(e,i))||r.enumerable});return t};var nt=(t,e,n)=>(n=t!=null?gs(ys(t)):{},ws(e||!t||!t.__esModule?$r(n,"default",{value:t,enumerable:!0}):n,t));var qr=j((kd,jr)=>{"use strict";var Vr=()=>process.platform==="linux",it=null,Ss=()=>{if(!it)if(Vr()&&process.report){let t=process.report.excludeNetwork;process.report.excludeNetwork=!0,it=process.report.getReport(),process.report.excludeNetwork=t}else it={};return it};jr.exports={isLinux:Vr,getReport:Ss}});var Wr=j((Rd,Hr)=>{"use strict";var Te=de("fs"),bs="/usr/bin/ldd",ks="/proc/self/exe",ot=2048,Rs=t=>{let e=Te.openSync(t,"r"),n=Buffer.alloc(ot),r=Te.readSync(e,n,0,ot,0);return Te.close(e,()=>{}),n.subarray(0,r)},_s=t=>new Promise((e,n)=>{Te.open(t,"r",(r,i)=>{if(r)n(r);else{let o=Buffer.alloc(ot);Te.read(i,o,0,ot,0,(a,l)=>{e(o.subarray(0,l)),Te.close(i,()=>{})})}})});Hr.exports={LDD_PATH:bs,SELF_PATH:ks,readFileSync:Rs,readFile:_s}});var Br=j((_d,Ur)=>{"use strict";var Is=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 l=t.readUInt32LE(o+8),u=t.readUInt32LE(o+32);return t.subarray(l,l+u).toString().replace(/\0.*$/g,"")}}return null};Ur.exports={interpreterPath:Is}});var li=j((Id,di)=>{"use strict";var Gr=de("child_process"),{isLinux:xe,getReport:Jr}=qr(),{LDD_PATH:st,SELF_PATH:Kr,readFile:tn,readFileSync:nn}=Wr(),{interpreterPath:Qr}=Br(),se,ae,ce,Yr="getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",ge="",Xr=()=>ge||new Promise(t=>{Gr.exec(Yr,(e,n)=>{ge=e?" ":n,t(ge)})}),Zr=()=>{if(!ge)try{ge=Gr.execSync(Yr,{encoding:"utf8"})}catch{ge=" "}return ge},le="glibc",ei=/LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i,be="musl",Cs=t=>t.includes("libc.musl-")||t.includes("ld-musl-"),ti=()=>{let t=Jr();return t.header&&t.header.glibcVersionRuntime?le:Array.isArray(t.sharedObjects)&&t.sharedObjects.some(Cs)?be:null},ni=t=>{let[e,n]=t.split(/[\r\n]+/);return e&&e.includes(le)?le:n&&n.includes(be)?be:null},ri=t=>{if(t){if(t.includes("/ld-musl-"))return be;if(t.includes("/ld-linux-"))return le}return null},ii=t=>(t=t.toString(),t.includes("musl")?be:t.includes("GNU C Library")?le:null),Ps=async()=>{if(ae!==void 0)return ae;ae=null;try{let t=await tn(st);ae=ii(t)}catch{}return ae},Ts=()=>{if(ae!==void 0)return ae;ae=null;try{let t=nn(st);ae=ii(t)}catch{}return ae},xs=async()=>{if(se!==void 0)return se;se=null;try{let t=await tn(Kr),e=Qr(t);se=ri(e)}catch{}return se},Ms=()=>{if(se!==void 0)return se;se=null;try{let t=nn(Kr),e=Qr(t);se=ri(e)}catch{}return se},oi=async()=>{let t=null;if(xe()&&(t=await xs(),!t&&(t=await Ps(),t||(t=ti()),!t))){let e=await Xr();t=ni(e)}return t},si=()=>{let t=null;if(xe()&&(t=Ms(),!t&&(t=Ts(),t||(t=ti()),!t))){let e=Zr();t=ni(e)}return t},Os=async()=>xe()&&await oi()!==le,Ns=()=>xe()&&si()!==le,Ls=async()=>{if(ce!==void 0)return ce;ce=null;try{let e=(await tn(st)).match(ei);e&&(ce=e[1])}catch{}return ce},Fs=()=>{if(ce!==void 0)return ce;ce=null;try{let e=nn(st).match(ei);e&&(ce=e[1])}catch{}return ce},ai=()=>{let t=Jr();return t.header&&t.header.glibcVersionRuntime?t.header.glibcVersionRuntime:null},zr=t=>t.trim().split(/\s+/)[1],ci=t=>{let[e,n,r]=t.split(/[\r\n]+/);return e&&e.includes(le)?zr(e):n&&r&&n.includes(be)?zr(r):null},As=async()=>{let t=null;if(xe()&&(t=await Ls(),t||(t=ai()),!t)){let e=await Xr();t=ci(e)}return t},Ds=()=>{let t=null;if(xe()&&(t=Fs(),t||(t=ai()),!t)){let e=Zr();t=ci(e)}return t};di.exports={GLIBC:le,MUSL:be,family:oi,familySync:si,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 la(t){return t===!0||t===!1}z.boolean=la;function Ci(t){return typeof t=="string"||t instanceof String}z.string=Ci;function ua(t){return typeof t=="number"||t instanceof Number}z.number=ua;function pa(t){return t instanceof Error}z.error=pa;function fa(t){return typeof t=="function"}z.func=fa;function Pi(t){return Array.isArray(t)}z.array=Pi;function ha(t){return Pi(t)&&t.every(e=>Ci(e))}z.stringArray=ha});var Tn=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 ke=Oe(),on;(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})(on||(v.ErrorCodes=on={}));var sn=class t extends Error{constructor(e,n,r){super(n),this.code=ke.number(e)?e:on.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=sn;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 L=class{constructor(e,n){this.method=e,this.numberOfParams=n}get parameterStructures(){return Y.auto}};v.AbstractMessageSignature=L;var an=class extends L{constructor(e){super(e,0)}};v.RequestType0=an;var cn=class extends L{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.RequestType=cn;var dn=class extends L{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.RequestType1=dn;var ln=class extends L{constructor(e){super(e,2)}};v.RequestType2=ln;var un=class extends L{constructor(e){super(e,3)}};v.RequestType3=un;var pn=class extends L{constructor(e){super(e,4)}};v.RequestType4=pn;var fn=class extends L{constructor(e){super(e,5)}};v.RequestType5=fn;var hn=class extends L{constructor(e){super(e,6)}};v.RequestType6=hn;var gn=class extends L{constructor(e){super(e,7)}};v.RequestType7=gn;var mn=class extends L{constructor(e){super(e,8)}};v.RequestType8=mn;var vn=class extends L{constructor(e){super(e,9)}};v.RequestType9=vn;var yn=class extends L{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.NotificationType=yn;var En=class extends L{constructor(e){super(e,0)}};v.NotificationType0=En;var wn=class extends L{constructor(e,n=Y.auto){super(e,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};v.NotificationType1=wn;var Sn=class extends L{constructor(e){super(e,2)}};v.NotificationType2=Sn;var bn=class extends L{constructor(e){super(e,3)}};v.NotificationType3=bn;var kn=class extends L{constructor(e){super(e,4)}};v.NotificationType4=kn;var Rn=class extends L{constructor(e){super(e,5)}};v.NotificationType5=Rn;var _n=class extends L{constructor(e){super(e,6)}};v.NotificationType6=_n;var In=class extends L{constructor(e){super(e,7)}};v.NotificationType7=In;var Cn=class extends L{constructor(e){super(e,8)}};v.NotificationType8=Cn;var Pn=class extends L{constructor(e){super(e,9)}};v.NotificationType9=Pn;var Ti;(function(t){function e(i){let o=i;return o&&ke.string(o.method)&&(ke.string(o.id)||ke.number(o.id))}t.isRequest=e;function n(i){let o=i;return o&&ke.string(o.method)&&i.id===void 0}t.isNotification=n;function r(i){let o=i;return o&&(o.result!==void 0||!!o.error)&&(ke.string(o.id)||ke.number(o.id)||o.id===null)}t.isResponse=r})(Ti||(v.Message=Ti={}))});var Mn=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 mt=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=mt;var xn=class extends mt{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=xn});var Oi=j(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.Disposable=void 0;var Mi;(function(t){function e(n){return{dispose:n}}t.create=e})(Mi||(vt.Disposable=Mi={}))});var ve=j(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});var On;function Nn(){if(On===void 0)throw new Error("No runtime abstraction layer installed");return On}(function(t){function e(n){if(n===void 0)throw new Error("No runtime abstraction layer provided");On=n}t.install=e})(Nn||(Nn={}));Ln.default=Nn});var Le=j(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Emitter=Ne.Event=void 0;var ga=ve(),Ni;(function(t){let e={dispose(){}};t.None=function(){return e}})(Ni||(Ne.Event=Ni={}));var Fn=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(l){(0,ga.default)().console.error(l)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},yt=class t{constructor(e){this._options=e}get event(){return this._event||(this._event=(e,n,r)=>{this._callbacks||(this._callbacks=new Fn),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=yt;yt._noop=function(){}});var St=j(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CancellationTokenSource=Fe.CancellationToken=void 0;var ma=ve(),va=Oe(),An=Le(),Et;(function(t){t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:An.Event.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:An.Event.None});function e(n){let r=n;return r&&(r===t.None||r===t.Cancelled||va.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}t.is=e})(Et||(Fe.CancellationToken=Et={}));var ya=Object.freeze(function(t,e){let n=(0,ma.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?ya:(this._emitter||(this._emitter=new An.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},Dn=class{get token(){return this._token||(this._token=new wt),this._token}cancel(){this._token?this._token.cancel():this._token=Et.Cancelled}dispose(){this._token?this._token instanceof wt&&this._token.dispose():this._token=Et.None}};Fe.CancellationTokenSource=Dn});var Li=j(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.SharedArrayReceiverStrategy=Ae.SharedArraySenderStrategy=void 0;var Ea=St(),ze;(function(t){t.Continue=0,t.Cancelled=1})(ze||(ze={}));var $n=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=$n;var Vn=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")}},jn=class{constructor(e){this.token=new Vn(e)}cancel(){}dispose(){}},qn=class{constructor(){this.kind="request"}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new Ea.CancellationTokenSource:new jn(n)}};Ae.SharedArrayReceiverStrategy=qn});var Wn=j(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.Semaphore=void 0;var wa=ve(),Hn=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,wa.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()}}};bt.Semaphore=Hn});var Ai=j(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.ReadableStreamMessageReader=ye.AbstractMessageReader=ye.MessageReader=void 0;var Bn=ve(),De=Oe(),Un=Le(),Sa=Wn(),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 Un.Emitter,this.closeEmitter=new Un.Emitter,this.partialMessageEmitter=new Un.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 zn;(function(t){function e(n){let r,i,o,a=new Map,l,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 h of n.contentDecoders)a.set(h.name,h);if(n.contentTypeDecoder!==void 0&&(l=n.contentTypeDecoder,u.set(l.name,l)),n.contentTypeDecoders!==void 0)for(let h of n.contentTypeDecoders)u.set(h.name,h)}return l===void 0&&(l=(0,Bn.default)().applicationJson.decoder,u.set(l.name,l)),{charset:r,contentDecoder:o,contentDecoders:a,contentTypeDecoder:l,contentTypeDecoders:u}}t.fromOptions=e})(zn||(zn={}));var Gn=class extends kt{constructor(e,n){super(),this.readable=e,this.options=zn.fromOptions(n),this.buffer=(0,Bn.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new Sa.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,Bn.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=Gn});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(),ba=Wn(),$i=Le(),ka="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 Rt=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=Rt;var Jn;(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})(Jn||(Jn={}));var Kn=class extends Rt{constructor(e,n){super(),this.writable=e,this.options=Jn.fromOptions(n),this.errorCount=0,this.writeSemaphore=new ba.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(ka,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=Kn});var Hi=j(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.AbstractMessageBuffer=void 0;var Ra=13,_a=10,Ia=`\r
`,Qn=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 h=this._chunks[r];for(i=0;i<h.length;){switch(h[i]){case Ra:switch(n){case 0:n=1;break;case 2:n=3;break;default:n=0}break;case _a:switch(n){case 1:n=2;break;case 3:n=4,i++;break e;default:n=0}break;default:n=0}i++}o+=h.byteLength,r++}if(n!==4)return;let a=this._read(o+i),l=new Map,u=this.toString(a,"ascii").split(Ia);if(u.length<2)return l;for(let h=0;h<u.length-2;h++){let E=u[h],k=E.indexOf(":");if(k===-1)throw new Error(`Message header must separate key and value using ':'
${E}`);let M=E.substr(0,k),$=E.substr(k+1).trim();l.set(e?M.toLowerCase():M,$)}return l}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=Qn});var Gi=j(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.createMessageConnection=w.ConnectionOptions=w.MessageStrategy=w.CancellationStrategy=w.CancellationSenderStrategy=w.CancellationReceiverStrategy=w.RequestCancellationReceiverStrategy=w.IdCancellationReceiverStrategy=w.ConnectionStrategy=w.ConnectionError=w.ConnectionErrors=w.LogTraceNotification=w.SetTraceNotification=w.TraceFormat=w.TraceValues=w.Trace=w.NullLogger=w.ProgressType=w.ProgressToken=void 0;var Wi=ve(),A=Oe(),y=Tn(),Ui=Mn(),Je=Le(),Yn=St(),Ye;(function(t){t.type=new y.NotificationType("$/cancelRequest")})(Ye||(Ye={}));var Xn;(function(t){function e(n){return typeof n=="string"||typeof n=="number"}t.is=e})(Xn||(w.ProgressToken=Xn={}));var Ke;(function(t){t.type=new y.NotificationType("$/progress")})(Ke||(Ke={}));var Zn=class{constructor(){}};w.ProgressType=Zn;var er;(function(t){function e(n){return A.func(n)}t.is=e})(er||(er={}));w.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var I;(function(t){t[t.Off=0]="Off",t[t.Messages=1]="Messages",t[t.Compact=2]="Compact",t[t.Verbose=3]="Verbose"})(I||(w.Trace=I={}));var Bi;(function(t){t.Off="off",t.Messages="messages",t.Compact="compact",t.Verbose="verbose"})(Bi||(w.TraceValues=Bi={}));(function(t){function e(r){if(!A.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})(I||(w.Trace=I={}));var X;(function(t){t.Text="text",t.JSON="json"})(X||(w.TraceFormat=X={}));(function(t){function e(n){return A.string(n)?(n=n.toLowerCase(),n==="json"?t.JSON:t.Text):t.Text}t.fromString=e})(X||(w.TraceFormat=X={}));var tr;(function(t){t.type=new y.NotificationType("$/setTrace")})(tr||(w.SetTraceNotification=tr={}));var It;(function(t){t.type=new y.NotificationType("$/logTrace")})(It||(w.LogTraceNotification=It={}));var Qe;(function(t){t[t.Closed=1]="Closed",t[t.Disposed=2]="Disposed",t[t.AlreadyListening=3]="AlreadyListening"})(Qe||(w.ConnectionErrors=Qe={}));var $e=class t extends Error{constructor(e,n){super(n),this.code=e,Object.setPrototypeOf(this,t.prototype)}};w.ConnectionError=$e;var nr;(function(t){function e(n){let r=n;return r&&A.func(r.cancelUndispatched)}t.is=e})(nr||(w.ConnectionStrategy=nr={}));var Ct;(function(t){function e(n){let r=n;return r&&(r.kind===void 0||r.kind==="id")&&A.func(r.createCancellationTokenSource)&&(r.dispose===void 0||A.func(r.dispose))}t.is=e})(Ct||(w.IdCancellationReceiverStrategy=Ct={}));var rr;(function(t){function e(n){let r=n;return r&&r.kind==="request"&&A.func(r.createCancellationTokenSource)&&(r.dispose===void 0||A.func(r.dispose))}t.is=e})(rr||(w.RequestCancellationReceiverStrategy=rr={}));var Pt;(function(t){t.Message=Object.freeze({createCancellationTokenSource(n){return new Yn.CancellationTokenSource}});function e(n){return Ct.is(n)||rr.is(n)}t.is=e})(Pt||(w.CancellationReceiverStrategy=Pt={}));var Tt;(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&&A.func(r.sendCancellation)&&A.func(r.cleanup)}t.is=e})(Tt||(w.CancellationSenderStrategy=Tt={}));var xt;(function(t){t.Message=Object.freeze({receiver:Pt.Message,sender:Tt.Message});function e(n){let r=n;return r&&Pt.is(r.receiver)&&Tt.is(r.sender)}t.is=e})(xt||(w.CancellationStrategy=xt={}));var Mt;(function(t){function e(n){let r=n;return r&&A.func(r.handleMessage)}t.is=e})(Mt||(w.MessageStrategy=Mt={}));var zi;(function(t){function e(n){let r=n;return r&&(xt.is(r.cancellationStrategy)||nr.is(r.connectionStrategy)||Mt.is(r.messageStrategy))}t.is=e})(zi||(w.ConnectionOptions=zi={}));var ne;(function(t){t[t.New=1]="New",t[t.Listening=2]="Listening",t[t.Closed=3]="Closed",t[t.Disposed=4]="Disposed"})(ne||(ne={}));function Ca(t,e,n,r){let i=n!==void 0?n:w.NullLogger,o=0,a=0,l=0,u="2.0",h,E=new Map,k,M=new Map,$=new Map,C,H=new Ui.LinkedMap,S=new Map,Q=new Set,J=new Map,T=I.Off,Se=X.Text,W,pe=ne.New,Xt=new Je.Emitter,_r=new Je.Emitter,Ir=new Je.Emitter,Cr=new Je.Emitter,Pr=new Je.Emitter,fe=r&&r.cancellationStrategy?r.cancellationStrategy:xt.Message;function Tr(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-"+(++l).toString():"res-"+s.toString()}function Yo(){return"not-"+(++a).toString()}function Xo(s,d){y.Message.isRequest(d)?s.set(Tr(d.id),d):y.Message.isResponse(d)?s.set(Qo(d.id),d):s.set(Yo(),d)}function Zo(s){}function xr(){return pe===ne.Listening}function Mr(){return pe===ne.Closed}function Ie(){return pe===ne.Disposed}function Or(){(pe===ne.New||pe===ne.Listening)&&(pe=ne.Closed,_r.fire(void 0))}function es(s){Xt.fire([s,void 0,void 0])}function ts(s){Xt.fire(s)}t.onClose(Or),t.onError(es),e.onClose(Or),e.onError(ts);function Nr(){C||H.size===0||(C=(0,Wi.default)().timer.setImmediate(()=>{C=void 0,ns()}))}function Lr(s){y.Message.isRequest(s)?is(s):y.Message.isNotification(s)?ss(s):y.Message.isResponse(s)?os(s):as(s)}function ns(){if(H.size===0)return;let s=H.shift();try{let d=r?.messageStrategy;Mt.is(d)?d.handleMessage(s,Lr):Lr(s)}finally{Nr()}}let rs=s=>{try{if(y.Message.isNotification(s)&&s.method===Ye.type.method){let d=s.params.id,p=Tr(d),m=H.get(p);if(y.Message.isRequest(m)){let x=r?.connectionStrategy,D=x&&x.cancelUndispatched?x.cancelUndispatched(m,Zo):void 0;if(D&&(D.error!==void 0||D.result!==void 0)){H.delete(p),J.delete(d),D.id=m.id,tt(D,s.method,Date.now()),e.write(D).catch(()=>i.error("Sending response for canceled message failed."));return}}let N=J.get(d);if(N!==void 0){N.cancel(),Zt(s);return}else Q.add(d)}Xo(H,s)}finally{Nr()}};function is(s){if(Ie())return;function d(_,F,P){let U={jsonrpc:u,id:s.id};_ instanceof y.ResponseError?U.error=_.toJson():U.result=_===void 0?null:_,tt(U,F,P),e.write(U).catch(()=>i.error("Sending response failed."))}function p(_,F,P){let U={jsonrpc:u,id:s.id,error:_.toJson()};tt(U,F,P),e.write(U).catch(()=>i.error("Sending response failed."))}function m(_,F,P){_===void 0&&(_=null);let U={jsonrpc:u,id:s.id,result:_};tt(U,F,P),e.write(U).catch(()=>i.error("Sending response failed."))}ls(s);let N=E.get(s.method),x,D;N&&(x=N.type,D=N.handler);let V=Date.now();if(D||h){let _=s.id??String(Date.now()),F=Ct.is(fe.receiver)?fe.receiver.createCancellationTokenSource(_):fe.receiver.createCancellationTokenSource(s);s.id!==null&&Q.has(s.id)&&F.cancel(),s.id!==null&&J.set(_,F);try{let P;if(D)if(s.params===void 0){if(x!==void 0&&x.numberOfParams!==0){p(new y.ResponseError(y.ErrorCodes.InvalidParams,`Request ${s.method} defines ${x.numberOfParams} params but received none.`),s.method,V);return}P=D(F.token)}else if(Array.isArray(s.params)){if(x!==void 0&&x.parameterStructures===y.ParameterStructures.byName){p(new y.ResponseError(y.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by name but received parameters by position`),s.method,V);return}P=D(...s.params,F.token)}else{if(x!==void 0&&x.parameterStructures===y.ParameterStructures.byPosition){p(new y.ResponseError(y.ErrorCodes.InvalidParams,`Request ${s.method} defines parameters by position but received parameters by name`),s.method,V);return}P=D(s.params,F.token)}else h&&(P=h(s.method,s.params,F.token));let U=P;P?U.then?U.then(K=>{J.delete(_),d(K,s.method,V)},K=>{J.delete(_),K instanceof y.ResponseError?p(K,s.method,V):K&&A.string(K.message)?p(new y.ResponseError(y.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${K.message}`),s.method,V):p(new y.ResponseError(y.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,V)}):(J.delete(_),d(P,s.method,V)):(J.delete(_),m(P,s.method,V))}catch(P){J.delete(_),P instanceof y.ResponseError?d(P,s.method,V):P&&A.string(P.message)?p(new y.ResponseError(y.ErrorCodes.InternalError,`Request ${s.method} failed with message: ${P.message}`),s.method,V):p(new y.ResponseError(y.ErrorCodes.InternalError,`Request ${s.method} failed unexpectedly without providing any details.`),s.method,V)}}else p(new y.ResponseError(y.ErrorCodes.MethodNotFound,`Unhandled method ${s.method}`),s.method,V)}function os(s){if(!Ie())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 d=s.id,p=S.get(d);if(us(s,p),p!==void 0){S.delete(d);try{if(s.error){let m=s.error;p.reject(new y.ResponseError(m.code,m.message,m.data))}else if(s.result!==void 0)p.resolve(s.result);else throw new Error("Should never happen.")}catch(m){m.message?i.error(`Response handler '${p.method}' failed with message: ${m.message}`):i.error(`Response handler '${p.method}' failed unexpectedly.`)}}}}function ss(s){if(Ie())return;let d,p;if(s.method===Ye.type.method){let m=s.params.id;Q.delete(m),Zt(s);return}else{let m=M.get(s.method);m&&(p=m.handler,d=m.type)}if(p||k)try{if(Zt(s),p)if(s.params===void 0)d!==void 0&&d.numberOfParams!==0&&d.parameterStructures!==y.ParameterStructures.byName&&i.error(`Notification ${s.method} defines ${d.numberOfParams} params but received none.`),p();else if(Array.isArray(s.params)){let m=s.params;s.method===Ke.type.method&&m.length===2&&Xn.is(m[0])?p({token:m[0],value:m[1]}):(d!==void 0&&(d.parameterStructures===y.ParameterStructures.byName&&i.error(`Notification ${s.method} defines parameters by name but received parameters by position`),d.numberOfParams!==s.params.length&&i.error(`Notification ${s.method} defines ${d.numberOfParams} params but received ${m.length} arguments`)),p(...m))}else d!==void 0&&d.parameterStructures===y.ParameterStructures.byPosition&&i.error(`Notification ${s.method} defines parameters by position but received parameters by name`),p(s.params);else k&&k(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 Ir.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 d=s;if(A.string(d.id)||A.number(d.id)){let p=d.id,m=S.get(p);m&&m.reject(new Error("The received response has neither a result nor an error property."))}}function he(s){if(s!=null)switch(T){case I.Verbose:return JSON.stringify(s,null,4);case I.Compact:return JSON.stringify(s);default:return}}function cs(s){if(!(T===I.Off||!W))if(Se===X.Text){let d;(T===I.Verbose||T===I.Compact)&&s.params&&(d=`Params: ${he(s.params)}

`),W.log(`Sending request '${s.method} - (${s.id})'.`,d)}else Ce("send-request",s)}function ds(s){if(!(T===I.Off||!W))if(Se===X.Text){let d;(T===I.Verbose||T===I.Compact)&&(s.params?d=`Params: ${he(s.params)}

`:d=`No parameters provided.

`),W.log(`Sending notification '${s.method}'.`,d)}else Ce("send-notification",s)}function tt(s,d,p){if(!(T===I.Off||!W))if(Se===X.Text){let m;(T===I.Verbose||T===I.Compact)&&(s.error&&s.error.data?m=`Error data: ${he(s.error.data)}

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

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

`)),W.log(`Sending response '${d} - (${s.id})'. Processing request took ${Date.now()-p}ms`,m)}else Ce("send-response",s)}function ls(s){if(!(T===I.Off||!W))if(Se===X.Text){let d;(T===I.Verbose||T===I.Compact)&&s.params&&(d=`Params: ${he(s.params)}

`),W.log(`Received request '${s.method} - (${s.id})'.`,d)}else Ce("receive-request",s)}function Zt(s){if(!(T===I.Off||!W||s.method===It.type.method))if(Se===X.Text){let d;(T===I.Verbose||T===I.Compact)&&(s.params?d=`Params: ${he(s.params)}

`:d=`No parameters provided.

`),W.log(`Received notification '${s.method}'.`,d)}else Ce("receive-notification",s)}function us(s,d){if(!(T===I.Off||!W))if(Se===X.Text){let p;if((T===I.Verbose||T===I.Compact)&&(s.error&&s.error.data?p=`Error data: ${he(s.error.data)}

`:s.result?p=`Result: ${he(s.result)}

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

`)),d){let m=s.error?` Request failed: ${s.error.message} (${s.error.code}).`:"";W.log(`Received response '${d.method} - (${s.id})' in ${Date.now()-d.timerStart}ms.${m}`,p)}else W.log(`Received response ${s.id} without active response promise.`,p)}else Ce("receive-response",s)}function Ce(s,d){if(!W||T===I.Off)return;let p={isLSPMessage:!0,type:s,message:d,timestamp:Date.now()};W.log(p)}function We(){if(Mr())throw new $e(Qe.Closed,"Connection is closed.");if(Ie())throw new $e(Qe.Disposed,"Connection is disposed.")}function ps(){if(xr())throw new $e(Qe.AlreadyListening,"Connection is already listening")}function fs(){if(!xr())throw new Error("Call listen() first.")}function Ue(s){return s===void 0?null:s}function Fr(s){if(s!==null)return s}function Ar(s){return s!=null&&!Array.isArray(s)&&typeof s=="object"}function en(s,d){switch(s){case y.ParameterStructures.auto:return Ar(d)?Fr(d):[Ue(d)];case y.ParameterStructures.byName:if(!Ar(d))throw new Error("Received parameters by name but param is not an object literal.");return Fr(d);case y.ParameterStructures.byPosition:return[Ue(d)];default:throw new Error(`Unknown parameter structure ${s.toString()}`)}}function Dr(s,d){let p,m=s.numberOfParams;switch(m){case 0:p=void 0;break;case 1:p=en(s.parameterStructures,d[0]);break;default:p=[];for(let N=0;N<d.length&&N<m;N++)p.push(Ue(d[N]));if(d.length<m)for(let N=d.length;N<m;N++)p.push(null);break}return p}let Pe={sendNotification:(s,...d)=>{We();let p,m;if(A.string(s)){p=s;let x=d[0],D=0,V=y.ParameterStructures.auto;y.ParameterStructures.is(x)&&(D=1,V=x);let _=d.length,F=_-D;switch(F){case 0:m=void 0;break;case 1:m=en(V,d[D]);break;default:if(V===y.ParameterStructures.byName)throw new Error(`Received ${F} parameters for 'by Name' notification parameter structure.`);m=d.slice(D,_).map(P=>Ue(P));break}}else{let x=d;p=s.method,m=Dr(s,x)}let N={jsonrpc:u,method:p,params:m};return ds(N),e.write(N).catch(x=>{throw i.error("Sending notification failed."),x})},onNotification:(s,d)=>{We();let p;return A.func(s)?k=s:d&&(A.string(s)?(p=s,M.set(s,{type:void 0,handler:d})):(p=s.method,M.set(s.method,{type:s,handler:d}))),{dispose:()=>{p!==void 0?M.delete(p):k=void 0}}},onProgress:(s,d,p)=>{if($.has(d))throw new Error(`Progress handler for token ${d} already registered`);return $.set(d,p),{dispose:()=>{$.delete(d)}}},sendProgress:(s,d,p)=>Pe.sendNotification(Ke.type,{token:d,value:p}),onUnhandledProgress:Cr.event,sendRequest:(s,...d)=>{We(),fs();let p,m,N;if(A.string(s)){p=s;let _=d[0],F=d[d.length-1],P=0,U=y.ParameterStructures.auto;y.ParameterStructures.is(_)&&(P=1,U=_);let K=d.length;Yn.CancellationToken.is(F)&&(K=K-1,N=F);let oe=K-P;switch(oe){case 0:m=void 0;break;case 1:m=en(U,d[P]);break;default:if(U===y.ParameterStructures.byName)throw new Error(`Received ${oe} parameters for 'by Name' request parameter structure.`);m=d.slice(P,K).map(hs=>Ue(hs));break}}else{let _=d;p=s.method,m=Dr(s,_);let F=s.numberOfParams;N=Yn.CancellationToken.is(_[F])?_[F]:void 0}let x=o++,D;N&&(D=N.onCancellationRequested(()=>{let _=fe.sender.sendCancellation(Pe,x);return _===void 0?(i.log(`Received no promise from cancellation strategy when cancelling id ${x}`),Promise.resolve()):_.catch(()=>{i.log(`Sending cancellation messages for id ${x} failed`)})}));let V={jsonrpc:u,id:x,method:p,params:m};return cs(V),typeof fe.sender.enableCancellation=="function"&&fe.sender.enableCancellation(V),new Promise(async(_,F)=>{let P=oe=>{_(oe),fe.sender.cleanup(x),D?.dispose()},U=oe=>{F(oe),fe.sender.cleanup(x),D?.dispose()},K={method:p,timerStart:Date.now(),resolve:P,reject:U};try{S.set(x,K),await e.write(V)}catch(oe){throw S.delete(x),K.reject(new y.ResponseError(y.ErrorCodes.MessageWriteError,oe.message?oe.message:"Unknown reason")),i.error("Sending request failed."),oe}})},onRequest:(s,d)=>{We();let p=null;return er.is(s)?(p=void 0,h=s):A.string(s)?(p=null,d!==void 0&&(p=s,E.set(s,{handler:d,type:void 0}))):d!==void 0&&(p=s.method,E.set(s.method,{type:s,handler:d})),{dispose:()=>{p!==null&&(p!==void 0?E.delete(p):h=void 0)}}},hasPendingResponse:()=>S.size>0,trace:async(s,d,p)=>{let m=!1,N=X.Text;p!==void 0&&(A.boolean(p)?m=p:(m=p.sendNotification||!1,N=p.traceFormat||X.Text)),T=s,Se=N,T===I.Off?W=void 0:W=d,m&&!Mr()&&!Ie()&&await Pe.sendNotification(tr.type,{value:I.toString(s)})},onError:Xt.event,onClose:_r.event,onUnhandledNotification:Ir.event,onDispose:Pr.event,end:()=>{e.end()},dispose:()=>{if(Ie())return;pe=ne.Disposed,Pr.fire(void 0);let s=new y.ResponseError(y.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let d of S.values())d.reject(s);S=new Map,J=new Map,Q=new Set,H=new Ui.LinkedMap,A.func(e.dispose)&&e.dispose(),A.func(t.dispose)&&t.dispose()},listen:()=>{We(),ps(),pe=ne.Listening,t.listen(rs)},inspect:()=>{(0,Wi.default)().console.log("inspect")}};return Pe.onNotification(It.type,s=>{if(T===I.Off||!W)return;let d=T===I.Verbose||T===I.Compact;W.log(s.message,d?s.verbose:void 0)}),Pe.onNotification(Ke.type,s=>{let d=$.get(s.token);d?d(s.value):Cr.fire(s)}),Pe}w.createMessageConnection=Ca});var Ot=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 O=Tn();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return O.Message}});Object.defineProperty(c,"RequestType",{enumerable:!0,get:function(){return O.RequestType}});Object.defineProperty(c,"RequestType0",{enumerable:!0,get:function(){return O.RequestType0}});Object.defineProperty(c,"RequestType1",{enumerable:!0,get:function(){return O.RequestType1}});Object.defineProperty(c,"RequestType2",{enumerable:!0,get:function(){return O.RequestType2}});Object.defineProperty(c,"RequestType3",{enumerable:!0,get:function(){return O.RequestType3}});Object.defineProperty(c,"RequestType4",{enumerable:!0,get:function(){return O.RequestType4}});Object.defineProperty(c,"RequestType5",{enumerable:!0,get:function(){return O.RequestType5}});Object.defineProperty(c,"RequestType6",{enumerable:!0,get:function(){return O.RequestType6}});Object.defineProperty(c,"RequestType7",{enumerable:!0,get:function(){return O.RequestType7}});Object.defineProperty(c,"RequestType8",{enumerable:!0,get:function(){return O.RequestType8}});Object.defineProperty(c,"RequestType9",{enumerable:!0,get:function(){return O.RequestType9}});Object.defineProperty(c,"ResponseError",{enumerable:!0,get:function(){return O.ResponseError}});Object.defineProperty(c,"ErrorCodes",{enumerable:!0,get:function(){return O.ErrorCodes}});Object.defineProperty(c,"NotificationType",{enumerable:!0,get:function(){return O.NotificationType}});Object.defineProperty(c,"NotificationType0",{enumerable:!0,get:function(){return O.NotificationType0}});Object.defineProperty(c,"NotificationType1",{enumerable:!0,get:function(){return O.NotificationType1}});Object.defineProperty(c,"NotificationType2",{enumerable:!0,get:function(){return O.NotificationType2}});Object.defineProperty(c,"NotificationType3",{enumerable:!0,get:function(){return O.NotificationType3}});Object.defineProperty(c,"NotificationType4",{enumerable:!0,get:function(){return O.NotificationType4}});Object.defineProperty(c,"NotificationType5",{enumerable:!0,get:function(){return O.NotificationType5}});Object.defineProperty(c,"NotificationType6",{enumerable:!0,get:function(){return O.NotificationType6}});Object.defineProperty(c,"NotificationType7",{enumerable:!0,get:function(){return O.NotificationType7}});Object.defineProperty(c,"NotificationType8",{enumerable:!0,get:function(){return O.NotificationType8}});Object.defineProperty(c,"NotificationType9",{enumerable:!0,get:function(){return O.NotificationType9}});Object.defineProperty(c,"ParameterStructures",{enumerable:!0,get:function(){return O.ParameterStructures}});var ir=Mn();Object.defineProperty(c,"LinkedMap",{enumerable:!0,get:function(){return ir.LinkedMap}});Object.defineProperty(c,"LRUCache",{enumerable:!0,get:function(){return ir.LRUCache}});Object.defineProperty(c,"Touch",{enumerable:!0,get:function(){return ir.Touch}});var Pa=Oi();Object.defineProperty(c,"Disposable",{enumerable:!0,get:function(){return Pa.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=St();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 or=Ai();Object.defineProperty(c,"MessageReader",{enumerable:!0,get:function(){return or.MessageReader}});Object.defineProperty(c,"AbstractMessageReader",{enumerable:!0,get:function(){return or.AbstractMessageReader}});Object.defineProperty(c,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return or.ReadableStreamMessageReader}});var sr=qi();Object.defineProperty(c,"MessageWriter",{enumerable:!0,get:function(){return sr.MessageWriter}});Object.defineProperty(c,"AbstractMessageWriter",{enumerable:!0,get:function(){return sr.AbstractMessageWriter}});Object.defineProperty(c,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return sr.WriteableStreamMessageWriter}});var Ta=Hi();Object.defineProperty(c,"AbstractMessageBuffer",{enumerable:!0,get:function(){return Ta.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 xa=ve();c.RAL=xa.default});var Zi=j(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});var Yi=de("util"),ue=Ot(),Nt=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)}};Nt.emptyBuffer=Buffer.allocUnsafe(0);var ar=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))}},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))}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 Nt(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 ar(t),asWritableStream:t=>new cr(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 dr(){return Xi}(function(t){function e(){ue.RAL.install(Xi)}t.install=e})(dr||(dr={}));lr.default=dr});var no=j(R=>{"use strict";var Ma=R&&R.__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]})),Oa=R&&R.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Ma(e,t,n)};Object.defineProperty(R,"__esModule",{value:!0});R.createMessageConnection=R.createServerSocketTransport=R.createClientSocketTransport=R.createServerPipeTransport=R.createClientPipeTransport=R.generateRandomPipeName=R.StreamMessageWriter=R.StreamMessageReader=R.SocketMessageWriter=R.SocketMessageReader=R.PortMessageWriter=R.PortMessageReader=R.IPCMessageWriter=R.IPCMessageReader=void 0;var Ve=Zi();Ve.default.install();var eo=de("path"),Na=de("os"),La=de("crypto"),At=de("net"),Z=Ot();Oa(Ot(),R);var ur=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))}};R.IPCMessageReader=ur;var pr=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(){}};R.IPCMessageWriter=pr;var fr=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)}};R.PortMessageReader=fr;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(){}};R.PortMessageWriter=hr;var Re=class extends Z.ReadableStreamMessageReader{constructor(e,n="utf-8"){super((0,Ve.default)().stream.asReadableStream(e),n)}};R.SocketMessageReader=Re;var _e=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n),this.socket=e}dispose(){super.dispose(),this.socket.destroy()}};R.SocketMessageWriter=_e;var Lt=class extends Z.ReadableStreamMessageReader{constructor(e,n){super((0,Ve.default)().stream.asReadableStream(e),n)}};R.StreamMessageReader=Lt;var Ft=class extends Z.WriteableStreamMessageWriter{constructor(e,n){super((0,Ve.default)().stream.asWritableStream(e),n)}};R.StreamMessageWriter=Ft;var to=process.env.XDG_RUNTIME_DIR,Fa=new Map([["linux",107],["darwin",103]]);function Aa(){let t=(0,La.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(Na.tmpdir(),`vscode-${t}.sock`);let n=Fa.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}R.generateRandomPipeName=Aa;function Da(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,At.createServer)(l=>{a.close(),n([new Re(l,e),new _e(l,e)])});a.on("error",o),a.listen(t,()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}R.createClientPipeTransport=Da;function $a(t,e="utf-8"){let n=(0,At.createConnection)(t);return[new Re(n,e),new _e(n,e)]}R.createServerPipeTransport=$a;function Va(t,e="utf-8"){let n,r=new Promise((i,o)=>{n=i});return new Promise((i,o)=>{let a=(0,At.createServer)(l=>{a.close(),n([new Re(l,e),new _e(l,e)])});a.on("error",o),a.listen(t,"127.0.0.1",()=>{a.removeListener("error",o),i({onConnected:()=>r})})})}R.createClientSocketTransport=Va;function ja(t,e="utf-8"){let n=(0,At.createConnection)(t,"127.0.0.1");return[new Re(n,e),new _e(n,e)]}R.createServerSocketTransport=ja;function qa(t){let e=t;return e.read!==void 0&&e.addListener!==void 0}function Ha(t){let e=t;return e.write!==void 0&&e.addListener!==void 0}function Wa(t,e,n,r){n||(n=Z.NullLogger);let i=qa(t)?new Lt(t):t,o=Ha(e)?new Ft(e):e;return Z.ConnectionStrategy.is(r)&&(r={connectionStrategy:r}),(0,Z.createMessageConnection)(i,o,n,r)}R.createMessageConnection=Wa});var Dt=j((Al,ro)=>{"use strict";ro.exports=no()});import{join as yd}from"node:path";import*as lt from"os";import rn from"node:path";import{fileURLToPath as Qs}from"node:url";var rt=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 ---")}},g=new rt;import{createRequire as $s}from"node:module";import{platform as Vs,type as js}from"node:os";import{join as pi,resolve as qs}from"node:path";import{fileURLToPath as Hs}from"node:url";var at=nt(li(),1);function ct(t={}){return(t.platform??process.platform)!=="linux"?"gnu":(t.detectLibcFamily??at.familySync)()===at.MUSL?"musl":"gnu"}function ui(t=process.platform,e){let n=e??(t==="linux"?ct():"gnu");return t==="linux"&&n==="musl"?"linuxmusl":t}function Ws(){let t=hi(),e=t==="linux"?ct({platform:t}):"gnu";return`${ui(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}-${ct({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 gi(t,e){let n=Ws(),r=`${t}.node`,i=`${t}.${Us()}.node`,o=[];for(let l of e){let u=qs(l),h=pi(u,"prebuilds",n,r),E=fi(h);if(E.ok)return E.value;o.push({path:h,err:E.err});let k=pi(u,i),M=fi(k);if(M.ok)return M.value;o.push({path:k,err:M.err})}let a=o.map(l=>`  ${l.path}: ${Bs(l.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 fi(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 dt="COPILOT_RUNTIME_OOP";function mi(){return process.env[dt]==="1"||process.env[dt]==="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`,l=class{__provider;__handle;constructor(...u){let h=u[u.length-1],E=u.slice(0,u.length-1);this.__provider=h,this.__handle=h.call(a,E),h.trackExternal(this.__handle)}};Object.defineProperty(l,"name",{value:i.name}),l.__fromHandle=function(u,h){let E=Object.create(l.prototype);return E.__provider=u,E.__handle=h,u.trackExternal(h),E};for(let u of i.methods){if(u.js_name==="constructor")continue;let h=n.has(u.ret),E=u.rust_name,k=(M,$)=>h?e[u.ret].__fromHandle(M.__provider,$):$;if(u.is_getter){Object.defineProperty(l.prototype,u.js_name,{configurable:!0,get(){return u.is_async?(async()=>k(this,await this.__provider.callAsync(E,[this.__handle])))():k(this,this.__provider.call(E,[this.__handle]))}});continue}l.prototype[u.js_name]=u.is_async?async function(...M){return k(this,await this.__provider.callAsync(E,[this.__handle,...M]))}:function(...M){return k(this,this.__provider.call(E,[this.__handle,...M]))}}r[i.name]=l,e[i.name]=l}return r}function vi(){let{bindClasses:t,connectFromEnvSync:e,createSyncBinding:n,SOCKET_ENV:r}=Js()("napi-oop-runtime");if(!process.env[r])throw new Error(`${dt} 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[dt],!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(S=>S.name)),l=o.functions.filter(S=>S.is_async).map(S=>S.js_name),u=o.functions.filter(S=>S.ret==="ExternalObject").map(S=>S.js_name),h={};for(let S of o.functions)h[S.js_name]=S.rust_name;let E=n(i,l,u,h),k={},M=Ks(o,k),$={};for(let S of o.functions)a.has(S.ret)&&($[S.js_name]={cls:k[S.ret],isAsync:S.is_async,rustName:S.rust_name});let C=t(E,i,M,$),H=new Map((o.constants??[]).map(S=>[S.js_name,S.value]));return H.size===0?C:new Proxy(C,{get(S,Q,J){return typeof Q=="string"&&H.has(Q)?H.get(Q):Reflect.get(S,Q,J)},has(S,Q){return typeof Q=="string"&&H.has(Q)?!0:Reflect.has(S,Q)}})}var yi="__copilotRuntimeAddon__";function Ys(){let t=globalThis,e=t[yi];return e||(e={addon:null},t[yi]=e),e}function Ei(){let t=Ys();if(t.addon)return t.addon;if(mi()){g.debug("[runtimeBridge] out-of-process mode: skipping the in-process runtime .node; all native calls are remoted to the Rust provider");let r=vi();return t.addon=r,r}g.debug("[runtimeBridge] in-process mode: loading the native runtime .node addon into this process");let e=rn.dirname(Qs(import.meta.url)),n=gi("runtime",[e,rn.resolve(e,".."),rn.resolve(e,"..","..","runtime")]);return t.addon=n,n}var Xs;function Me(){return Xs??=Ei()}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 q=new Proxy({},{get:(t,e)=>ea(Me(),e),has:(t,e)=>Reflect.has(Me(),e),set:(t,e,n)=>Reflect.set(Me(),e,n),ownKeys:()=>Reflect.ownKeys(Me()),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(Me(),e),defineProperty:(t,e,n)=>Reflect.defineProperty(Me(),e,n)});function Si(t,e){return q.resolveCopilotHome(t?.configDir??null,process.env.COPILOT_HOME??null,lt.homedir())}var zd=lt.tmpdir();import{constants as ia}from"fs";import{access as oa,appendFile as sa,mkdir as aa}from"fs/promises";import{dirname as ca}from"path";function ut(t){let e=[],n=!1,r=()=>{n||(e.push(...t()),n=!0)};return new Proxy(e,{get(i,o,a){r();let l=Reflect.get(i,o,a);return typeof l!="function"?l:(...u)=>Reflect.apply(l,i,u)},set(i,o,a,l){return r(),Reflect.set(i,o,a,l)},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 bi=ut(()=>q.settingsSecretEnvVarNames()),Yd=ut(()=>q.settingsEnvVarNamesToFilterFromShellsAndMcp()),Xd=ut(()=>q.settingsEnvVarNamesToFilterFromShellsOnly()),Zd=ut(()=>q.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=q.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}import*as Ri from"process";function Be(t){let e=Ri.env[t];if(e&&e.trim()!=="")return e}var na=["GITHUB_COPILOT_OIDC_","GITHUB_AGENTIC_APP_OIDC_"];var _i=new FinalizationRegistry(t=>{try{q.secretFilterDispose(t)}catch{}}),pt=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=q.secretFilterCreate(),_i.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:q.secretFilterIsAdditionalSecretValue(this.handle,e)}getAdditionalSecretValues(){return new Set(this.disposed?[]:q.secretFilterGetAdditionalSecretValues(this.handle))}getRawAdditionalSecretValues(){return new Set(this.disposed?[]:q.secretFilterGetRawAdditionalSecretValues(this.handle))}addSecretValues(e){let n=this.disposed?0:q.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}:q.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:q.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))}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,_i.unregister(this.finalizerToken),q.secretFilterDispose(this.handle),t.singleton===this&&(t.singleton=void 0))}invalidateSourceSecrets(){this.sourceSecretsDirty=!0}ensureSourceSecretsSynced(){this.disposed||!this.sourceSecretsDirty||(q.secretFilterSetSourceSecretValues(this.handle,this.getSourceSecretValues()),this.sourceSecretsDirty=!1)}getSourceSecretValues(){let e=new Set;for(let n of bi){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 Ii(...t){let e=new Set(["DEBUG","COPILOT_AGENT_DEBUG",...t]);for(let n of e)if(process.env[n]==="1"||process.env[n]?.toLocaleLowerCase()==="true")return!0;return!1}var ft=class{logLevel;debugEnvironmentVariables;secretFilter=pt.getInstance();constructor(e,n){e===void 0?Ii(...n??[])?this.logLevel=4:this.logLevel=3:this.logLevel=e,this.debugEnvironmentVariables=n}filterSecrets(e){return typeof e=="string"?this.secretFilter.filterSecrets(e):this.secretFilter.filterSecrets(e)}shouldLog(e){return this.logLevel===void 0||this.logLevel>=e}isDebug(){return Ii(...this.debugEnvironmentVariables??[])}};var ht=class{constructor(e,n){this.writeFn=e;this.onError=n}writeFn;onError;pendingData="";drainScheduled=!1;writeQueue=Promise.resolve();_writeCount=0;append(e){try{this.pendingData+=e}catch(n){this.onError?.(n);return}this.drainScheduled||(this.drainScheduled=!0,this.writeQueue=this.writeQueue.then(()=>this.drain()))}enqueue(e){this.writeQueue=this.writeQueue.then(async()=>{try{await e()}catch(n){this.onError?.(n)}})}async flush(){await this.writeQueue}reset(){this.pendingData="",this.drainScheduled=!1,this._writeCount=0}get stats(){return{writeCount:this._writeCount,pendingLength:this.pendingData.length,drainScheduled:this.drainScheduled}}async drain(){for(;this.pendingData.length>0;){let e=this.pendingData;this.pendingData="";try{await this.writeFn(e),this._writeCount++}catch(n){if(this.onError?.(n),this.pendingData.length>0)continue;break}}this.drainScheduled=!1}};var gt=class extends ft{constructor(n,r,i){super(r,i);this.filePath=n;this.queue=new ht(o=>sa(this.filePath,o)),this.queue.enqueue(()=>da(ca(this.filePath)))}filePath;queue;get writeQueue(){return this.queue.flush()}outputPath(){return this.filePath}log(n){this.write("LOG",n)}debug(n){super.shouldLog(4)&&this.write("DEBUG",this.filterSecrets(n).toString())}info(n){super.shouldLog(3)&&this.write("INFO",this.filterSecrets(n).toString())}notice(n){super.shouldLog(2)&&this.write("NOTICE",this.filterSecrets(n).toString())}warning(n){super.shouldLog(2)&&this.write("WARNING",this.filterSecrets(n).toString())}error(n){super.shouldLog(1)&&this.write("ERROR",this.filterSecrets(n).toString())}startGroup(n,r){super.shouldLog(r||3)&&this.write("START-GROUP",n)}endGroup(n){super.shouldLog(n||3)&&this.write("END-GROUP","")}get stats(){return this.queue.stats}write(n,r){let o=`${new Date().toISOString()} [${n}] ${r}
`;this.queue.append(o)}writeLog(n,r){switch(n){case"debug":this.debug(r);break;case"info":this.info(r);break;case"warning":this.warning(r);break;case"error":this.error(r);break;default:{let i=n;break}}return this.writeQueue}};async function da(t){try{await oa(t,ia.F_OK)}catch{await aa(t,{recursive:!0})}}var oo=nt(Dt(),1);var io=["setEnabled","selectModel","downloadModel","cancelDownload","deleteModel","installRuntime","refreshCatalog","openSession","finishSession","acknowledgeOperationError"];function Ba(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{},type:`rpc:${t}`,connectionId:n,requestId:r}}var $t=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(Ba(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 Vt=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 $t({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 za(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 b(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 za(e)}var je=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="VoiceBackendError"}code};function gr(t){return t.code!==void 0?new je(t.message,t.code):new Error(t.message)}function jt(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=b(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 mr=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 mr(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 Ga="github-copilot-cli",Ja="automatic-speech-recognition",Ka={AzureCatalogFilter:"'',test"},uo=1e4,po=2e3,qt=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){g.error(`[voice-engine] checkRuntime failed: ${b(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)Qa(a)&&co.has(a.alias)&&i.push(Xa(a));this.events.submit({type:"internal:catalogFetched",generation:e,models:i})}catch(n){let r=b(n);g.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=b(n);g.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(l){g.warning(`[voice-engine] download progress callback threw: ${b(l)}`)}},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=b(i);g.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&&g.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=b(r);g.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=b(r);g.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 g.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 g.error(`[voice-engine] openSttSession(${e}) failed: ${b(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=>g.warning(`[voice-engine] orphan teardown(${e}) failed: ${b(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){g.error(`[voice-engine] runEnd(${n}) failed: ${b(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=>g.warning(`[voice-engine] teardown(${n}) failed: ${b(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){g.warning(`[voice-engine] runCancel(${e.sessionId}) teardown: ${b(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,g.error(`[voice-engine] session(${e.sessionId}) failed: ${b(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=>g.warning(`[voice-engine] failSession teardown: ${b(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=Ya(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=>{g.error(`[voice-engine] dispose: variant.unload failed: ${b(n)}`)})}}}async runDelete(e){try{(await this.getVariant(e)).removeFromCache()}catch(n){g.error(`[voice-engine] deleteModel '${e}' failed: ${b(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:Ga,libraryPath:e.corePath,additionalSettings:{...Ka}}))}};function Qa(t){return t.info.task===Ja}function Ya(t){return t.content?.[0]?.text??""}function Xa(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 Za=1600,ec=15,fo=-1,ho=150,Ht=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){if(this.disposed)return Promise.resolve({ok:!1,subreason:"cancelled"});let n=this.state;switch(n.tag){case"idle":return this.beginStart(e,void 0);case"stopping":return this.beginStart(e,n.teardown);case"starting":case"active":return g.error(`[voice-mic] openForSession(${e}) while ${n.tag} for session ${n.sessionId} \u2014 engine contract violation`),Promise.resolve({ok:!1,subreason:"in-use"});default:return n}}beginStart(e,n){let r,i=new Promise(l=>{r=l}),o={stopped:!1,commitDrain:!1,resolveOpen:r},a=(async()=>{n&&await n.catch(()=>{}),await this.runStart(e,fo,o)})();return this.state={tag:"starting",sessionId:e,deviceId:fo,cancel:o,startTask:a},i}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,re(()=>i.stop())):r.commitDrain=!0;let a=(async()=>{e==="commit"&&(await Promise.race([o,mo(ho)]).catch(()=>{}),r.stopped=!0,re(()=>i.stop())),await Promise.race([o,mo(ho)]).catch(()=>{}),re(()=>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,re(()=>e.recorder.stop()),await e.loop.catch(()=>{}),re(()=>e.recorder.release()),this.state={tag:"idle"};return}case"stopping":{await e.teardown.catch(()=>{}),this.state={tag:"idle"};return}default:return e}}async runStart(e,n,r){if(r.stopped||this.disposed){this.exitCancelled(r);return}let i;try{i=await this.pvRecorderLoader()}catch(l){g.error(`[voice-mic] pvrecorder-node load failed: ${b(l)}`),this.failOpen(r,"hardware-error");return}if(r.stopped||this.disposed){this.exitCancelled(r);return}let o;try{o=new i.PvRecorder(Za,n,ec),o.start()}catch(l){if(o!==void 0){let u=o;re(()=>u.stop()),re(()=>u.release())}this.failOpen(r,go(l));return}if(r.stopped||this.disposed){re(()=>o.stop()),re(()=>o.release()),this.exitCancelled(r);return}let a=this.runReadLoop(o,e,r);this.state={tag:"active",sessionId:e,deviceId:n,cancel:r,recorder:o,loop:a},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"}),re(()=>e.stop()),re(()=>e.release());let l=go(a);g.error(`[voice-mic] read loop failed (${l}): ${b(a)}`),this.disposed||this.events.submit({type:"internal:micError",sessionId:n,subreason:l});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 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 mo(t){return new Promise(e=>setTimeout(e,t))}function re(t){try{t()}catch{}}function tc(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}}function nc(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 Wt(t,e){t.enabled=e.clientEnabled}function qe(t,e){return t.models.find(n=>n.variantId===e)}function vo(t,e){let n=qe(t,e);return!!n&&(n.inCatalog||n.cached)}function yo(t,e){let n=qe(t,e);return!!n&&n.cached}function vr(t){return t.currentSession!==null}function rc(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 Ut(t,e){return t.generations.downloadByVariant.get(e)??0}function ic(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}),ic(i,n,r),e.currentSession=null,t.session=null)}function oc(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&&vo(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(yo(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 Eo(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=tc(t),i=nc(e),a=sc(r,i,n,[]);return oc(a.snapshot,a.internal,a.effects),rc(a.snapshot,a.internal),a}function sc(t,e,n,r){switch(n.type){case"boot":return ac(t,e,n,r);case"shutdown":return cc(t,e,r);case"rpc:setEnabled":return dc(t,e,n,r);case"rpc:selectModel":return lc(t,e,n,r);case"rpc:downloadModel":return uc(t,e,n,r);case"rpc:cancelDownload":return pc(t,e,n,r);case"rpc:deleteModel":return fc(t,e,n,r);case"rpc:installRuntime":return hc(t,e,n,r);case"rpc:refreshCatalog":return gc(t,e,n,r);case"rpc:openSession":return mc(t,e,n,r);case"rpc:finishSession":return vc(t,e,n,r);case"rpc:acknowledgeOperationError":return yc(t,e,n,r);case"internal:catalogFetched":return Ec(t,e,n,r);case"internal:catalogFetchFailed":return wc(t,e,n,r);case"internal:runtimeChecked":return Sc(t,e,n,r);case"internal:runtimeInstalled":return bc(t,e,n,r);case"internal:runtimeInstallFailed":return kc(t,e,n,r);case"internal:modelDownloadProgress":return Rc(t,e,n,r);case"internal:modelDownloaded":return _c(t,e,n,r);case"internal:modelDownloadCancelled":return Ic(t,e,n,r);case"internal:modelDownloadFailed":return Cc(t,e,n,r);case"internal:modelLoaded":return Pc(t,e,n,r);case"internal:modelLoadFailed":return Tc(t,e,n,r);case"internal:modelUnloaded":return xc(t,e,n,r);case"internal:modelUnloadFailed":return Mc(t,e,n,r);case"internal:micError":return Fc(t,e,n,r);case"internal:sessionWarmed":return Oc(t,e,n,r);case"internal:sessionWarmupFailed":return Nc(t,e,n,r);case"internal:sttFinal":return Ac(t,e,n,r);case"internal:sttError":return Dc(t,e,n,r);case"client:disconnected":return $c(t,e,n,r)}}function f(t,e,n){return{snapshot:t,internal:e,effects:n}}function ac(t,e,n,r){e.clientEnabled=n.bootEnabled,Wt(t,e),t.selectedTarget=n.bootSelectedModel,t.state={kind:"starting"};let i=++e.generations.runtimeCheck;return r.push({type:"checkRuntime",generation:i}),f(t,e,r)}function cc(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"},f(t,e,n)}function dc(t,e,n,r){let i=e.clientEnabled;e.clientEnabled=n.enabled,Wt(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}),f(t,e,r)}function lc(t,e,n,r){return Eo(t.state)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(t,e,r)):vr(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(t,e,r)):vo(t,n.variantId)?(e.clientEnabled=!0,Wt(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}),f(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}),f(t,e,r))):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-not-found",variantId:n.variantId}}),f(t,e,r))}function uc(t,e,n,r){if(Eo(t.state))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(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}}),f(t,e,r);if(yo(t,n.variantId))return r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:void 0}),f(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}),f(t,e,r)}function pc(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}),f(t,e,r)}function fc(t,e,n,r){if(t.inFlightDownloads.some(E=>E.variantId===n.variantId))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"model-in-use"}}),f(t,e,r);if(n.variantId===t.selectedTarget&&vr(e))return r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(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"}}),f(t,e,r);let a=qe(t,n.variantId),l=o.kind==="loaded"&&o.variantId===n.variantId,u=n.variantId===t.selectedTarget,h=t.state.kind==="model-failed"&&t.state.variantId===n.variantId;return l?e.pendingDelete={variantId:n.variantId}:(r.push({type:"deleteModel",variantId:n.variantId}),a&&(a.cached=!1)),(u||h)&&(t.selectedTarget=null,e.clientEnabled=!1,Wt(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}),f(t,e,r)}function hc(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"}}),f(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}),f(t,e,r)}function gc(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}),f(t,e,r)}function mc(t,e,n,r){return t.enabled?vr(e)?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"session-in-use"}}),f(t,e,r)):t.selectedTarget?t.state.kind!=="ready"?(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"runtime-not-ready"}}),f(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}),f(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"invalid-state"}}),f(t,e,r)):(r.push({type:"replyReject",connectionId:n.connectionId,requestId:n.requestId,reason:{code:"engine-disabled"}}),f(t,e,r))}function vc(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}),f(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"}}),f(t,e,r)):i!==null&&i.pendingFinishReply?(r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"lost",reason:"not-ready"}}),f(t,e,r)):(i!==null&&(i.pendingFinishReply={connectionId:n.connectionId,requestId:n.requestId}),r.push({type:"commitSession",sessionId:n.sessionId}),f(t,e,r)):(ie(t,e,{kind:"discarded"},r),r.push({type:"replyResolve",connectionId:n.connectionId,requestId:n.requestId,result:{kind:"discarded"}}),f(t,e,r))}function yc(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}),f(t,e,r)}function Ec(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"})),f(t,e,r)}function wc(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"})),f(t,e,r)}function Sc(t,e,n,r){if(n.generation!==e.generations.runtimeCheck||t.state.kind!=="starting")return f(t,e,r);if(n.cacheState!=="installed")return t.state={kind:"runtime-missing",cacheState:n.cacheState},f(t,e,r);t.state={kind:"fetching-catalog"},t.catalogStatus="fetching";let i=++e.generations.catalogFetch;return r.push({type:"fetchCatalog",generation:i}),f(t,e,r)}function bc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return f(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 f(t,e,r)}function kc(t,e,n,r){if(n.generation!==e.generations.runtimeInstall)return f(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}),f(t,e,r)}function Rc(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return f(t,e,r);let i={type:"modelDownloadProgress",variantId:n.variantId,percent:n.percent};return r.push({type:"broadcast",event:i}),f(t,e,r)}function _c(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return f(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}),f(t,e,r)}function Ic(t,e,n,r){return n.generation!==Ut(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"})),f(t,e,r)}function Cc(t,e,n,r){if(n.generation!==Ut(e,n.variantId))return f(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}),f(t,e,r)}function Pc(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}),f(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),f(t,e,r))}function Tc(t,e,n,r){let i=e.modelLoad;if(i.kind!=="loading"||i.generation!==n.generation||i.variantId!==n.variantId)return f(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}),f(t,e,r)}function xc(t,e,n,r){let i=e.modelLoad;if(i.kind!=="unloading"||i.variantId!==n.variantId)return f(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 f(t,e,r)}function Mc(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}),f(t,e,r)}function Oc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||i.status==="opening"&&(i.status="active"),f(t,e,r)}function Nc(t,e,n,r){let i=e.currentSession;return!i||i.id!==n.sessionId||(Lc(i.ownerConnectionId,n.sessionId,n.failure,r),ie(t,e,{kind:"lost",reason:n.failure.side==="mic"?"mic-error":"stt-error"},r)),f(t,e,r)}function Lc(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 Fc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(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),f(t,e,r)}function Ac(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(t,e,r);let o=i.pendingFinishReply?{kind:"committed",text:n.text}:{kind:"discarded"};return ie(t,e,o,r),f(t,e,r)}function Dc(t,e,n,r){let i=e.currentSession;if(!i||i.id!==n.sessionId)return f(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),f(t,e,r)}function $c(t,e,n,r){let i=e.currentSession;return i&&i.ownerConnectionId===n.connectionId&&ie(t,e,{kind:"lost",reason:"engine-disabled"},r),f(t,e,r)}function So(){return{state:{kind:"starting"},enabled:!1,selectedTarget:null,models:[],catalogStatus:"ok",inFlightDownloads:[],session:null,lastOperationError:null}}function bo(){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 l=0;l<a;l+=r){let u=Math.min(a,l+r),h=0;for(let H=l;H<u;H++){let S=o[H*2],J=(o[H*2+1]<<8|S)<<16>>16,T=J<0?-J:J;T>h&&(h=T)}let E=h/32768,k=Math.min(1,Math.sqrt(E)),M=(u-l)/16e3*1e3,$=k>i?e:n,C=1-Math.exp(-M/Math.max(.001,$));i=i+(k-i)*C}},current(){return i},reset(){i=0}}}function Vc(t){throw new Error(`Unhandled EngineEffect type: ${t.type}`)}var Ro=64,Bt=class{snapshot;internal;host;foundry;mic;unsubscribeConnected;unsubscribeDisconnected;disposed=!1;dispatchDepth=0;levelMeter;constructor(e){this.snapshot=So(),this.internal=bo(),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}),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){g.error(`[VoiceEngine] onSttPartial threw: ${b(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){g.error(`[VoiceEngine] onPcmFrame threw: ${b(r)}`)}}}}submit(e){if(!this.disposed){if(this.dispatchDepth>=Ro){g.error(`[VoiceEngine] dispatch depth exceeded ${Ro} 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(h){g.error(`[VoiceEngine] dispatching effect '${u.type}' threw: ${b(h)}`)}let l=this.snapshot.session?.status==="active"?this.snapshot.session.id:null;r===null&&l!==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"&&g.error(`[VoiceEngine] adapter dispose rejected: ${b(n.reason)}`)}emitEnvelope(e,n){try{this.host.sendTo(n,{type:"sessionAudio",sessionId:e,envelope:this.levelMeter.current()})}catch(r){g.error(`[VoiceEngine] emitEnvelope threw: ${b(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}=e,i;try{i=this.mic.openForSession(n)}catch(u){i=Promise.reject(u instanceof Error?u:new Error(String(u)))}let o=i.then(u=>(u.ok||this.foundry.cancelSttSession(n),u)),a;try{a=this.foundry.openSttSession(n,r)}catch(u){a=Promise.reject(u instanceof Error?u:new Error(String(u)))}let l=a.then(u=>(u.ok||this.mic.closeSession("discard").catch(()=>{}),u));Promise.all([o,l]).then(([u,h])=>{this.disposed||(u.ok&&h.ok?this.submit({type:"internal:sessionWarmed",sessionId:n}):u.ok?h.ok||this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"stt",subreason:h.subreason}}):this.submit({type:"internal:sessionWarmupFailed",sessionId:n,failure:{side:"mic",subreason:u.subreason}}))},u=>{g.error(`[VoiceEngine] warmupSession(${n}) rejected: ${b(u)}`),!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=>{g.error(`[VoiceEngine] commitSession(${n}) drain rejected: ${b(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"broadcast":this.host.broadcast(e.event);break;case"sendTo":this.host.sendTo(e.connectionId,e.event);break;case"logWarning":g.warning(`[VoiceEngine] ${e.message}`);break;default:Vc(e)}}};import{existsSync as Er}from"node:fs";import{dirname as _o,join as wr}from"node:path";import{fileURLToPath as jc}from"node:url";function Io(t){let{importMetaUrl:e,filename:n,label:r}=t,i;try{i=_o(jc(e))}catch(h){throw new Error(`Voice ${r} worker bundle unavailable: cannot resolve module URL (${b(h)}).`)}let o=wr(i,n);if(Er(o))return o;let a=qc(i),l=a?wr(a,"dist-cli",n):void 0;if(l&&Er(l))return l;let u=l?`${o}, ${l}`:o;throw new Error(`Voice ${r} worker bundle not found. Searched: ${u}`)}function qc(t){let e=t;for(;;){if(Er(wr(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 Sr=16*1024;function br(t,e,n=g){let r=Hc(t.level)?t.level:"info",i=typeof t.message=="string"?t.message:Co(t.message);n[r](`[${e} worker] ${Wc(i)}`)}function Hc(t){return t==="debug"||t==="info"||t==="warning"||t==="error"}function Wc(t){return t.length<=Sr?t:`${t.slice(0,Sr)}\u2026 [truncated, ${t.length-Sr} more chars]`}import{Worker as Uc}from"node:worker_threads";var Po=(t,e)=>new Uc(t,e);import{createRequire as zc}from"node:module";import*as we from"node:fs/promises";import*as te from"node:path";import{createHash as Gc}from"node:crypto";import{join as Ze,basename as Ou}from"node:path";import{homedir as kr}from"node:os";function Bc(){return process.env.XDG_CACHE_HOME||Ze(kr(),".cache")}function To(){if(process.platform==="darwin")return Ze(kr(),"Library","Caches","copilot");if(process.platform==="win32"){let t=process.env.LOCALAPPDATA||Ze(kr(),".cache");return Ze(t,"copilot")}return Ze(Bc(),"copilot")}var Jc=1,Kc=".complete";var Oo={"win32-x64":"win-x64","win32-arm64":"win-arm64","linux-x64":"linux-x64","darwin-arm64":"osx-arm64"};function Qc(){return typeof __foundryRequire<"u"&&__foundryRequire||zc(import.meta.url)}var zt;function Yc(){if(zt)return zt;try{let t=Qc()("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 zt=t,zt}catch(t){throw new Error(`Failed to load foundry-local-sdk/deps_versions.json: ${b(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 Xc(t=process.platform){let e=Yc();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 No(t){return t==="win32"?".dll":t==="darwin"?".dylib":".so"}function Zc(t,e){return te.join(t,`Microsoft.AI.Foundry.Local.Core${No(e)}`)}function ed(t){let e=No(t),n=t==="win32"?"":"lib";return[`Microsoft.AI.Foundry.Local.Core${e}`,`${n}onnxruntime${e}`,`${n}onnxruntime-genai${e}`]}function td(t,e=process.platform,n=process.arch){let r=Oo[`${e}-${n}`];if(!r)throw new Error(`Voice mode not supported on ${e}-${n}`);let i=t??process.env.COPILOT_CACHE_HOME??To(),o=Xc(e),a=Gc("sha256").update(JSON.stringify({schema:Jc,artifacts:o})).digest("hex").slice(0,12);return te.join(i,"foundry",a,r)}async function Lo(t={}){let e=t.platform??process.platform,n=t.arch??process.arch,r=`${e}-${n}`,i=Oo[r];if(!i)return{kind:"unsupported-platform",platformKey:r};let o=td(t.cacheRoot,e,n),a=ed(e);if(await xo(o,a))return{kind:"downloaded",location:{corePath:Zc(o,e)}};let l=te.dirname(te.dirname(o)),u;try{u=await we.readdir(l)}catch{return{kind:"not-downloaded"}}let h=te.basename(te.dirname(o));for(let E of u){if(E===h)continue;let k=te.join(l,E,i);if(await xo(k,a))return{kind:"update-available"}}return{kind:"not-downloaded"}}async function xo(t,e){return await Mo(te.join(t,Kc))?(await Promise.all(e.map(r=>Mo(te.join(t,r))))).every(Boolean):!1}async function Mo(t){try{return await we.access(t),!0}catch{return!1}}var Fo=5e3;function Ao(t={}){let{cacheRoot:e,workerFactory:n=Po,workerScriptPath:r,inspectImpl:i=Lo}=t,o,a;return{async inspect(){if(a&&Date.now()<a.expiry)return a.result;let l=await i({cacheRoot:e});return a={result:l,expiry:Date.now()+Fo},l},install(l){if(o)return o;a=void 0;let u=nd({cacheRoot:e,workerFactory:n,workerScriptPath:r??Io({importMetaUrl:import.meta.url,filename:"voice-installer.worker.js",label:"installer"}),onProgress:l}).then(h=>(a={result:{kind:"downloaded",location:h},expiry:Date.now()+Fo},h)).catch(h=>{throw o=void 0,a=void 0,h});return o=u,u}}}function nd(t){return new Promise((e,n)=>{let r;try{r=t.workerFactory(t.workerScriptPath,{workerData:{cacheRoot:t.cacheRoot}})}catch(a){n(jt(a));return}let i=!1,o=a=>{i||(i=!0,r.terminate().catch(l=>{g.warning(`[voice-runtime] installer worker terminate failed: ${b(l)}`)}),a())};r.on("message",a=>{if(a==null||typeof a!="object"){g.warning("[voice-runtime] installer worker posted a malformed message; ignoring");return}let l=a;if(l.kind==="log"){br(l,"Installer");return}if(l.kind==="download-started"){if(!t.onProgress)return;try{t.onProgress({kind:"indeterminate"})}catch(u){g.warning(`[voice-runtime] installer onProgress threw: ${b(u)}`)}return}if(l.kind==="ok"){o(()=>e(l.location));return}if(l.kind==="error"){o(()=>n(gr(l.error)));return}}),r.on("error",a=>{o(()=>n(jt(a)))}),r.on("exit",a=>{o(()=>n(new Error(`Voice installer worker exited unexpectedly with code ${a}.`)))})})}import{readFileSync as rd,unlinkSync as id,writeFileSync as od}from"node:fs";function Do(t,e){od(t,`${e}
`,{encoding:"utf8"})}function $o(t){let e;try{e=rd(t,"utf8")}catch{return null}let n=Number(e.trim());return!Number.isSafeInteger(n)||n<=0?null:n}function Vo(t){try{id(t)}catch{}}var Kt=nt(Dt(),1);import{unlinkSync as sd}from"node:fs";import{createConnection as ad,createServer as cd}from"node:net";var jo=nt(Dt(),1),Gt=class extends jo.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 Jt=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 dd(this.address,n=>this.handleSocket(n));return e===null?"lost":(this.server=e,"bound")}async stop(){if(this.stopped)return;this.stopped=!0,g.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,Kt.createMessageConnection)(new Kt.SocketMessageReader(e),new Gt(e));try{let r=this.host.registerConnection({connection:n});g.info(`voice server: client connected id=${r.connectionId} (clients=${this.host.connectionCount})`)}catch(r){g.error(`voice server: registerConnection failed: ${r.message}`);try{n.dispose()}catch{}e.destroy()}}};function dd(t,e){return new Promise((n,r)=>{let i=o=>{let a=cd(e),l=u=>{if(a.removeAllListeners(),u.code==="EADDRINUSE"&&o&&process.platform!=="win32"){let h=ad(t);h.once("connect",()=>{h.destroy(),n(null)}),h.once("error",E=>{let k=E.code;if(k==="ECONNREFUSED"||k==="ENOENT"){try{sd(t)}catch{}i(!1)}else n(null)});return}if(u.code==="EADDRINUSE"||u.code==="EEXIST"){n(null);return}r(u)};a.once("error",l),a.listen(t,()=>{a.removeListener("error",l),n(a)})};i(!0)})}import{createHash as hd}from"node:crypto";import{mkdirSync as Ho}from"node:fs";import{homedir as Wo,tmpdir as gd}from"node:os";import{join as He}from"node:path";import{readFileSync as ld}from"fs";import{dirname as ud,join as Rr}from"path";import{fileURLToPath as pd}from"url";var et=null;function qo(){return fd().version}function fd(){if(et!==null)return et;try{let t=pd(import.meta.url),e=ud(t),n=[Rr(e,"package.json"),Rr(e,"../package.json"),Rr(e,"../../package.json")];for(let i of n)try{let o=JSON.parse(ld(i,"utf8")),a={name:o.name||"unknown",version:o.version||"unknown",buildMetadata:o.buildMetadata};return et=a,a}catch{continue}let r={name:"unknown",version:"unknown"};return et=r,r}catch{let e={name:"unknown",version:"unknown"};return et=e,e}}var md=8,Qt="copilot-voice",vd=100;function Uo(t={}){let e=t.platform??process.platform,n=t.env??process.env,r=t.tmpDir??gd(),i=t.cliVersion??qo();if(e==="win32"){let E=Yt(n.USERPROFILE??n.HOMEPATH??n.USERNAME??t.homeDir??Wo()??"anon"),k=Yt(`${i}|${E}`),M=`\\\\.\\pipe\\${Qt}-${k}`,$=He(r,Qt);return Ho($,{recursive:!0}),{address:M,pidFile:He($,`${k}.pid`),endpointHash:k}}let o=Yt(i),a=n.XDG_RUNTIME_DIR,l=Yt(n.HOME??t.homeDir??Wo()??n.USER??"anon"),u=a?He(a,Qt):He(r,`${Qt}-${l}`);Ho(u,{recursive:!0,mode:448});let h=He(u,`${o}.sock`);return h.length>vd&&g.warning(`voice server: Unix socket path is ${h.length} bytes (macOS limit is 104): ${h}`),{address:h,pidFile:He(u,`${o}.pid`),endpointHash:o}}function Yt(t){return hd("sha256").update(t).digest("hex").slice(0,md)}var zo="COPILOT_VOICE_SERVER_BOOT";function Go(t){if(!t)return{};let e;try{e=JSON.parse(t)}catch{return{}}if(!Bo(e))return{};let n=e.voice;if(!Bo(n))return{};let r={};return typeof n.enabled=="boolean"&&(r.enabled=n.enabled),typeof n.selectedModel=="string"&&n.selectedModel.length>0&&(r.selectedModel=n.selectedModel),Object.keys(r).length>0?{voice:r}:{}}function Bo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ed=10,Jo=1,Ko=6e4;async function Cp(){let t=Uo(),e=wd(t.endpointHash),n=new gt(e);g.setLogWriter(n),g.info(`voice server: boot pid=${process.pid} endpoint=${t.address}`);let r=Ao(),i=new Vt,o=new Bt({host:i,foundryFactory:C=>new qt({events:C,installer:r}),micFactory:C=>new Ht({events:C}),bootSettings:Go(process.env[zo])});i.setSubmit(C=>o.submit(C));let a=!1,l=null,u=()=>{l===null&&(l=setTimeout(()=>{l=null,g.info("voice server: idle timeout, shutting down"),$("idle timeout").catch(()=>{})},Ko))},h=()=>{l!==null&&(clearTimeout(l),l=null)};i.onClientConnected(()=>h()),i.onClientDisconnected(()=>{a||i.connectionCount===0&&u()}),u();let E=new Jt({host:i,address:t.address}),k;try{k=await E.start()}catch(C){g.error(`voice server: bind threw: ${C.stack??String(C)}`),await n.writeQueue,process.exit(Jo)}k==="lost"&&(g.info(`voice server: bind-loser, another voice server owns ${t.address}`),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(Ed));try{Do(t.pidFile,process.pid)}catch(C){g.error(`voice server: writeServerPidFile failed: ${C.message}`),await E.stop(),await o.dispose().catch(()=>{}),await n.writeQueue,process.exit(Jo)}let M=()=>{$o(t.pidFile)===process.pid&&Vo(t.pidFile)},$=async C=>{if(a)return;a=!0,h(),g.info(`voice server: shutdown (${C})`);let H=E.stop().catch(S=>{g.error(`voice server: server.stop failed: ${S.message}`)});i.dispose(),await H,await o.dispose().catch(S=>{g.error(`voice server: engine.dispose failed: ${S.message}`)}),M(),await n.writeQueue.catch(()=>{}),process.exit(0)};for(let C of["SIGINT","SIGTERM","SIGHUP"])process.on(C,()=>{$(`signal ${C}`).catch(()=>{})});process.on("uncaughtException",C=>{g.error(`voice server: uncaughtException: ${C.stack??String(C)}`),$("uncaughtException").catch(()=>{})}),process.on("unhandledRejection",C=>{g.error(`voice server: unhandledRejection: ${String(C)}`)}),process.on("exit",()=>{M()}),g.info(`voice server: ready (idle timer armed ${Ko}ms)`)}function wd(t){return yd(Si(void 0,"state"),"logs",`voice-server-${t}.log`)}export{Cp as runVoiceServer};
